Merge pull request #1 from Dasemu/development

Development
This commit is contained in:
dasemu authored and GitHub committed 2026-10-15 11:28:27 +02:00
commit 5c7cd31037
31 files changed
+1659 -120

No files matched your search

+12 -8
View File
@@ -5,12 +5,14 @@ X GeoBlock is a Manifest V3 browser extension for Chromium and Firefox. While yo
## Features
- Processes posts already on the page and posts loaded by infinite scrolling.
- Performs authenticated About-page requests in the extension service worker.
- Caches account results locally for a configurable period (seven days by default).
- Uses X's authenticated `AboutAccountQuery` from the current page session. HTML parsing and an invisible same-origin `/about` frame remain as fallbacks, without opening tabs or windows.
- Caches account results locally for 30 days, with manual clearing available.
- Coalesces duplicate lookups and spaces network requests to reduce load on X.
- Skips followed accounts.
- Provides a configurable country blacklist, an enable switch, and optional hidden-post placeholders.
- Stores all settings and lookup results in browser extension storage. No data is sent to third parties.
- Skips followed accounts by default, with a setting to apply the blocklist to them as well.
- Provides a searchable country and region checklist with flags, an enable switch, and optional hidden-post placeholders.
- Includes opt-in debug logging for every lookup and filtering decision.
- By default, stores all settings and lookup results only in browser extension storage. No data is sent to third parties unless cloud contribution is explicitly enabled.
- Uses the project Cloudflare Worker + D1 collaborative cache at `x-geoblock-cache.dariosevilla.es`, with signed contributions and three-installation consensus. Contributions are enabled by default and can be disabled in settings.
## Install from source in Chromium
@@ -18,7 +20,7 @@ X GeoBlock is a Manifest V3 browser extension for Chromium and Firefox. While yo
2. Enable **Developer mode**.
3. Select **Load unpacked** and choose this repository directory.
4. Sign in to `https://x.com` and browse normally.
5. Open the extension settings to review the default blacklist.
5. Open the extension settings and select the countries you want to block. No country is selected by default.
No build step or dependency installation is required.
@@ -41,19 +43,21 @@ npm run check
npm run build
```
After editing a file, reload the extension and refresh the X tab. See [Architecture](docs/architecture.md), [Releases](docs/releases.md), [Privacy](docs/privacy.md), and [Contributing](CONTRIBUTING.md).
After editing a file, reload the extension and refresh the X tab. See [Architecture](docs/architecture.md), [Cloud cache](docs/cloud-cache.md), [Releases](docs/releases.md), [Privacy](docs/privacy.md), and [Contributing](CONTRIBUTING.md).
## Limitations
X does not publish a stable API for the country shown on the About page. The extension parses X's HTML and embedded page data, so a markup change can temporarily prevent detection. An unknown country leaves the post visible. Requests use your existing X session and are subject to X's rate limits.
The default blacklist is an editable starting point: Belarus, China, Iran, North Korea, and Russia. Inclusion is a local user preference and does not assert anything about individual account holders.
The location picker contains the ISO 3166-1 countries, plus Kosovo, using English CLDR display names. It also includes the broader English region labels exposed by X, such as `West Asia`, alongside country labels such as `United Kingdom`. Inclusion is a local user preference and does not assert anything about individual account holders.
## Permissions
- `storage`: saves settings and the local user cache.
- `offscreen`: parses returned HTML without opening visible tabs.
- `declarativeNetRequestWithHostAccess`: removes anti-framing response headers only from `x.com/*/about` subframe requests so the fallback can render.
- `https://x.com/*`: reads About pages and runs the feed filter on X.
- `https://x-geoblock-cache.dariosevilla.es/*`: looks up confirmed shared location results and submits observations only when contribution is enabled.
## License
+187 -41
View File
@@ -1,20 +1,34 @@
if (typeof XGeoConfig === "undefined") importScripts("lib/config.js");
if (typeof XGeoConfig === "undefined") importScripts("lib/config.js", "lib/cloud-cache.js");
const extensionApi = globalThis.browser || chrome;
const CACHE_KEY = "userCache";
const DEFAULTS_MIGRATION_KEY = "defaultsV2Applied";
const LOCAL_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const activeRequests = new Map();
let queueTail = Promise.resolve();
const pendingFrameLookups = new Map();
const requestQueue = [];
let runningRequests = 0;
let lastRequestAt = 0;
const MAX_CONCURRENT_REQUESTS = 3;
extensionApi.runtime.onInstalled.addListener(async () => {
const current = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS);
await extensionApi.storage.sync.set(current);
const current = await extensionApi.storage.sync.get(null);
const local = await extensionApi.storage.local.get({ [DEFAULTS_MIGRATION_KEY]: false });
const next = { ...XGeoConfig.DEFAULT_SETTINGS, ...current, cloudCacheEndpoint: XGeoConfig.CLOUD_CACHE_ENDPOINT };
if (!local[DEFAULTS_MIGRATION_KEY]) {
next.showPlaceholder = true;
next.contributeCloudCache = true;
await extensionApi.storage.local.set({ [DEFAULTS_MIGRATION_KEY]: true });
}
await extensionApi.storage.sync.set(next);
});
extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type === "lookup-user") {
lookupUser(message.username).then(sendResponse).catch((error) => {
lookupUser(message.username, message.followingHint, sender?.tab?.id).then(sendResponse).catch(async (error) => {
const { debugMode } = await extensionApi.storage.sync.get({ debugMode: false });
emitDebug(sender?.tab?.id, debugMode, "Lookup failed", { username: message.username, error: error.message });
sendResponse({ ok: false, error: error.message });
});
return true;
@@ -23,6 +37,11 @@ extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
extensionApi.storage.local.remove(CACHE_KEY).then(() => sendResponse({ ok: true }));
return true;
}
if (message?.type === "about-page-result") {
finishFrameLookup(message, sender?.tab?.id);
sendResponse({ ok: true });
return false;
}
return false;
});
@@ -30,31 +49,86 @@ function validUsername(username) {
return typeof username === "string" && /^[A-Za-z0-9_]{1,15}$/.test(username);
}
async function lookupUser(username) {
async function lookupUser(username, followingHint = null, tabId = null) {
if (!validUsername(username)) return { ok: false, error: "Invalid username" };
const key = username.toLowerCase();
if (activeRequests.has(key)) return activeRequests.get(key);
const promise = lookupUserInternal(username, key).finally(() => activeRequests.delete(key));
const promise = lookupUserInternal(username, key, followingHint, tabId).finally(() => activeRequests.delete(key));
activeRequests.set(key, promise);
return promise;
}
async function lookupUserInternal(username, key) {
async function lookupUserInternal(username, key, followingHint, tabId) {
const settings = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS);
settings.cloudCacheEndpoint = XGeoConfig.CLOUD_CACHE_ENDPOINT;
emitDebug(tabId, settings.debugMode, "Lookup started", { username, followingHint });
const stored = await extensionApi.storage.local.get(CACHE_KEY);
const cache = stored[CACHE_KEY] || {};
const cached = cache[key];
const ttl = Math.max(1, Number(settings.cacheTtlHours) || 168) * 60 * 60 * 1000;
if (cached && Date.now() - cached.checkedAt < ttl) {
const cacheFresh = cached && Date.now() - Number(cached.checkedAt || 0) < LOCAL_CACHE_TTL_MS;
if (cacheFresh && (cached.country || cached.following === true)) {
emitDebug(tabId, settings.debugMode, "Local cache hit", { username, country: cached.country, following: cached.following, source: cached.source || "direct" });
return decision(cached, settings, true);
}
if (cached) {
emitDebug(tabId, settings.debugMode, "Local cache expired or invalid", { username, checkedAt: cached.checkedAt || null });
delete cache[key];
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
} else emitDebug(tabId, settings.debugMode, "Local cache miss", { username });
const result = await enqueue(() => fetchAbout(username));
cache[key] = { ...result, checkedAt: Date.now() };
pruneCache(cache);
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
return decision(cache[key], settings, false);
if (followingHint === true && settings.skipFollowed) {
emitDebug(tabId, settings.debugMode, "Author is followed; allowing post", { username });
return decision({ country: null, following: true }, settings, false);
}
if ((followingHint !== true || !settings.skipFollowed) && settings.cloudCacheEndpoint) {
try {
emitDebug(tabId, settings.debugMode, "Cloud cache lookup", { username, endpoint: settings.cloudCacheEndpoint });
const cloud = await XGeoCloud.lookup(settings.cloudCacheEndpoint, [key]);
const hit = cloud.get(key);
if (hit?.status === "confirmed" && hit.location) {
emitDebug(tabId, settings.debugMode, "Cloud cache hit", { username, country: hit.location, confidence: hit.confidence, confirmations: hit.confirmations });
const record = { country: hit.location, following: followingHint === true, checkedAt: Date.now(), source: "cloud" };
cache[key] = record;
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
return decision(record, settings, false);
}
emitDebug(tabId, settings.debugMode, "Cloud cache miss", { username });
} catch (error) {
emitDebug(tabId, settings.debugMode, "Cloud cache error; falling back to X", { username, error: error.message });
// Cloud cache failure must never prevent the direct X lookup.
}
}
emitDebug(tabId, settings.debugMode, "Direct X lookup started", { username });
const lookupLog = (event, data = {}) => emitDebug(tabId, settings.debugMode, event, { username, ...data });
const result = await enqueue(() => fetchAbout(username, lookupLog, tabId));
const record = { ...result, following: result.following ?? followingHint, checkedAt: Date.now() };
emitDebug(tabId, settings.debugMode, "Direct X lookup completed", { username, country: record.country, following: record.following });
if (record.country || record.following === true) {
cache[key] = record;
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
} else if (cached) {
delete cache[key];
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
}
if (record.country && settings.contributeCloudCache && settings.cloudCacheEndpoint) {
emitDebug(tabId, settings.debugMode, "Cloud contribution queued", { username, country: record.country });
XGeoCloud.report(settings.cloudCacheEndpoint, key, record.country, extensionApi.runtime.getManifest().version)
.then(() => emitDebug(tabId, settings.debugMode, "Cloud contribution accepted", { username }))
.catch((error) => emitDebug(tabId, settings.debugMode, "Cloud contribution failed", { username, error: error.message }));
}
const finalDecision = decision(record, settings, false);
emitDebug(tabId, settings.debugMode, "Decision", { username, country: finalDecision.country, following: finalDecision.following, blocked: finalDecision.blocked });
return finalDecision;
}
function emitDebug(tabId, enabled, event, data = {}) {
if (!enabled) return;
console.info("[X GeoBlock]", event, data);
if (Number.isInteger(tabId)) {
extensionApi.tabs.sendMessage(tabId, { type: "debug-event", event, data }).catch(() => {});
}
}
function decision(record, settings, cached) {
@@ -62,31 +136,71 @@ function decision(record, settings, cached) {
ok: true,
country: record.country,
following: record.following === true,
blocked: record.following !== true && XGeoConfig.isBlacklisted(record.country, settings.blacklist),
blocked: XGeoConfig.shouldBlock(record.country, settings.blacklist, record.following, settings.skipFollowed),
cached
};
}
function enqueue(task) {
const run = queueTail.then(async () => {
const delay = Math.max(0, 350 - (Date.now() - lastRequestAt));
if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
lastRequestAt = Date.now();
return task();
return new Promise((resolve, reject) => {
requestQueue.push({ task, resolve, reject });
drainQueue();
});
queueTail = run.catch(() => {});
return run;
}
async function fetchAbout(username) {
const response = await fetch(`https://x.com/${encodeURIComponent(username)}/about`, {
credentials: "include",
headers: { "Accept-Language": "en-US,en;q=0.9" },
redirect: "follow"
});
if (!response.ok) throw new Error(`X returned HTTP ${response.status}`);
const html = await response.text();
if (/\/i\/flow\/login/i.test(response.url)) throw new Error("X authentication is required");
function drainQueue() {
while (runningRequests < MAX_CONCURRENT_REQUESTS && requestQueue.length) {
const entry = requestQueue.shift();
runningRequests += 1;
const scheduledAt = Math.max(Date.now(), lastRequestAt + 350);
lastRequestAt = scheduledAt;
const delay = scheduledAt - Date.now();
setTimeout(async () => {
try { entry.resolve(await entry.task()); }
catch (error) { entry.reject(error); }
finally {
runningRequests -= 1;
drainQueue();
}
}, delay);
}
}
async function fetchAbout(username, log = () => {}, tabId = null) {
try {
const response = await fetch(`https://x.com/${encodeURIComponent(username)}/about`, {
credentials: "include",
headers: { "Accept-Language": "en-US,en;q=0.9" },
redirect: "follow"
});
log("Background HTTP response", { status: response.status, finalUrl: response.url });
if (response.ok && !/\/i\/flow\/login/i.test(response.url)) {
const parsed = await parseFetchedHtml(await response.text(), username);
log("Background HTML parsed", { country: parsed?.country || null, following: parsed?.following ?? null });
if (parsed?.country) return parsed;
}
} catch (error) {
log("Background HTTP lookup failed", { error: error.message });
// X frequently serves an incomplete SPA shell to extension fetches.
}
if (Number.isInteger(tabId)) {
try {
log("Authenticated AboutAccountQuery started");
const apiResult = await extensionApi.tabs.sendMessage(tabId, { type: "lookup-about-api", username });
log("Authenticated AboutAccountQuery completed", { country: apiResult?.country || null });
if (apiResult?.ok && apiResult.country) {
return { country: apiResult.country, following: null, profileLocation: null, source: "x-api" };
}
if (apiResult?.error) log("Authenticated AboutAccountQuery failed", { error: apiResult.error });
} catch (error) {
log("Authenticated AboutAccountQuery failed", { error: error.message });
}
}
log("Falling back to same-origin hidden frame");
return lookupViaPageFrame(username, tabId, log);
}
async function parseFetchedHtml(html, username) {
if (typeof DOMParser !== "undefined" && typeof XGeoParser !== "undefined") {
const document = new DOMParser().parseFromString(html, "text/html");
return XGeoParser.parseAboutDocument(document, username);
@@ -95,6 +209,45 @@ async function fetchAbout(username) {
return extensionApi.runtime.sendMessage({ type: "parse-about-html", html, username });
}
async function lookupViaPageFrame(username, tabId, log = () => {}) {
if (!Number.isInteger(tabId)) throw new Error("No X tab is available for the rendered About lookup");
const key = username.toLowerCase();
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingFrameLookups.delete(key);
removePageFrame(tabId, key);
log("Same-origin hidden frame timed out");
reject(new Error(`Timed out while rendering @${username}'s About page`));
}, 25000);
pendingFrameLookups.set(key, { resolve, reject, timer, log, tabId });
extensionApi.tabs.sendMessage(tabId, { type: "create-about-frame", username })
.then(() => log("Same-origin hidden frame created")).catch((error) => {
clearTimeout(timer);
pendingFrameLookups.delete(key);
reject(error);
});
});
}
function finishFrameLookup(message, tabId) {
const key = String(message.username).toLowerCase();
const pending = pendingFrameLookups.get(key);
if (!pending || pending.tabId !== tabId) return;
pending.log("Rendered About page reported a result", { country: message.country || null, following: message.following ?? null });
clearTimeout(pending.timer);
pendingFrameLookups.delete(key);
pending.resolve({
country: message.country || null,
following: message.following === true,
profileLocation: message.profileLocation || null
});
removePageFrame(tabId, key);
}
function removePageFrame(tabId, username) {
extensionApi.tabs.sendMessage(tabId, { type: "remove-about-frame", username }).catch(() => {});
}
async function ensureOffscreenDocument() {
const url = extensionApi.runtime.getURL("offscreen/offscreen.html");
const clients = await self.clients.matchAll();
@@ -102,13 +255,6 @@ async function ensureOffscreenDocument() {
await extensionApi.offscreen.createDocument({
url: "offscreen/offscreen.html",
reasons: ["DOM_PARSER"],
justification: "Parse the account About page without opening a visible tab."
justification: "Parse account About HTML without opening a visible page."
});
}
function pruneCache(cache) {
const entries = Object.entries(cache);
if (entries.length <= 2000) return;
entries.sort((a, b) => (b[1].checkedAt || 0) - (a[1].checkedAt || 0));
for (const [key] of entries.slice(1500)) delete cache[key];
}
+2 -3
View File
@@ -1,9 +1,8 @@
.x-geoblock-hidden:is(article), .x-geoblock-hidden > article { display: none !important; }
.x-geoblock-hidden.x-geoblock-revealed:is(article), .x-geoblock-hidden.x-geoblock-revealed > article { display: block !important; }
.x-geoblock-hidden:not(.x-geoblock-revealed) > :not(.x-geoblock-placeholder) { display: none !important; }
.x-geoblock-placeholder {
width: 100%; padding: 14px 16px; border: 0; border-bottom: 1px solid rgb(47, 51, 54);
background: transparent; color: rgb(113, 118, 123); font: 14px/20px system-ui, sans-serif;
cursor: pointer; text-align: center;
}
.x-geoblock-hidden:not(.x-geoblock-revealed) > .x-geoblock-placeholder { display: block; }
.x-geoblock-hidden:not(.x-geoblock-revealed) > .x-geoblock-placeholder { display: block !important; }
.x-geoblock-hidden.x-geoblock-revealed > .x-geoblock-placeholder { display: block; opacity: .7; }
+160 -4
View File
@@ -3,28 +3,75 @@
const extensionApi = globalThis.browser || chrome;
const processed = new WeakSet();
const hiddenByUser = new Map();
let settings = { enabled: true, showPlaceholder: false };
let settings = { enabled: true, showPlaceholder: false, debugMode: false };
let scanQueued = false;
initialize();
async function initialize() {
settings = await extensionApi.storage.sync.get({ enabled: true, showPlaceholder: false });
const aboutMatch = location.pathname.match(/^\/([A-Za-z0-9_]{1,15})\/about\/?$/);
if (aboutMatch) {
reportRenderedAboutPage(aboutMatch[1]);
return;
}
if (window.top !== window) return;
settings = await extensionApi.storage.sync.get({ enabled: true, showPlaceholder: false, debugMode: false });
debug("Content script initialized", { url: location.href });
scan(document);
new MutationObserver((mutations) => {
if (mutations.some((mutation) => mutation.addedNodes.length)) scheduleScan();
}).observe(document.documentElement, { childList: true, subtree: true });
}
function reportRenderedAboutPage(username) {
const startedAt = Date.now();
const inspect = () => {
const result = XGeoParser.parseAboutDocument(document, username);
if (result.country) {
extensionApi.runtime.sendMessage({ type: "about-page-result", username, ...result }).catch(() => {});
return true;
}
return Date.now() - startedAt >= 24000;
};
if (inspect()) return;
const observer = new MutationObserver(() => {
if (inspect()) observer.disconnect();
});
observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true });
setTimeout(() => observer.disconnect(), 24500);
}
extensionApi.storage.onChanged.addListener((changes, area) => {
if (area !== "sync") return;
if (changes.enabled) settings.enabled = changes.enabled.newValue;
if (changes.showPlaceholder) settings.showPlaceholder = changes.showPlaceholder.newValue;
if (changes.debugMode) settings.debugMode = changes.debugMode.newValue;
restoreAll();
document.querySelectorAll("article").forEach((article) => processed.delete(article));
if (settings.enabled) scheduleScan();
});
extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type === "debug-event" && settings.debugMode) {
console.info("[X GeoBlock]", message.event, message.data || {});
}
if (message?.type === "create-about-frame") {
createAboutFrame(message.username);
sendResponse({ ok: true });
return false;
}
if (message?.type === "lookup-about-api") {
lookupAboutApi(message.username).then(sendResponse);
return true;
}
if (message?.type === "remove-about-frame") {
removeAboutFrame(message.username);
sendResponse({ ok: true });
return false;
}
return false;
});
function scheduleScan() {
if (scanQueued) return;
scanQueued = true;
@@ -44,11 +91,14 @@ async function processArticle(article) {
if (processed.has(article)) return;
const identity = getTweetIdentity(article);
if (!identity) return;
debug("Post author detected", identity);
processed.add(article);
article.dataset.xGeoBlockState = "checking";
try {
const result = await extensionApi.runtime.sendMessage({ type: "lookup-user", username: identity.username });
const followingHint = await getFollowingHint(article, identity.username);
debug("Following hint resolved", { username: identity.username, followingHint });
const result = await extensionApi.runtime.sendMessage({ type: "lookup-user", username: identity.username, followingHint });
if (!article.isConnected || !result?.ok) {
delete article.dataset.xGeoBlockState;
return;
@@ -56,11 +106,45 @@ async function processArticle(article) {
article.dataset.xGeoBlockCountry = result.country || "unknown";
if (result.blocked) hideArticle(article, identity.username, result.country);
else article.dataset.xGeoBlockState = result.following ? "followed" : "allowed";
} catch (_) {
debug("Post decision applied", { username: identity.username, ...result });
} catch (error) {
debug("Post lookup failed", { username: identity.username, error: error.message });
delete article.dataset.xGeoBlockState;
}
}
function getFollowingHint(article, username) {
const profileHint = getProfileFollowingHint(username);
if (profileHint !== null) return Promise.resolve(profileHint);
return new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
article.removeEventListener("x-geoblock-following-response", finish);
const value = article.dataset.xGeoBlockFollowing;
resolve(value === "true" ? true : value === "false" ? false : null);
};
article.dataset.xGeoBlockRequestUser = username;
article.addEventListener("x-geoblock-following-response", finish, { once: true });
article.dispatchEvent(new Event("x-geoblock-following-request", { bubbles: true }));
setTimeout(finish, 150);
});
}
function getProfileFollowingHint(username) {
const profile = location.pathname.match(/^\/([A-Za-z0-9_]{1,15})(?:\/|$)/)?.[1];
if (!profile || profile.toLowerCase() !== username.toLowerCase()) return null;
const column = document.querySelector('[data-testid="primaryColumn"]') || document;
if (column.querySelector('[data-testid$="-unfollow"]')) return true;
if (column.querySelector('[data-testid$="-follow"]')) return false;
const buttons = Array.from(column.querySelectorAll("button, [role=button]"));
const labels = buttons.slice(0, 30).map((button) => `${button.textContent || ""} ${button.getAttribute("aria-label") || ""}`.trim().toLowerCase());
if (labels.some((label) => /^(following|siguiendo|abonné|abonniert|seguindo|seguiti)(\s|$)/.test(label))) return true;
if (labels.some((label) => /^(follow|seguir|s’abonner|folgen|seguir)(\s|$)/.test(label))) return false;
return null;
}
function getTweetIdentity(article) {
const links = article.querySelectorAll('a[href*="/status/"]');
for (const link of links) {
@@ -71,6 +155,7 @@ function getTweetIdentity(article) {
}
function hideArticle(article, username, country) {
debug("Hiding post", { username, country });
article.dataset.xGeoBlockState = "blocked";
const container = article.closest('[data-testid="cellInnerDiv"]') || article;
container.classList.add("x-geoblock-hidden");
@@ -88,6 +173,77 @@ function hideArticle(article, username, country) {
}
}
function debug(event, data = {}) {
if (settings.debugMode) console.info("[X GeoBlock]", event, data);
}
function createAboutFrame(username) {
removeAboutFrame(username);
const frame = document.createElement("iframe");
frame.dataset.xGeoBlockAboutUser = username.toLowerCase();
frame.setAttribute("aria-hidden", "true");
frame.tabIndex = -1;
frame.style.cssText = "position:fixed!important;width:1px!important;height:1px!important;opacity:0!important;pointer-events:none!important;left:-10000px!important;top:-10000px!important;border:0!important";
frame.src = `https://x.com/${encodeURIComponent(username)}/about`;
frame.addEventListener("load", () => inspectAboutFrame(frame, username), { once: true });
document.documentElement.append(frame);
debug("Hidden About frame appended", { username });
}
function lookupAboutApi(username) {
return new Promise((resolve) => {
let timer;
const request = document.createElement("span");
request.hidden = true;
request.dataset.xGeoBlockUsername = username;
const finish = () => {
clearTimeout(timer);
const raw = request.dataset.xGeoBlockResult;
const error = request.dataset.xGeoBlockError;
request.remove();
if (raw) {
try { resolve({ ok: true, ...JSON.parse(raw) }); }
catch (parseError) { resolve({ ok: false, error: parseError.message }); }
} else resolve({ ok: false, error: error || "AboutAccountQuery did not respond" });
};
request.addEventListener("x-geoblock-about-api-response", finish, { once: true });
document.documentElement.append(request);
request.dispatchEvent(new Event("x-geoblock-about-api-request", { bubbles: true }));
timer = setTimeout(finish, 10000);
});
}
function inspectAboutFrame(frame, username) {
const startedAt = Date.now();
const timer = setInterval(() => {
if (!frame.isConnected) return clearInterval(timer);
try {
const frameDocument = frame.contentDocument;
if (!frameDocument?.documentElement) {
if (Date.now() - startedAt > 24000) {
clearInterval(timer);
debug("Hidden About frame document remained unavailable", { username });
}
return;
}
const result = XGeoParser.parseAboutDocument(frameDocument, username);
if (result.country) {
clearInterval(timer);
debug("Hidden About frame parsed", { username, country: result.country, following: result.following });
extensionApi.runtime.sendMessage({ type: "about-page-result", username, ...result }).catch(() => {});
} else if (Date.now() - startedAt > 24000) clearInterval(timer);
} catch (error) {
clearInterval(timer);
debug("Hidden About frame cannot be inspected", { username, error: error.message });
}
}, 250);
}
function removeAboutFrame(username) {
const key = String(username).toLowerCase();
document.querySelector(`iframe[data-x-geo-block-about-user="${CSS.escape(key)}"]`)?.remove();
}
function restoreAll() {
document.querySelectorAll(".x-geoblock-hidden").forEach((node) => {
node.classList.remove("x-geoblock-hidden", "x-geoblock-revealed");
+5 -5
View File
@@ -4,12 +4,12 @@
1. The content script observes X's timeline and extracts an author from each canonical `/user/status/id` link.
2. The service worker checks the local cache and coalesces concurrent lookups for the same username.
3. On a cache miss, the background process requests `https://x.com/<user>/about` with the browser's existing X session.
4. Chromium passes the HTML to an offscreen document; Firefox parses it in its background page. The parser locates the location-pin row for the account country and also inspects embedded user data for the `following` relationship.
3. On a cache miss, the extension first parses `https://x.com/<user>/about`, then asks the current X page to run the authenticated `AboutAccountQuery` and reads `about_profile.account_based_in`.
4. If both direct methods fail, an invisible same-origin frame renders the `/about` URL. A static network rule removes CSP and `X-Frame-Options` only from matching `/about` subframe responses. The content script reads the location row and immediately destroys the frame. This does not create a browser tab or window.
5. The worker caches the result and compares the country with the configured blacklist.
6. The content script hides the post only when the country matches and the account is not followed.
6. The content script hides the post when the country matches. Followed accounts are exempt by default; the user can disable that exemption.
Failed or ambiguous lookups fail open: the post remains visible. The cache is limited to 2,000 entries and pruned to the 1,500 most recently checked entries when the limit is exceeded.
Failed or ambiguous lookups fail open: the post remains visible. Empty results are never cached. Successful local and cloud lookups expire after 30 days. The user can clear the entire cache from the settings page at any time.
## Browser components
@@ -22,4 +22,4 @@ Failed or ambiguous lookups fail open: the post remains visible. The cache is li
## Compatibility
The Chromium package requires Chrome 109 or newer. Firefox 109 or newer uses a browser-specific background-page manifest and does not require the Chromium offscreen-document API.
The Chromium package requires Chrome 109 or newer. Firefox 113 or newer uses a browser-specific background-page manifest and does not require the Chromium offscreen-document API.
+28
View File
@@ -0,0 +1,28 @@
# Collaborative cloud cache
The cloud cache uses the Cloudflare Worker and D1 schema in `worker/`. Extension builds use `https://x-geoblock-cache.dariosevilla.es` for reads. Contributing observations is enabled by default and can be disabled in settings.
## Data flow
1. Local cache results always win.
2. When the page's own React data confirms that an author is not followed, the extension asks the Worker for a confirmed location using a SHA-256 username hash.
3. A confirmed cloud hit can be used immediately. Pending, conflicting, stale, unavailable, or malformed results fall back to a direct X lookup.
4. A direct successful lookup is stored locally. If contribution is enabled, the extension signs and submits the username hash, location, observation time, and parser version.
Following relationships, blacklist entries, post contents, URLs visited, and raw usernames are not uploaded. Username hashing reduces accidental disclosure but is not anonymity because public handles can be enumerated and hashed.
## Cryptographic boundary
Each installation creates an ECDSA P-256 key pair with a non-exportable private key in IndexedDB. Reports include a timestamp and one-time nonce and are signed over the HTTP method, path, timestamp, nonce, and body hash. D1 rejects replayed nonces.
This proves continuity of an installation and prevents report tampering. It cannot prove that a request came from the official extension: an attacker can reproduce public extension behavior and register another key. Embedded API keys, extension origins, user-agent strings, and CORS are not authentication. Consensus and rate limits provide the actual abuse resistance.
## Freshness and consensus
- Three distinct installations must agree within seven days.
- Tied observations become `conflict` and are never returned for blocking.
- Confirmed entries are served for 30 days.
- Raw observations are retained for 90 days.
- Local cache entries expire after 30 days or when the user clears them.
These values are configured in `worker/wrangler.toml`.
+3 -1
View File
@@ -2,6 +2,8 @@
X GeoBlock does not collect analytics, transmit browsing data to third parties, or operate a remote server.
The extension reads public account About pages from `x.com` using the X session already present in your browser. It stores usernames, detected countries, following status, and lookup timestamps in local extension storage. Settings use synchronized extension storage when browser sync is enabled. You can clear the lookup cache at any time from the settings page or remove all extension data by uninstalling the extension.
The extension reads public account About pages from `x.com` using the X session already present in your browser. It stores usernames, detected countries, following status, and lookup timestamps in local extension storage for 30 days. Settings use synchronized extension storage when browser sync is enabled. You can clear the lookup cache at any time from the settings page or remove all extension data by uninstalling the extension.
The extension reads post author links in X timelines only to decide whether to display those posts. It does not read or store post text.
The collaborative cache at `x-geoblock-cache.dariosevilla.es` receives SHA-256 hashes of public usernames for lookups. Contributions are enabled by default and can be disabled in settings; signed reports contain the observed location, timestamp, and parser version. The service never receives following relationships, blacklist settings, post contents, or raw usernames. Public username hashes remain enumerable and must not be treated as anonymous data.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 861 KiB

+124
View File
@@ -0,0 +1,124 @@
(function (root) {
"use strict";
const DB_NAME = "x-geoblock-identity";
const STORE_NAME = "keys";
const KEY_ID = "installation";
function normalizeEndpoint(value) {
try {
const url = new URL(String(value || "").trim());
if (url.protocol !== "https:") return "";
return url.origin;
} catch { return ""; }
}
async function lookup(endpoint, usernames) {
endpoint = normalizeEndpoint(endpoint);
if (!endpoint) return new Map();
const pairs = await Promise.all(usernames.map(async (username) => [username, await hashHandle(username)]));
const response = await fetch(`${endpoint}/v1/cache/lookup`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ handleHashes: pairs.map(([, hash]) => hash) })
});
if (!response.ok) throw new Error(`Cloud cache lookup failed: HTTP ${response.status}`);
const data = await response.json();
const byHash = new Map((data.results || []).map((result) => [result.handleHash, result]));
return new Map(pairs.flatMap(([username, hash]) => byHash.has(hash) ? [[username, byHash.get(hash)]] : []));
}
async function report(endpoint, username, location, parserVersion) {
endpoint = normalizeEndpoint(endpoint);
if (!endpoint || !location) return;
const identity = await getIdentity(endpoint);
const path = "/v1/cache/report";
const body = JSON.stringify({
handleHash: await hashHandle(username),
location,
observedAt: Math.floor(Date.now() / 1000),
parserVersion
});
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = randomBase64Url(18);
const bodyHash = await sha256Hex(body);
const canonical = `POST\n${path}\n${timestamp}\n${nonce}\n${bodyHash}`;
const signature = await crypto.subtle.sign(
{ name: "ECDSA", hash: "SHA-256" }, identity.privateKey, new TextEncoder().encode(canonical)
);
const response = await fetch(`${endpoint}${path}`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-installation-id": identity.installationId,
"x-timestamp": timestamp,
"x-nonce": nonce,
"x-signature": toBase64Url(signature)
},
body
});
if (response.status === 401) {
await deleteIdentity();
throw new Error("Cloud cache installation identity was rejected");
}
if (!response.ok) throw new Error(`Cloud cache report failed: HTTP ${response.status}`);
}
async function getIdentity(endpoint) {
const existing = await readIdentity();
if (existing?.endpoint === endpoint && existing.privateKey && existing.installationId) return existing;
const keyPair = await crypto.subtle.generateKey(
{ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]
);
const publicKey = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
const response = await fetch(`${endpoint}/v1/installations`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ publicKey })
});
if (!response.ok) throw new Error(`Cloud cache registration failed: HTTP ${response.status}`);
const { installationId } = await response.json();
const identity = { endpoint, installationId, privateKey: keyPair.privateKey };
await writeIdentity(identity);
return identity;
}
async function hashHandle(username) {
return sha256Hex(String(username).trim().toLowerCase());
}
async function sha256Hex(value) {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
}
function randomBase64Url(length) { return toBase64Url(crypto.getRandomValues(new Uint8Array(length))); }
function toBase64Url(value) {
return btoa(String.fromCharCode(...new Uint8Array(value))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
function openDatabase() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, 1);
request.onupgradeneeded = () => request.result.createObjectStore(STORE_NAME);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
async function transaction(mode, operation) {
const database = await openDatabase();
try {
return await new Promise((resolve, reject) => {
const tx = database.transaction(STORE_NAME, mode);
const request = operation(tx.objectStore(STORE_NAME));
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
} finally { database.close(); }
}
function readIdentity() { return transaction("readonly", (store) => store.get(KEY_ID)); }
function writeIdentity(value) { return transaction("readwrite", (store) => store.put(value, KEY_ID)); }
function deleteIdentity() { return transaction("readwrite", (store) => store.delete(KEY_ID)); }
const api = { normalizeEndpoint, lookup, report, hashHandle };
root.XGeoCloud = api;
if (typeof module !== "undefined") module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
+27 -5
View File
@@ -1,11 +1,16 @@
(function (root) {
"use strict";
const CLOUD_CACHE_ENDPOINT = "https://x-geoblock-cache.dariosevilla.es";
const DEFAULT_SETTINGS = Object.freeze({
enabled: true,
blacklist: ["Belarus", "China", "Iran", "North Korea", "Russia"],
cacheTtlHours: 168,
showPlaceholder: false
blacklist: [],
skipFollowed: true,
showPlaceholder: true,
debugMode: false,
cloudCacheEndpoint: CLOUD_CACHE_ENDPOINT,
contributeCloudCache: true
});
const COUNTRY_ALIASES = Object.freeze({
@@ -16,8 +21,21 @@
"dprk": "north korea",
"republic of korea": "south korea",
"united states of america": "united states",
"u.s.": "united states",
"usa": "united states",
"uk": "united kingdom"
"uk": "united kingdom",
"viet nam": "vietnam",
"bolivia, plurinational state of": "bolivia",
"venezuela, bolivarian republic of": "venezuela",
"tanzania, united republic of": "tanzania",
"syrian arab republic": "syria",
"lao people's democratic republic": "laos",
"moldova, republic of": "moldova",
"brunei darussalam": "brunei",
"czechia": "czech republic",
"turkiye": "turkey",
"cote d’ivoire": "ivory coast",
"cote d'ivoire": "ivory coast"
});
function normalizeCountry(value) {
@@ -37,7 +55,11 @@
);
}
const api = { DEFAULT_SETTINGS, normalizeCountry, isBlacklisted };
function shouldBlock(country, blacklist, following, skipFollowed = true) {
return !(skipFollowed && following === true) && isBlacklisted(country, blacklist);
}
const api = { CLOUD_CACHE_ENDPOINT, DEFAULT_SETTINGS, normalizeCountry, isBlacklisted, shouldBlock };
root.XGeoConfig = api;
if (typeof module !== "undefined") module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
+51
View File
@@ -0,0 +1,51 @@
(function (root) {
"use strict";
// ISO 3166-1 alpha-2, plus XK for Kosovo (commonly exposed by CLDR services).
const REGION_CODES = (`
AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ
BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ
CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ
DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR
GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY
HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP
KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY
MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ
NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY
QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ
TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ
VA VC VE VG VI VN VU WF WS XK YE YT ZA ZM ZW
`).trim().split(/\s+/);
const displayNames = new Intl.DisplayNames(["en"], { type: "region" });
// X sometimes exposes a broad region instead of an ISO country. Keep these
// labels verbatim because they are compared with the About-page value.
const X_REGIONS = Object.freeze([
["Caribbean", "🌎"], ["Central Africa", "🌍"], ["Central America", "🌎"],
["Central Asia", "🌏"], ["East Africa", "🌍"], ["East Asia", "🌏"],
["Eastern Europe", "🌍"], ["North Africa", "🌍"], ["North America", "🌎"],
["Northern Europe", "🌍"], ["Oceania", "🌏"], ["South America", "🌎"],
["South Asia", "🌏"], ["Southeast Asia", "🌏"], ["Southern Africa", "🌍"],
["Southern Europe", "🌍"], ["West Africa", "🌍"], ["West Asia", "🌏"],
["Western Europe", "🌍"]
].map(([name, flag]) => Object.freeze({ code: `X-${name}`, name, flag, type: "region" })));
function countryName(code) {
return displayNames.of(code) || code;
}
function countryFlag(code) {
if (!/^[A-Z]{2}$/.test(code)) return "🌐";
return String.fromCodePoint(...code.split("").map((letter) => 127397 + letter.charCodeAt(0)));
}
const COUNTRIES = Object.freeze(REGION_CODES
.map((code) => Object.freeze({ code, name: countryName(code), flag: countryFlag(code), type: "country" }))
.sort((a, b) => a.name.localeCompare(b.name, "en")));
const LOCATIONS = Object.freeze([...X_REGIONS, ...COUNTRIES]);
const api = { REGION_CODES, X_REGIONS, COUNTRIES, LOCATIONS, countryName, countryFlag };
root.XGeoCountries = api;
if (typeof module !== "undefined") module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
+2 -2
View File
@@ -17,9 +17,9 @@
seen.add(value);
const legacy = value.legacy && typeof value.legacy === "object" ? value.legacy : value;
const screenName = legacy.screen_name || value.screen_name || value.username;
const screenName = legacy.screen_name || value.screen_name || value.core?.screen_name || value.username;
if (screenName && String(screenName).toLowerCase() === username.toLowerCase()) {
const following = legacy.following ?? value.following;
const following = legacy.following ?? value.following ?? value.relationship_perspectives?.following;
const location = legacy.location || value.location;
return {
following: typeof following === "boolean" ? following : null,
+36 -3
View File
@@ -3,22 +3,51 @@
"name": "X GeoBlock",
"version": "1.0.1",
"description": "Hide posts from X accounts based in countries you choose.",
"icons": {
"16": "icons/icon.png",
"32": "icons/icon.png",
"48": "icons/icon.png",
"128": "icons/icon.png"
},
"permissions": [
"storage",
"offscreen"
"offscreen",
"declarativeNetRequestWithHostAccess"
],
"host_permissions": [
"https://x.com/*"
"https://x.com/*",
"https://x-geoblock-cache.dariosevilla.es/*"
],
"background": {
"service_worker": "background.js"
},
"declarative_net_request": {
"rule_resources": [
{
"id": "about_page_frame",
"enabled": true,
"path": "rules/about-frame.json"
}
]
},
"content_scripts": [
{
"matches": [
"https://x.com/*"
],
"js": [
"page-bridge.js"
],
"run_at": "document_start",
"world": "MAIN"
},
{
"matches": [
"https://x.com/*"
],
"all_frames": true,
"js": [
"lib/parser.js",
"content.js"
],
"css": [
@@ -30,7 +59,11 @@
"options_page": "options/options.html",
"action": {
"default_title": "X GeoBlock",
"default_popup": "popup/popup.html"
"default_popup": "popup/popup.html",
"default_icon": {
"16": "icons/icon.png",
"32": "icons/icon.png"
}
},
"web_accessible_resources": [],
"minimum_chrome_version": "109"
+8 -6
View File
@@ -3,12 +3,14 @@
const extensionApi = globalThis.browser || chrome;
extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type !== "parse-about-html") return false;
try {
const document = new DOMParser().parseFromString(message.html, "text/html");
sendResponse(XGeoParser.parseAboutDocument(document, message.username));
} catch (error) {
sendResponse({ country: null, following: null, error: error.message });
if (message?.type === "parse-about-html") {
try {
const document = new DOMParser().parseFromString(message.html, "text/html");
sendResponse(XGeoParser.parseAboutDocument(document, message.username));
} catch (error) {
sendResponse({ country: null, following: null, error: error.message });
}
return false;
}
return false;
});
+36 -9
View File
@@ -1,9 +1,36 @@
:root { color-scheme: light dark; font: 16px/1.5 system-ui, sans-serif; }
body { margin: 0; background: #0f1419; color: #e7e9ea; }
main { max-width: 650px; margin: 48px auto; padding: 0 24px; }
h1 { font-size: 32px; margin-bottom: 4px; }.lead,.hint { color: #8b98a5; }.hint { margin: -8px 0 8px; font-size: 14px; }
label:not(.check) { display: block; margin: 24px 0 8px; font-weight: 700; }
textarea,input[type=number] { box-sizing: border-box; width: 100%; border: 1px solid #536471; border-radius: 8px; background: #000; color: inherit; padding: 12px; font: inherit; }
.check { display: block; margin: 22px 0; }.check input { margin-right: 8px; }.actions { display: flex; gap: 12px; margin-top: 28px; }
button { border: 0; border-radius: 999px; background: #1d9bf0; color: #fff; padding: 10px 18px; font-weight: 700; cursor: pointer; }
button.secondary { background: transparent; border: 1px solid #536471; }#status { min-height: 24px; color: #00ba7c; }
:root { color-scheme:dark; font:15px/1.5 Inter,ui-sans-serif,system-ui,sans-serif; --bg:#090d12; --panel:#111920; --panel2:#142029; --line:#293944; --line2:#38505e; --text:#f3f7f9; --muted:#a4b2ba; --cyan:#58ddf2; --lime:#b7f45b; --amber:#ffbe55; }
* { box-sizing:border-box; }
body { margin:0; min-height:100vh; background:radial-gradient(circle at 70% -20%,#102c39 0,transparent 38%),var(--bg); color:var(--text); }
body::before { content:""; position:fixed; inset:0; pointer-events:none; opacity:.12; background-image:linear-gradient(rgba(69,230,255,.055) 1px,transparent 1px),linear-gradient(90deg,rgba(69,230,255,.055) 1px,transparent 1px); background-size:32px 32px; mask-image:linear-gradient(to bottom,#000,transparent 80%); }
.noise { position:fixed; inset:0; pointer-events:none; opacity:.025; background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 160 160' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E"); }
main { position:relative; width:min(920px,calc(100% - 40px)); margin:0 auto; padding:46px 0 70px; }
.masthead { display:flex; align-items:center; justify-content:space-between; margin-bottom:30px; }
.identity { display:flex; align-items:center; gap:17px; }
.logo-shell { width:68px; height:68px; display:grid; place-items:center; border:1px solid #285064; border-radius:16px; background:linear-gradient(145deg,#132935,#081117); box-shadow:0 0 38px rgba(69,230,255,.1),inset 0 1px rgba(255,255,255,.04); }
.logo-shell img { width:53px; height:53px; object-fit:contain; }
.kicker,.section-tag,.system-state,.counter,.connected,.endpoint { font-family:"SFMono-Regular",Consolas,"Liberation Mono",monospace; letter-spacing:.06em; }
.kicker,.section-tag { margin:0 0 3px; color:var(--cyan); font-size:10px; font-weight:700; }
h1 { margin:0; font-size:34px; line-height:1.1; letter-spacing:-.035em; }
.lead { margin:5px 0 0; color:var(--muted); font-size:14px; }
.system-state { display:flex; align-items:center; gap:9px; padding:9px 12px; border:1px solid var(--line); border-radius:8px; background:rgba(15,24,30,.8); }
.system-state strong { color:var(--lime); font-size:10px; }
.state-dot { width:9px; height:9px; border-radius:50%; background:var(--lime); box-shadow:0 0 13px rgba(173,255,47,.75); }
form { display:grid; gap:16px; }
.panel { position:relative; padding:23px; border:1px solid var(--line); border-radius:14px; background:linear-gradient(145deg,rgba(19,29,37,.98),rgba(13,20,26,.98)); box-shadow:inset 0 1px rgba(255,255,255,.025),0 18px 50px rgba(0,0,0,.12); }
.panel::after { content:""; position:absolute; top:-1px; left:25px; width:70px; height:1px; background:var(--cyan); box-shadow:0 0 10px var(--cyan); opacity:.65; }
.master-panel { display:grid; grid-template-columns:1fr auto; align-items:center; gap:20px; }
.panel-copy h2,.section-head h2 { margin:0; font-size:20px; letter-spacing:-.015em; }.panel-copy p:last-child,.hint { margin:5px 0 0; color:var(--muted); font-size:13px; }
.section-head { display:flex; align-items:flex-start; justify-content:space-between; gap:20px; margin-bottom:18px; }
.counter { flex:none; margin-top:4px; padding:6px 9px; border:1px solid var(--line2); border-radius:5px; color:#bdd0d8; font-size:10px; }
.switch { display:flex; align-items:center; gap:9px; cursor:pointer; }.switch input { position:absolute; opacity:0; }.switch b { color:var(--muted); font:700 9px "SFMono-Regular",Consolas,monospace; letter-spacing:.1em; }.track { width:48px; height:26px; padding:4px; border:1px solid #2a3c46; border-radius:99px; background:#111b21; transition:.2s; }.track span { display:block; width:16px; height:16px; border-radius:50%; background:#657b86; transition:.2s; }.switch input:checked + .track { border-color:rgba(69,230,255,.7); background:rgba(69,230,255,.1); }.switch input:checked + .track span { transform:translateX(22px); background:var(--cyan); box-shadow:0 0 12px rgba(69,230,255,.75); }.switch input:checked ~ b { color:var(--cyan); }
.country-tools { display:flex; align-items:center; gap:10px; margin-bottom:11px; }.search-shell { flex:1; display:flex; align-items:center; gap:10px; padding:0 13px; border:1px solid var(--line2); border-radius:8px; background:#070c10; color:var(--cyan); }.search-shell:focus-within { border-color:#3cbdd0; box-shadow:0 0 0 3px rgba(69,230,255,.07); }.search-shell input { width:100%; border:0; outline:0; padding:11px 0; background:transparent; color:var(--text); font:inherit; }.search-shell input::placeholder { color:#506872; }
button { cursor:pointer; }.ghost,.primary,.danger { border-radius:7px; padding:11px 14px; font-weight:700; }.ghost { border:1px solid var(--line2); background:transparent; color:#b6c4ca; font:700 12px Inter,ui-sans-serif,system-ui,sans-serif; }.ghost:hover { border-color:var(--cyan); color:var(--cyan); }
.country-list { display:grid; grid-template-columns:repeat(auto-fill,minmax(190px,1fr)); gap:7px; max-height:420px; overflow:auto; scrollbar-color:#284550 #081016; padding:10px; border:1px solid var(--line); border-radius:10px; background:#070c10; }
.country-option { display:flex; align-items:center; gap:9px; min-width:0; padding:8px 9px; border:1px solid transparent; border-radius:7px; cursor:pointer; transition:.15s; }.country-option:hover { border-color:#203844; background:#0e1a21; }.country-option:has(input:checked) { border-color:rgba(69,230,255,.32); background:rgba(69,230,255,.075); }.country-option[hidden] { display:none; }.country-option input { accent-color:var(--cyan); }.country-flag { font-size:19px; line-height:1; }.country-name { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:13px; }
.setting-grid { display:grid; grid-template-columns:repeat(2,1fr); gap:10px; }.setting-card { display:flex; align-items:flex-start; gap:11px; padding:14px; border:1px solid var(--line); border-radius:9px; background:#091017; cursor:pointer; transition:.15s; }.setting-card:hover { border-color:#2d4a58; }.setting-card input { position:absolute; opacity:0; }.checkmark { flex:0 0 auto; width:18px; height:18px; border:1px solid #34505c; border-radius:4px; background:#071015; }.setting-card input:checked + .checkmark { border-color:var(--cyan); background:var(--cyan); box-shadow:0 0 12px rgba(69,230,255,.25); }.setting-card input:checked + .checkmark::after { content:""; display:block; width:8px; height:4px; margin:4px 0 0 4px; border:solid #041014; border-width:0 0 2px 2px; transform:rotate(-45deg); }.setting-card strong,.setting-card small { display:block; }.setting-card strong { font-size:13px; }.setting-card small { margin-top:3px; color:var(--muted); font-size:12px; line-height:1.4; }
.connected { display:flex; align-items:center; gap:7px; padding:6px 9px; border:1px solid rgba(183,244,91,.28); border-radius:5px; color:var(--lime); font-size:10px; }.connected i { width:6px; height:6px; border-radius:50%; background:var(--lime); box-shadow:0 0 9px rgba(173,255,47,.75); }
.endpoint { margin-bottom:11px; padding:12px 13px; border:1px solid var(--line); border-radius:8px; background:#0c1318; }.endpoint code { overflow:hidden; color:#b8d6df; font-size:12px; letter-spacing:0; text-overflow:ellipsis; }.lock { color:#4f6873; }
.contribution { max-width:none; }
.actions { display:flex; align-items:center; justify-content:space-between; min-height:50px; padding:4px 1px; }.actions > div { display:flex; gap:10px; }.primary { border:1px solid #2bc7de; background:linear-gradient(90deg,rgba(23,158,180,.25),rgba(69,230,255,.1)); color:var(--cyan); }.primary:hover { background:rgba(69,230,255,.16); box-shadow:0 0 20px rgba(69,230,255,.1); }.danger { border:1px solid #44363a; background:transparent; color:#c28c94; }.danger:hover { border-color:#a45762; color:#ff9aa7; }#status { min-width:170px; margin:0; color:var(--lime); font:11px "SFMono-Regular",Consolas,monospace; text-align:right; }
button:focus-visible,input:focus-visible,label:has(input:focus-visible) { outline:2px solid var(--cyan); outline-offset:2px; }
@media (max-width:680px) { main { width:min(100% - 24px,920px); padding-top:24px; }.masthead { align-items:flex-start; }.system-state { display:none; }.master-panel { grid-template-columns:1fr; }.section-head { display:block; }.counter,.connected { display:inline-flex; margin-top:10px; }.setting-grid { grid-template-columns:1fr; }.endpoint { grid-template-columns:1fr; }.endpoint span { display:none; }.actions { align-items:flex-start; gap:12px; flex-direction:column; }.actions > div { width:100%; }.actions button { flex:1; }#status { text-align:left; } }
+43 -14
View File
@@ -1,15 +1,44 @@
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>X GeoBlock settings</title><link rel="stylesheet" href="options.css"></head>
<body><main>
<h1>X GeoBlock</h1><p class="lead">Hide posts based on the country shown in an account's About page.</p>
<form id="settings">
<label class="check"><input id="enabled" type="checkbox"> Enable filtering</label>
<label for="blacklist">Blocked countries</label>
<p class="hint">Enter one country per line, exactly as X displays it.</p>
<textarea id="blacklist" rows="10" spellcheck="false"></textarea>
<label for="ttl">Cache duration (hours)</label><input id="ttl" type="number" min="1" max="8760">
<label class="check"><input id="placeholder" type="checkbox"> Show a clickable placeholder for hidden posts</label>
<div class="actions"><button type="submit">Save settings</button><button type="button" class="secondary" id="clear">Clear user cache</button></div>
<p id="status" role="status"></p>
</form>
</main><script src="../lib/config.js"></script><script src="options.js"></script></body></html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>X GeoBlock // Control panel</title><link rel="stylesheet" href="options.css"></head>
<body>
<div class="noise" aria-hidden="true"></div>
<main>
<header class="masthead">
<div class="identity"><div class="logo-shell"><img src="../icons/icon.png" alt=""></div><div><h1>X GeoBlock</h1><p class="lead">Location filtering for your X timeline.</p></div></div>
<div class="system-state"><span class="state-dot"></span><strong>Operational</strong></div>
</header>
<form id="settings">
<section class="panel master-panel">
<div class="panel-copy"><h2>Filtering</h2><p>Apply location rules as posts load.</p></div>
<label class="switch" for="enabled"><input id="enabled" type="checkbox"><span class="track"><span></span></span><b>Enabled</b></label>
</section>
<section class="panel">
<div class="section-head"><div><h2>Blocked locations</h2><p class="hint">Countries and regions reported by X.</p></div><div class="counter" id="selection-count">0 locations selected</div></div>
<div class="country-tools"><label class="search-shell"><span aria-hidden="true">⌕</span><input id="country-search" type="search" placeholder="Search locations…" autocomplete="off"></label><button type="button" class="ghost" id="clear-selection">Clear</button></div>
<div id="country-list" class="country-list"></div>
</section>
<section class="panel">
<div class="section-head"><div><h2>Behavior</h2></div></div>
<div class="setting-grid">
<label class="setting-card"><input id="placeholder" type="checkbox"><span class="checkmark"></span><span><strong>Reveal controls</strong><small>Show a marker for hidden posts.</small></span></label>
<label class="setting-card"><input id="debug-mode" type="checkbox"><span class="checkmark"></span><span><strong>Debug logging</strong><small>Log activity in the X console.</small></span></label>
<label class="setting-card"><input id="skip-followed" type="checkbox"><span class="checkmark"></span><span><strong>Ignore followed accounts</strong><small>Always allow accounts you follow.</small></span></label>
</div>
</section>
<section class="panel cloud-panel">
<div class="section-head"><div><h2>Cloud cache</h2><p class="hint">Shared results reduce requests to X.</p></div><span class="connected"><i></i>Connected</span></div>
<div class="endpoint"><code>x-geoblock-cache.dariosevilla.es</code></div>
<label class="setting-card contribution"><input id="cloud-contribute" type="checkbox"><span class="checkmark"></span><span><strong>Contribute observations</strong><small>Share hashed usernames and detected locations.</small></span></label>
</section>
<footer class="actions"><div><button type="submit" class="primary">Save settings</button><button type="button" class="danger" id="clear">Clear cache</button></div><p id="status" role="status"></p></footer>
</form>
</main>
<script src="../lib/config.js"></script><script src="../lib/countries.js"></script><script src="../lib/cloud-cache.js"></script><script src="options.js"></script>
</body>
</html>
+63 -7
View File
@@ -2,26 +2,82 @@
const extensionApi = globalThis.browser || chrome;
const form = document.querySelector("#settings");
const enabled = document.querySelector("#enabled");
const blacklist = document.querySelector("#blacklist");
const ttl = document.querySelector("#ttl");
const placeholder = document.querySelector("#placeholder");
const debugMode = document.querySelector("#debug-mode");
const skipFollowed = document.querySelector("#skip-followed");
const status = document.querySelector("#status");
const countryList = document.querySelector("#country-list");
const countrySearch = document.querySelector("#country-search");
const selectionCount = document.querySelector("#selection-count");
const cloudContribute = document.querySelector("#cloud-contribute");
renderCountries();
load();
async function load() {
const value = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS);
enabled.checked = value.enabled;
blacklist.value = value.blacklist.join("\n");
ttl.value = value.cacheTtlHours;
placeholder.checked = value.showPlaceholder;
debugMode.checked = value.debugMode === true;
skipFollowed.checked = value.skipFollowed !== false;
cloudContribute.checked = value.contributeCloudCache === true;
const selected = new Set(value.blacklist.map(XGeoConfig.normalizeCountry));
countryList.querySelectorAll("input").forEach((input) => {
input.checked = selected.has(XGeoConfig.normalizeCountry(input.value));
});
updateSelectionCount();
}
function renderCountries() {
const fragment = document.createDocumentFragment();
for (const country of XGeoCountries.LOCATIONS) {
const label = document.createElement("label");
label.className = "country-option";
label.dataset.search = `${country.name} ${country.code}`.toLowerCase();
const input = document.createElement("input");
input.type = "checkbox";
input.value = country.name;
const flag = document.createElement("span");
flag.className = "country-flag";
flag.textContent = country.flag;
flag.setAttribute("aria-hidden", "true");
const name = document.createElement("span");
name.className = "country-name";
name.textContent = country.name;
label.append(input, flag, name);
fragment.append(label);
}
countryList.append(fragment);
countryList.addEventListener("change", updateSelectionCount);
}
function updateSelectionCount() {
const count = countryList.querySelectorAll("input:checked").length;
selectionCount.textContent = `${count} ${count === 1 ? "location" : "locations"} selected`;
}
countrySearch.addEventListener("input", () => {
const query = countrySearch.value.trim().toLowerCase();
countryList.querySelectorAll(".country-option").forEach((option) => {
option.hidden = Boolean(query) && !option.dataset.search.includes(query);
});
});
document.querySelector("#clear-selection").addEventListener("click", () => {
countryList.querySelectorAll("input:checked").forEach((input) => input.checked = false);
updateSelectionCount();
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
await extensionApi.storage.sync.set({
enabled: enabled.checked,
blacklist: Array.from(new Set(blacklist.value.split(/\r?\n/).map((value) => value.trim()).filter(Boolean))),
cacheTtlHours: Math.max(1, Number(ttl.value) || 168),
showPlaceholder: placeholder.checked
blacklist: Array.from(countryList.querySelectorAll("input:checked"), (input) => input.value),
showPlaceholder: placeholder.checked,
debugMode: debugMode.checked,
skipFollowed: skipFollowed.checked,
cloudCacheEndpoint: XGeoConfig.CLOUD_CACHE_ENDPOINT,
contributeCloudCache: cloudContribute.checked
});
status.textContent = "Settings saved.";
setTimeout(() => status.textContent = "", 2000);
+220
View File
@@ -0,0 +1,220 @@
{
"name": "x-geoblock",
"version": "1.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "x-geoblock",
"version": "1.0.1",
"license": "MIT",
"devDependencies": {
"linkedom": "^0.18.12"
},
"engines": {
"node": ">=18"
}
},
"node_modules/boolbase": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
"integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==",
"dev": true,
"license": "ISC"
},
"node_modules/css-select": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz",
"integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"boolbase": "^1.0.0",
"css-what": "^6.1.0",
"domhandler": "^5.0.2",
"domutils": "^3.0.1",
"nth-check": "^2.0.1"
},
"funding": {
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/css-what": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz",
"integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">= 6"
},
"funding": {
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/cssom": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz",
"integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==",
"dev": true,
"license": "MIT"
},
"node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
"integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
"dev": true,
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.2",
"entities": "^4.2.0"
},
"funding": {
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
}
},
"node_modules/domelementtype": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
"integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause"
},
"node_modules/domhandler": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
"integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^2.3.0"
},
"engines": {
"node": ">= 4"
},
"funding": {
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^2.0.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3"
},
"funding": {
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/html-escaper": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz",
"integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==",
"dev": true,
"license": "MIT"
},
"node_modules/htmlparser2": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
"integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
"dev": true,
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.2.2",
"entities": "^7.0.1"
}
},
"node_modules/htmlparser2/node_modules/entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/linkedom": {
"version": "0.18.12",
"resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.12.tgz",
"integrity": "sha512-jalJsOwIKuQJSeTvsgzPe9iJzyfVaEJiEXl+25EkKevsULHvMJzpNqwvj1jOESWdmgKDiXObyjOYwlUqG7wo1Q==",
"dev": true,
"license": "ISC",
"dependencies": {
"css-select": "^5.1.0",
"cssom": "^0.5.0",
"html-escaper": "^3.0.3",
"htmlparser2": "^10.0.0",
"uhyphen": "^0.2.0"
},
"engines": {
"node": ">=16"
},
"peerDependencies": {
"canvas": ">= 2"
},
"peerDependenciesMeta": {
"canvas": {
"optional": true
}
}
},
"node_modules/nth-check": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz",
"integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"boolbase": "^1.0.0"
},
"funding": {
"url": "https://github.com/fb55/nth-check?sponsor=1"
}
},
"node_modules/uhyphen": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz",
"integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==",
"dev": true,
"license": "ISC"
}
}
}
+9 -3
View File
@@ -5,11 +5,17 @@
"description": "Browser extension that hides X posts based on account country.",
"scripts": {
"test": "node --test",
"check": "node --check background.js && node --check content.js && node --check lib/config.js && node --check lib/parser.js && node --check offscreen/offscreen.js && node --check options/options.js && node --check popup/popup.js && node --check scripts/build.mjs && node --check scripts/bump-version.mjs && node --test",
"build": "node scripts/build.mjs"
"check": "node --check background.js && node --check content.js && node --check page-bridge.js && node --check lib/config.js && node --check lib/countries.js && node --check lib/cloud-cache.js && node --check lib/parser.js && node --check offscreen/offscreen.js && node --check options/options.js && node --check popup/popup.js && node --check scripts/build.mjs && node --check scripts/bump-version.mjs && node --check worker/src/index.js && node --test",
"build": "node scripts/build.mjs",
"worker:migrate": "npx wrangler d1 migrations apply x-geoblock-cache --remote --config worker/wrangler.toml",
"worker:deploy": "npx wrangler deploy --config worker/wrangler.toml",
"worker:tail": "npx wrangler tail --config worker/wrangler.toml"
},
"engines": {
"node": ">=18"
},
"license": "MIT"
"license": "MIT",
"devDependencies": {
"linkedom": "^0.18.12"
}
}
+82
View File
@@ -0,0 +1,82 @@
(function () {
"use strict";
const ABOUT_QUERY_ID = "TzOG2twZEfhr9KmClvVVqA";
const PUBLIC_BEARER_TOKEN = "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";
document.addEventListener("x-geoblock-following-request", (event) => {
const article = event.target;
if (!(article instanceof Element)) return;
const username = article.dataset.xGeoBlockRequestUser || "";
const following = findFollowing(article, username);
article.dataset.xGeoBlockFollowing = following === null ? "unknown" : String(following);
article.dispatchEvent(new Event("x-geoblock-following-response"));
});
document.addEventListener("x-geoblock-about-api-request", async (event) => {
const request = event.target;
if (!(request instanceof Element)) return;
const username = request.dataset.xGeoBlockUsername || "";
try {
const csrf = document.cookie.match(/(?:^|;\s*)ct0=([^;]+)/)?.[1];
if (!csrf) throw new Error("X session CSRF cookie is unavailable");
const variables = encodeURIComponent(JSON.stringify({ screenName: username }));
const response = await fetch(`/i/api/graphql/${ABOUT_QUERY_ID}/AboutAccountQuery?variables=${variables}`, {
credentials: "include",
headers: {
authorization: `Bearer ${PUBLIC_BEARER_TOKEN}`,
"x-csrf-token": decodeURIComponent(csrf),
"x-twitter-active-user": "yes",
"x-twitter-auth-type": "OAuth2Session",
"x-twitter-client-language": document.documentElement.lang || "en"
}
});
if (!response.ok) throw new Error(`AboutAccountQuery returned HTTP ${response.status}`);
const payload = await response.json();
const result = payload?.data?.user_result_by_screen_name?.result;
request.dataset.xGeoBlockResult = JSON.stringify({
country: result?.about_profile?.account_based_in || null,
screenName: result?.core?.screen_name || null
});
} catch (error) {
request.dataset.xGeoBlockError = error?.message || String(error);
}
request.dispatchEvent(new Event("x-geoblock-about-api-response"));
});
function findFollowing(article, username) {
const roots = [article, ...article.querySelectorAll("[data-testid='User-Name'], a[href]")];
for (const element of roots) {
for (const key of Object.getOwnPropertyNames(element)) {
if (!key.startsWith("__reactProps$") && !key.startsWith("__reactFiber$")) continue;
const result = searchReactData(element[key], username);
if (result !== null) return result;
}
}
return null;
}
function searchReactData(root, username) {
const queue = [{ value: root, depth: 0 }];
const seen = new Set();
let inspected = 0;
while (queue.length && inspected++ < 8000) {
const { value, depth } = queue.shift();
if (!value || typeof value !== "object" || seen.has(value) || depth > 12) continue;
seen.add(value);
const legacy = value.legacy && typeof value.legacy === "object" ? value.legacy : value;
const screenName = legacy.screen_name || value.screen_name || value.core?.screen_name;
const following = legacy.following ?? value.following ?? value.relationship_perspectives?.following;
if (typeof screenName === "string" && screenName.toLowerCase() === username.toLowerCase() &&
typeof following === "boolean") return following;
for (const key of Object.keys(value)) {
if (key === "stateNode" || key === "return" || key === "sibling") continue;
try {
const child = value[key];
if (child && typeof child === "object" && !(child instanceof Node)) queue.push({ value: child, depth: depth + 1 });
} catch (_) {}
}
}
return null;
}
})();
+35 -1
View File
@@ -1 +1,35 @@
:root { color-scheme: light dark; font: 14px/1.4 system-ui,sans-serif; } body { margin: 0; min-width: 280px; background: #0f1419; color: #e7e9ea; } main { padding: 18px; } h1 { font-size: 20px; margin: 0 0 16px; } label { display:block; } p { color:#8b98a5; } button { border:0; border-radius:999px; padding:8px 14px; background:#1d9bf0; color:white; font-weight:700; cursor:pointer; }
:root { color-scheme: dark; font: 14px/1.45 Inter, ui-sans-serif, system-ui, sans-serif; --bg:#0a0e13; --panel:#121b22; --line:#2a3a45; --cyan:#58ddf2; --lime:#b7f45b; --muted:#a0afb7; }
* { box-sizing:border-box; }
body { margin:0; min-width:340px; background:var(--bg); color:#edfaff; }
body::before { content:""; position:fixed; inset:0; pointer-events:none; opacity:.12; background-image:linear-gradient(rgba(69,230,255,.07) 1px,transparent 1px),linear-gradient(90deg,rgba(69,230,255,.07) 1px,transparent 1px); background-size:24px 24px; mask-image:linear-gradient(to bottom,#000,transparent 72%); }
main { position:relative; padding:20px; }
.brand { display:flex; align-items:center; gap:11px; margin-bottom:18px; }
.logo-shell { width:43px; height:43px; display:grid; place-items:center; border:1px solid #244253; border-radius:11px; background:linear-gradient(145deg,#132430,#081016); box-shadow:0 0 24px rgba(69,230,255,.09); }
.brand img { width:34px; height:34px; object-fit:contain; }
.eyebrow,.version,.status-line,.metric,.cloud-line,button { font-family:"SFMono-Regular",Consolas,"Liberation Mono",monospace; letter-spacing:.08em; }
.eyebrow { margin:0 0 1px; color:var(--cyan); font-size:9px; }
h1 { margin:0; font-size:19px; letter-spacing:-.02em; }
.version { margin-left:auto; color:#5e7482; font-size:9px; border:1px solid var(--line); padding:3px 6px; border-radius:4px; }
.status-card { overflow:hidden; border:1px solid var(--line); border-radius:12px; background:linear-gradient(135deg,rgba(16,29,39,.96),rgba(9,14,20,.96)); box-shadow:inset 0 1px rgba(255,255,255,.025); }
.status-line { display:flex; align-items:center; gap:7px; padding:9px 12px; border-bottom:1px solid var(--line); color:var(--muted); font-size:9px; }
.status-line strong { margin-left:auto; color:var(--lime); font-size:9px; }
.pulse,.cloud-dot { width:7px; height:7px; border-radius:50%; background:var(--lime); box-shadow:0 0 10px rgba(173,255,47,.7); }
body[data-enabled="false"] .pulse { background:#ffb84d; box-shadow:0 0 10px rgba(255,184,77,.6); }
body[data-enabled="false"] .status-line strong { color:#ffb84d; }
.switch-row { display:flex; align-items:center; justify-content:space-between; padding:14px 13px; cursor:pointer; }
.switch-row strong,.switch-row small { display:block; }
.switch-row strong { font-size:14px; }
.switch-row small { margin-top:2px; color:var(--muted); font-size:11px; }
.switch { position:relative; width:44px; height:24px; }
.switch input { position:absolute; opacity:0; }
.slider { position:absolute; inset:0; border:1px solid #2b3d49; border-radius:99px; background:#131e26; transition:.2s; }
.slider::after { content:""; position:absolute; width:16px; height:16px; left:3px; top:3px; border-radius:50%; background:#6f8490; transition:.2s; }
.switch input:checked + .slider { border-color:rgba(69,230,255,.6); background:rgba(69,230,255,.12); }
.switch input:checked + .slider::after { transform:translateX(20px); background:var(--cyan); box-shadow:0 0 12px rgba(69,230,255,.7); }
.metric { display:flex; justify-content:space-between; margin-top:12px; padding:11px 12px; border:1px solid var(--line); border-radius:9px; color:var(--muted); font-size:10px; }
.metric strong { color:#dffaff; }
.cloud-line { display:flex; align-items:center; gap:7px; margin:12px 2px 16px; color:#6f8997; font-size:9px; }
.cloud-dot { width:5px; height:5px; background:var(--cyan); box-shadow:0 0 8px rgba(69,230,255,.8); }
button { width:100%; display:flex; justify-content:space-between; align-items:center; border:1px solid #2bc7de; border-radius:8px; padding:11px 13px; background:linear-gradient(90deg,rgba(28,167,190,.2),rgba(69,230,255,.08)); color:var(--cyan); font-size:10px; font-weight:700; cursor:pointer; transition:.18s; }
button:hover { background:rgba(69,230,255,.17); box-shadow:0 0 20px rgba(69,230,255,.1); }
button:focus-visible,input:focus-visible { outline:2px solid var(--cyan); outline-offset:2px; }
+12 -2
View File
@@ -1,2 +1,12 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>X GeoBlock</title><link rel="stylesheet" href="popup.css"></head>
<body><main><h1>X GeoBlock</h1><label><input id="enabled" type="checkbox"> Filtering enabled</label><p id="summary"></p><button id="settings">Open settings</button></main><script src="../lib/config.js"></script><script src="popup.js"></script></body></html>
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>X GeoBlock</title><link rel="stylesheet" href="popup.css"></head>
<body><main>
<header class="brand"><div class="logo-shell"><img src="../icons/icon.png" alt=""></div><div><h1>X GeoBlock</h1><p class="eyebrow">Timeline location filter</p></div><span class="version" id="version">v—</span></header>
<section class="status-card">
<div class="status-line"><span class="pulse" aria-hidden="true"></span><span>Filter status</span><strong id="engine-status">Online</strong></div>
<label class="switch-row" for="enabled"><span><strong>Protection</strong><small>Scan posts as they load</small></span><span class="switch"><input id="enabled" type="checkbox"><span class="slider"></span></span></label>
</section>
<div class="metric"><span>Blocklist</span><strong id="summary">—</strong></div>
<div class="cloud-line"><span class="cloud-dot"></span><span>Cloud cache linked</span></div>
<button id="settings"><span>Open settings</span><span aria-hidden="true">→</span></button>
</main><script src="../lib/config.js"></script><script src="popup.js"></script></body></html>
+10 -2
View File
@@ -2,9 +2,17 @@
const extensionApi = globalThis.browser || chrome;
const enabled = document.querySelector("#enabled");
const summary = document.querySelector("#summary");
const engineStatus = document.querySelector("#engine-status");
document.querySelector("#version").textContent = `v${extensionApi.runtime.getManifest().version}`;
extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS).then((value) => {
enabled.checked = value.enabled;
summary.textContent = `${value.blacklist.length} ${value.blacklist.length === 1 ? "country" : "countries"} blocked.`;
summary.textContent = `${value.blacklist.length} locations`;
engineStatus.textContent = value.enabled ? "Online" : "Paused";
document.body.dataset.enabled = String(value.enabled);
});
enabled.addEventListener("change", () => {
extensionApi.storage.sync.set({ enabled: enabled.checked });
engineStatus.textContent = enabled.checked ? "Online" : "Paused";
document.body.dataset.enabled = String(enabled.checked);
});
enabled.addEventListener("change", () => extensionApi.storage.sync.set({ enabled: enabled.checked }));
document.querySelector("#settings").addEventListener("click", () => extensionApi.runtime.openOptionsPage());
+18
View File
@@ -0,0 +1,18 @@
[
{
"id": 1,
"priority": 1,
"action": {
"type": "modifyHeaders",
"responseHeaders": [
{ "header": "content-security-policy", "operation": "remove" },
{ "header": "x-frame-options", "operation": "remove" }
]
},
"condition": {
"urlFilter": "||x.com/*/about",
"initiatorDomains": ["x.com"],
"resourceTypes": ["sub_frame"]
}
}
]
+3 -3
View File
@@ -8,7 +8,7 @@ const dist = join(root, "dist");
const baseManifest = JSON.parse(readFileSync(join(root, "manifest.json"), "utf8"));
const version = baseManifest.version;
const sharedFiles = [
"background.js", "content.js", "content.css", "lib", "options", "popup"
"background.js", "content.js", "content.css", "page-bridge.js", "icons", "lib", "options", "popup", "rules"
];
rmSync(dist, { recursive: true, force: true });
@@ -30,12 +30,12 @@ const firefoxManifest = structuredClone(baseManifest);
delete firefoxManifest.minimum_chrome_version;
firefoxManifest.permissions = firefoxManifest.permissions.filter((permission) => permission !== "offscreen");
firefoxManifest.background = {
scripts: ["lib/config.js", "lib/parser.js", "background.js"]
scripts: ["lib/config.js", "lib/cloud-cache.js", "lib/parser.js", "background.js"]
};
firefoxManifest.browser_specific_settings = {
gecko: {
id: "x-geoblock@dasemu.github.io",
strict_min_version: "109.0"
strict_min_version: "113.0"
}
};
const firefoxDirectory = prepare("firefox", firefoxManifest);
+136
View File
@@ -0,0 +1,136 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const vm = require("node:vm");
const { parseHTML } = require("linkedom");
const parser = require("../lib/parser.js");
const contentSource = fs.readFileSync(require.resolve("../content.js"), "utf8");
const pageBridgeSource = fs.readFileSync(require.resolve("../page-bridge.js"), "utf8");
function createContext(html, pathname, sendMessage, storedSettings = {}) {
const { window, document } = parseHTML(html);
const runtimeListeners = [];
const context = {
document,
location: { pathname, href: `https://x.com${pathname}`, origin: "https://x.com" },
chrome: {
storage: {
sync: { get: async (defaults) => ({ ...defaults, enabled: true, blacklist: ["United States"], ...storedSettings }) },
onChanged: { addListener() {} }
},
runtime: {
sendMessage,
onMessage: { addListener(listener) { runtimeListeners.push(listener); } }
}
},
XGeoParser: parser,
MutationObserver: window.MutationObserver,
Event: window.Event,
Element: window.Element,
Node: window.Node,
URL,
CSS: { escape: (value) => value },
console,
setTimeout,
clearTimeout,
setInterval,
clearInterval,
requestAnimationFrame: (callback) => setTimeout(callback, 0)
};
context.window = context;
context.window.top = context.window;
context.globalThis = context;
vm.runInNewContext(contentSource, context, { filename: "content.js" });
return { document, runtimeListeners };
}
test("manifest injects the About-page reporter into child frames", () => {
const manifest = require("../manifest.json");
const isolatedScript = manifest.content_scripts.find((entry) => entry.js.includes("content.js"));
assert.equal(isolatedScript.all_frames, true);
assert.equal(manifest.permissions.includes("declarativeNetRequestWithHostAccess"), true);
const rules = require("../rules/about-frame.json");
assert.deepEqual(rules[0].condition.resourceTypes, ["sub_frame"]);
assert.equal(rules[0].condition.urlFilter, "||x.com/*/about");
});
test("rendered About page reports the account country", async () => {
const messages = [];
createContext(`
<div role="tab" data-testid="pivot">
<svg><path d="M12 7c-1.93 0-3.5 1.57-3.5 3.5S10.07 14 12 14"></path></svg>
<span>Account based in</span><span>United States</span>
</div>`, "/ShitskinBlud/about", async (message) => messages.push(message));
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(JSON.parse(JSON.stringify(messages[0])), {
type: "about-page-result",
username: "ShitskinBlud",
country: "United States",
following: null,
profileLocation: null
});
});
test("blacklisted profile owner post is hidden", async () => {
const { document } = createContext(`
<main data-testid="primaryColumn">
<button data-testid="ShitskinBlud-follow">Follow</button>
<div data-testid="cellInnerDiv"><div class="x-wrapper"><article>
<a href="/ShitskinBlud/status/2110603064012918829">post</a>
</article></div></div>
</main>`, "/ShitskinBlud/with_replies", async (message) => {
assert.equal(message.type, "lookup-user");
assert.equal(message.username, "ShitskinBlud");
assert.equal(message.followingHint, false);
return { ok: true, country: "United States", following: false, blocked: true };
}, { showPlaceholder: true });
await new Promise((resolve) => setTimeout(resolve, 20));
const article = document.querySelector("article");
assert.equal(article.dataset.xGeoBlockState, "blocked");
assert.equal(article.dataset.xGeoBlockCountry, "United States");
const container = article.closest('[data-testid="cellInnerDiv"]');
assert.equal(container.classList.contains("x-geoblock-hidden"), true);
assert.equal(container.querySelector(":scope > :not(.x-geoblock-placeholder)"), article.parentElement);
const placeholder = container.querySelector(":scope > .x-geoblock-placeholder");
assert.ok(placeholder);
placeholder.click();
assert.equal(container.classList.contains("x-geoblock-revealed"), true);
});
test("page bridge performs the authenticated AboutAccountQuery", async () => {
const { window, document } = parseHTML("<html lang=\"en\"><body></body></html>");
Object.defineProperty(document, "cookie", { value: "ct0=test-csrf", configurable: true });
let requestedUrl;
const context = {
document,
Element: window.Element,
Node: window.Node,
Event: window.Event,
console,
fetch: async (url, options) => {
requestedUrl = url;
assert.equal(options.credentials, "include");
assert.equal(options.headers["x-csrf-token"], "test-csrf");
return {
ok: true,
json: async () => ({ data: { user_result_by_screen_name: { result: {
core: { screen_name: "ShitskinBlud" },
about_profile: { account_based_in: "Lebanon" }
} } } })
};
}
};
vm.runInNewContext(pageBridgeSource, context, { filename: "page-bridge.js" });
const request = document.createElement("span");
request.dataset.xGeoBlockUsername = "ShitskinBlud";
const response = new Promise((resolve, reject) => {
request.addEventListener("x-geoblock-about-api-response", resolve, { once: true });
setTimeout(() => reject(new Error("AboutAccountQuery bridge response timed out")), 500);
});
document.body.append(request);
request.dispatchEvent(new window.Event("x-geoblock-about-api-request", { bubbles: true }));
await response;
assert.match(requestedUrl, /AboutAccountQuery\?variables=/);
assert.deepEqual(JSON.parse(request.dataset.xGeoBlockResult), { country: "Lebanon", screenName: "ShitskinBlud" });
});
+41 -1
View File
@@ -1,7 +1,10 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const { findUserRecord } = require("../lib/parser.js");
const { normalizeCountry, isBlacklisted } = require("../lib/config.js");
const config = require("../lib/config.js");
const { normalizeCountry, isBlacklisted } = config;
const { COUNTRIES, LOCATIONS } = require("../lib/countries.js");
const { normalizeEndpoint, hashHandle } = require("../lib/cloud-cache.js");
test("finds following state in nested X user data", () => {
const source = { data: { user: { result: { legacy: { screen_name: "Alice", following: true, location: "Berlin" } } } } };
@@ -10,8 +13,45 @@ test("finds following state in nested X user data", () => {
test("does not confuse another user record", () => {
assert.equal(findUserRecord({ legacy: { screen_name: "Bob", following: false } }, "alice"), null);
});
test("finds following state in the current X user schema", () => {
const source = {
result: {
core: { screen_name: "Alice" },
relationship_perspectives: { following: false, followed_by: true },
location: "United States"
}
};
assert.deepEqual(findUserRecord(source, "alice"), { following: false, location: "United States" });
});
test("normalizes country aliases", () => {
assert.equal(normalizeCountry(" Russian Federation "), "russia");
assert.equal(isBlacklisted("Russian Federation", ["Russia"]), true);
assert.equal(isBlacklisted("Germany", ["Russia"]), false);
});
test("uses the production collaborative cache endpoint", () => {
assert.equal(config.CLOUD_CACHE_ENDPOINT, "https://x-geoblock-cache.dariosevilla.es");
assert.equal(config.DEFAULT_SETTINGS.cloudCacheEndpoint, config.CLOUD_CACHE_ENDPOINT);
assert.equal(config.DEFAULT_SETTINGS.contributeCloudCache, true);
assert.equal(config.DEFAULT_SETTINGS.showPlaceholder, true);
});
test("followed-account exemption is configurable", () => {
assert.equal(config.shouldBlock("Lebanon", ["Lebanon"], true, true), false);
assert.equal(config.shouldBlock("Lebanon", ["Lebanon"], true, false), true);
assert.equal(config.shouldBlock("Lebanon", ["Lebanon"], false, true), true);
});
test("offers the full country checklist with unique values", () => {
assert.equal(COUNTRIES.length, 250);
assert.equal(new Set(COUNTRIES.map((country) => country.code)).size, 250);
assert.ok(COUNTRIES.some((country) => country.name === "Germany" && country.flag === "🇩🇪"));
assert.ok(LOCATIONS.some((location) => location.name === "West Asia"));
assert.ok(LOCATIONS.some((location) => location.name === "United Kingdom" && location.flag === "🇬🇧"));
});
test("accepts only HTTPS cloud cache endpoints", () => {
assert.equal(normalizeEndpoint("https://cache.example.com/path"), "https://cache.example.com");
assert.equal(normalizeEndpoint("http://cache.example.com"), "");
assert.equal(normalizeEndpoint("not a URL"), "");
});
test("hashes handles case-insensitively before cloud lookup", async () => {
assert.equal(await hashHandle("Alice"), await hashHandle("alice"));
assert.match(await hashHandle("alice"), /^[a-f0-9]{64}$/);
});
+28
View File
@@ -0,0 +1,28 @@
# Collaborative cache worker
This Cloudflare Worker stores privacy-conscious, consensus-based account location observations in D1. A single report never becomes a blocking result. Three distinct installations must submit the same location within seven days before the cache returns it as `confirmed`.
## Deploy
1. From the repository root, authenticate: `npx wrangler login`.
2. Create the database: `npx wrangler d1 create x-geoblock-cache`.
3. Put the returned database ID in `worker/wrangler.toml`.
4. Store a long random secret: `npx wrangler secret put ABUSE_HMAC_KEY --config worker/wrangler.toml`.
5. Apply migrations: `npm run worker:migrate`.
6. Deploy the code into the Worker: `npm run worker:deploy`.
7. Verify `https://<your-worker>.workers.dev/health` returns `{"ok":true}`.
8. Point `CLOUD_CACHE_ENDPOINT` in `lib/config.js` and the matching manifest host permission at the deployed hostname. Production builds use `https://x-geoblock-cache.dariosevilla.es`.
If you created an empty Worker in the Cloudflare dashboard already, keep the same `name` in `worker/wrangler.toml`; `npm run worker:deploy` replaces its code. You still need a D1 database bound under the exact name `DB`, the migration, and `ABUSE_HMAC_KEY`.
For live server diagnostics run `npm run worker:tail`. Extension debug logs appear in the `x.com` page console after enabling debug mode in settings.
The Worker Free and D1 Free plans are normally sufficient for an initial deployment, but Cloudflare can change quotas. Check the current Workers and D1 pricing pages before making capacity assumptions.
## Trust model
Each installation generates a non-exportable ECDSA P-256 private key. Signed reports are bound to that installation and include a timestamp and nonce. This prevents report modification and replay, but it cannot prove that the sender is an official extension: any public client can register its own key. No client-side cryptography can solve that because extension code and embedded credentials are public.
The service therefore relies on independent-network consensus, per-IP and per-installation quotas, conflict-safe behavior, and Cloudflare edge protections. IP addresses are stored only as keyed HMACs; three different installation-network hashes must agree. Only `confirmed` entries are returned. Handles are sent as SHA-256 hashes; this reduces accidental disclosure but does not anonymize enumerable public usernames.
The Worker never receives following relationships, the user's blacklist, browsing history, or post contents.
+48
View File
@@ -0,0 +1,48 @@
CREATE TABLE installations (
id TEXT PRIMARY KEY,
public_key_jwk TEXT NOT NULL,
network_hash TEXT NOT NULL,
created_at INTEGER NOT NULL,
last_seen INTEGER NOT NULL
);
CREATE TABLE request_nonces (
installation_id TEXT NOT NULL,
nonce TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (installation_id, nonce),
FOREIGN KEY (installation_id) REFERENCES installations(id) ON DELETE CASCADE
);
CREATE TABLE observations (
handle_hash TEXT NOT NULL,
installation_id TEXT NOT NULL,
location TEXT NOT NULL,
observed_at INTEGER NOT NULL,
received_at INTEGER NOT NULL,
parser_version TEXT NOT NULL,
PRIMARY KEY (handle_hash, installation_id),
FOREIGN KEY (installation_id) REFERENCES installations(id) ON DELETE CASCADE
);
CREATE INDEX observations_handle_received ON observations(handle_hash, received_at);
CREATE TABLE canonical_cache (
handle_hash TEXT PRIMARY KEY,
location TEXT,
status TEXT NOT NULL CHECK (status IN ('pending', 'confirmed', 'conflict')),
confirmations INTEGER NOT NULL DEFAULT 0,
confidence REAL NOT NULL DEFAULT 0,
first_seen INTEGER NOT NULL,
last_seen INTEGER NOT NULL,
expires_at INTEGER,
version INTEGER NOT NULL DEFAULT 1
);
CREATE INDEX canonical_status_expiry ON canonical_cache(status, expires_at);
CREATE TABLE rate_limits (
bucket TEXT NOT NULL,
period TEXT NOT NULL,
count INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
PRIMARY KEY (bucket, period)
);
+215
View File
@@ -0,0 +1,215 @@
const JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
const MAX_CLOCK_SKEW_SECONDS = 300;
export default {
async fetch(request, env, ctx) {
if (request.method === "OPTIONS") return cors(new Response(null, { status: 204 }), request, env);
try {
const url = new URL(request.url);
let response;
if (request.method === "GET" && url.pathname === "/health") {
response = json({ ok: true });
} else if (request.method === "POST" && url.pathname === "/v1/installations") {
response = await registerInstallation(request, env);
} else if (request.method === "POST" && url.pathname === "/v1/cache/lookup") {
response = await lookup(request, env);
} else if (request.method === "POST" && url.pathname === "/v1/cache/report") {
response = await report(request, env, ctx);
} else {
response = json({ error: "not_found" }, 404);
}
return cors(response, request, env);
} catch (error) {
console.error(error);
return cors(json({ error: "internal_error" }, 500), request, env);
}
}
};
async function registerInstallation(request, env) {
if (!(await rateLimit(request, env, "register", 20))) return json({ error: "rate_limited" }, 429);
const body = await readJson(request);
if (!validPublicKey(body.publicKey)) return json({ error: "invalid_public_key" }, 400);
const id = crypto.randomUUID();
const now = epochSeconds();
const ip = request.headers.get("cf-connecting-ip") || "unknown";
const networkHash = await hmacHex(env.ABUSE_HMAC_KEY, `installation:${ip}`);
await env.DB.prepare("INSERT INTO installations (id, public_key_jwk, network_hash, created_at, last_seen) VALUES (?, ?, ?, ?, ?)")
.bind(id, JSON.stringify(body.publicKey), networkHash, now, now).run();
return json({ installationId: id }, 201);
}
async function lookup(request, env) {
if (!(await rateLimit(request, env, "lookup", 500))) return json({ error: "rate_limited" }, 429);
const body = await readJson(request);
const hashes = Array.from(new Set(Array.isArray(body.handleHashes) ? body.handleHashes : []));
if (!hashes.length || hashes.length > 50 || hashes.some((value) => !validHash(value))) {
return json({ error: "invalid_handle_hashes" }, 400);
}
const placeholders = hashes.map(() => "?").join(",");
const now = epochSeconds();
const query = `SELECT handle_hash, location, confidence, confirmations, last_seen, expires_at, version
FROM canonical_cache WHERE status = 'confirmed' AND expires_at > ? AND handle_hash IN (${placeholders})`;
const result = await env.DB.prepare(query).bind(now, ...hashes).all();
return json({
results: result.results.map((row) => ({
handleHash: row.handle_hash,
location: row.location,
status: "confirmed",
confidence: row.confidence,
confirmations: row.confirmations,
lastSeen: row.last_seen,
expiresAt: row.expires_at,
version: row.version
}))
});
}
async function report(request, env, ctx) {
const rawBody = await request.text();
const auth = await authenticate(request, rawBody, env);
if (!auth.ok) return json({ error: auth.error }, auth.status);
if (!(await rateLimit(request, env, `report:${auth.installationId}`, 200))) {
return json({ error: "rate_limited" }, 429);
}
let body;
try { body = JSON.parse(rawBody); } catch { return json({ error: "invalid_json" }, 400); }
if (!validHash(body.handleHash) || !validLocation(body.location) || !validParserVersion(body.parserVersion)) {
return json({ error: "invalid_report" }, 400);
}
const now = epochSeconds();
const observedAt = Number.isInteger(body.observedAt) && Math.abs(now - body.observedAt) < 86400
? body.observedAt : now;
await env.DB.prepare(`INSERT INTO observations
(handle_hash, installation_id, location, observed_at, received_at, parser_version)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(handle_hash, installation_id) DO UPDATE SET
location = excluded.location, observed_at = excluded.observed_at,
received_at = excluded.received_at, parser_version = excluded.parser_version`)
.bind(body.handleHash, auth.installationId, body.location.trim(), observedAt, now, body.parserVersion).run();
const consensus = await updateConsensus(body.handleHash, env, now);
ctx.waitUntil(cleanup(env, now));
return json(consensus, 202);
}
async function updateConsensus(handleHash, env, now) {
const pendingDays = numberSetting(env.PENDING_RETENTION_DAYS, 7);
const threshold = numberSetting(env.CONFIRMATION_THRESHOLD, 3);
const cutoff = now - pendingDays * 86400;
const grouped = await env.DB.prepare(`SELECT o.location, COUNT(DISTINCT i.network_hash) AS votes
FROM observations o JOIN installations i ON i.id = o.installation_id
WHERE o.handle_hash = ? AND o.received_at >= ?
GROUP BY o.location ORDER BY votes DESC, o.location ASC`).bind(handleHash, cutoff).all();
const first = grouped.results[0];
const second = grouped.results[1];
let status = "pending";
let location = first?.location || null;
let confirmations = first?.votes || 0;
if (first && first.votes >= threshold && (!second || first.votes > second.votes)) status = "confirmed";
else if (second && first.votes === second.votes) status = "conflict";
const total = grouped.results.reduce((sum, row) => sum + row.votes, 0);
const confidence = total ? confirmations / total : 0;
const expiresAt = status === "confirmed"
? now + numberSetting(env.CONFIRMED_TTL_DAYS, 30) * 86400 : null;
await env.DB.prepare(`INSERT INTO canonical_cache
(handle_hash, location, status, confirmations, confidence, first_seen, last_seen, expires_at, version)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
ON CONFLICT(handle_hash) DO UPDATE SET location = excluded.location, status = excluded.status,
confirmations = excluded.confirmations, confidence = excluded.confidence,
last_seen = excluded.last_seen, expires_at = excluded.expires_at, version = version + 1`)
.bind(handleHash, location, status, confirmations, confidence, now, now, expiresAt).run();
return { status, confirmations, confidence };
}
async function authenticate(request, rawBody, env) {
const installationId = request.headers.get("x-installation-id") || "";
const timestamp = request.headers.get("x-timestamp") || "";
const nonce = request.headers.get("x-nonce") || "";
const signature = request.headers.get("x-signature") || "";
if (!/^[0-9a-f-]{36}$/.test(installationId) || !/^\d{10}$/.test(timestamp) ||
!/^[A-Za-z0-9_-]{16,64}$/.test(nonce) || !signature) {
return { ok: false, error: "missing_signature", status: 401 };
}
const now = epochSeconds();
if (Math.abs(now - Number(timestamp)) > MAX_CLOCK_SKEW_SECONDS) {
return { ok: false, error: "stale_signature", status: 401 };
}
const row = await env.DB.prepare("SELECT public_key_jwk FROM installations WHERE id = ?")
.bind(installationId).first();
if (!row) return { ok: false, error: "unknown_installation", status: 401 };
const bodyHash = await sha256Hex(rawBody);
const url = new URL(request.url);
const signed = `${request.method}\n${url.pathname}\n${timestamp}\n${nonce}\n${bodyHash}`;
try {
const key = await crypto.subtle.importKey("jwk", JSON.parse(row.public_key_jwk),
{ name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
const valid = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key,
fromBase64Url(signature), new TextEncoder().encode(signed));
if (!valid) return { ok: false, error: "invalid_signature", status: 401 };
await env.DB.prepare("INSERT INTO request_nonces (installation_id, nonce, created_at) VALUES (?, ?, ?)")
.bind(installationId, nonce, now).run();
await env.DB.prepare("UPDATE installations SET last_seen = ? WHERE id = ?").bind(now, installationId).run();
return { ok: true, installationId };
} catch {
return { ok: false, error: "invalid_or_replayed_signature", status: 401 };
}
}
async function rateLimit(request, env, kind, limit) {
const ip = request.headers.get("cf-connecting-ip") || "unknown";
const secret = env.ABUSE_HMAC_KEY;
if (!secret) throw new Error("ABUSE_HMAC_KEY is required");
const day = new Date().toISOString().slice(0, 10);
const bucket = await hmacHex(secret, `${day}:${ip}`);
const period = `${kind}:${day}`;
const expiresAt = epochSeconds() + 2 * 86400;
await env.DB.prepare(`INSERT INTO rate_limits (bucket, period, count, expires_at) VALUES (?, ?, 1, ?)
ON CONFLICT(bucket, period) DO UPDATE SET count = count + 1`)
.bind(bucket, period, expiresAt).run();
const row = await env.DB.prepare("SELECT count FROM rate_limits WHERE bucket = ? AND period = ?")
.bind(bucket, period).first();
return row.count <= limit;
}
async function cleanup(env, now) {
const retention = numberSetting(env.OBSERVATION_RETENTION_DAYS, 90) * 86400;
await env.DB.batch([
env.DB.prepare("DELETE FROM request_nonces WHERE created_at < ?").bind(now - MAX_CLOCK_SKEW_SECONDS),
env.DB.prepare("DELETE FROM observations WHERE received_at < ?").bind(now - retention),
env.DB.prepare("DELETE FROM rate_limits WHERE expires_at < ?").bind(now)
]);
}
function cors(response, request, env) {
const origin = request.headers.get("origin") || "";
const allowed = origin.startsWith("chrome-extension://") || origin.startsWith("moz-extension://") ||
(env.ADMIN_ORIGIN && origin === env.ADMIN_ORIGIN);
const headers = new Headers(response.headers);
if (allowed) headers.set("access-control-allow-origin", origin);
headers.set("vary", "origin");
headers.set("access-control-allow-headers", "content-type,x-installation-id,x-timestamp,x-nonce,x-signature");
headers.set("access-control-allow-methods", "GET,POST,OPTIONS");
return new Response(response.body, { status: response.status, headers });
}
async function readJson(request) {
if (Number(request.headers.get("content-length") || 0) > 16384) throw new Error("body_too_large");
return request.json();
}
function json(value, status = 200) { return new Response(JSON.stringify(value), { status, headers: JSON_HEADERS }); }
function validPublicKey(key) { return key?.kty === "EC" && key?.crv === "P-256" && typeof key.x === "string" && typeof key.y === "string"; }
function validHash(value) { return typeof value === "string" && /^[a-f0-9]{64}$/.test(value); }
function validLocation(value) { return typeof value === "string" && value.trim().length >= 2 && value.trim().length <= 80 && !/[\u0000-\u001f]/.test(value); }
function validParserVersion(value) { return typeof value === "string" && /^[0-9]+\.[0-9]+\.[0-9]+$/.test(value); }
function numberSetting(value, fallback) { const number = Number(value); return Number.isFinite(number) && number > 0 ? number : fallback; }
function epochSeconds() { return Math.floor(Date.now() / 1000); }
async function sha256Hex(value) { return toHex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))); }
async function hmacHex(secret, value) {
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
return toHex(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value)));
}
function toHex(buffer) { return Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, "0")).join(""); }
function fromBase64Url(value) {
const base64 = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
}
+15
View File
@@ -0,0 +1,15 @@
name = "x-geoblock-cache"
main = "src/index.js"
compatibility_date = "2026-10-01"
[[d1_databases]]
binding = "DB"
database_name = "x-geoblock-cache"
database_id = "replace-with-your-d1-database-id"
migrations_dir = "migrations"
[vars]
CONFIRMATION_THRESHOLD = "3"
CONFIRMED_TTL_DAYS = "30"
OBSERVATION_RETENTION_DAYS = "90"
PENDING_RETENTION_DAYS = "7"