feat: add collaborative Cloudflare cache and debug mode

This commit is contained in:
Darío Sevilla committed 2026-10-15 07:59:10 +00:00
1 parent 7e88fee0c2
commit 067cbfd24c
20 files changed
+695 -31

No files matched your search

+5 -3
View File
@@ -6,11 +6,13 @@ X GeoBlock is a Manifest V3 browser extension for Chromium and Firefox. While yo
- Processes posts already on the page and posts loaded by infinite scrolling.
- Performs authenticated About-page requests in the background. If X returns only its empty application shell, an isolated invisible extension frame renders the account data without opening tabs or windows.
- Caches account results locally without expiration until you clear the cache.
- 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 searchable country and region checklist with flags, 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.
- 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.
- Supports an optional, self-hosted Cloudflare Worker + D1 collaborative cache with signed opt-in contributions and three-installation consensus.
## Install from source in Chromium
@@ -41,7 +43,7 @@ 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
+73 -14
View File
@@ -1,9 +1,10 @@
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 FRAME_RULE_ID = 1;
const LOCAL_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const activeRequests = new Map();
const pendingFrameLookups = new Map();
let queueTail = Promise.resolve();
@@ -17,7 +18,9 @@ extensionApi.runtime.onInstalled.addListener(async () => {
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;
@@ -38,27 +41,61 @@ 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);
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];
if (cached && (cached.country || cached.following === true)) {
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));
if (followingHint === true) {
emitDebug(tabId, settings.debugMode, "Author is followed; allowing post", { username });
return decision({ country: null, following: true }, settings, false);
}
if (followingHint === false && 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: false, 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));
const record = { ...result, 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 });
@@ -66,7 +103,23 @@ async function lookupUserInternal(username, key) {
delete cache[key];
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
}
return decision(record, settings, false);
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.debug("[X GeoBlock]", event, data);
if (Number.isInteger(tabId)) {
extensionApi.tabs.sendMessage(tabId, { type: "debug-event", event, data }).catch(() => {});
}
}
function decision(record, settings, cached) {
@@ -90,21 +143,25 @@ function enqueue(task) {
return run;
}
async function fetchAbout(username) {
async function fetchAbout(username, log = () => {}) {
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 (_) {
} catch (error) {
log("Background HTTP lookup failed", { error: error.message });
// X frequently serves an incomplete SPA shell to extension fetches.
}
return lookupViaBackgroundFrame(username);
log("Falling back to isolated background frame");
return lookupViaBackgroundFrame(username, log);
}
async function parseFetchedHtml(html, username) {
@@ -116,16 +173,17 @@ async function parseFetchedHtml(html, username) {
return extensionApi.runtime.sendMessage({ type: "parse-about-html", html, username });
}
async function lookupViaBackgroundFrame(username) {
async function lookupViaBackgroundFrame(username, log = () => {}) {
const key = username.toLowerCase();
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingFrameLookups.delete(key);
removeBackgroundFrame(key);
log("Isolated background frame timed out");
reject(new Error(`Timed out while rendering @${username}'s About page in the background`));
}, 25000);
pendingFrameLookups.set(key, { resolve, reject, timer });
createBackgroundFrame(username).catch((error) => {
pendingFrameLookups.set(key, { resolve, reject, timer, log });
createBackgroundFrame(username).then(() => log("Isolated background frame created")).catch((error) => {
clearTimeout(timer);
pendingFrameLookups.delete(key);
reject(error);
@@ -137,6 +195,7 @@ function finishFrameLookup(message) {
const key = String(message.username).toLowerCase();
const pending = pendingFrameLookups.get(key);
if (!pending) 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({
+39 -4
View File
@@ -3,7 +3,7 @@
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();
@@ -15,7 +15,8 @@ async function initialize() {
return;
}
if (window.top !== window) return;
settings = await extensionApi.storage.sync.get({ enabled: true, showPlaceholder: false });
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();
@@ -44,11 +45,18 @@ 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) => {
if (message?.type === "debug-event" && settings.debugMode) {
console.debug("[X GeoBlock]", message.event, message.data || {});
}
});
function scheduleScan() {
if (scanQueued) return;
scanQueued = true;
@@ -68,11 +76,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;
@@ -80,11 +91,30 @@ 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) {
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"));
setTimeout(finish, 150);
});
}
function getTweetIdentity(article) {
const links = article.querySelectorAll('a[href*="/status/"]');
for (const link of links) {
@@ -95,6 +125,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");
@@ -112,6 +143,10 @@ function hideArticle(article, username, country) {
}
}
function debug(event, data = {}) {
if (settings.debugMode) console.debug("[X GeoBlock]", event, data);
}
function restoreAll() {
document.querySelectorAll(".x-geoblock-hidden").forEach((node) => {
node.classList.remove("x-geoblock-hidden", "x-geoblock-revealed");
+1 -1
View File
@@ -9,7 +9,7 @@
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.
Failed or ambiguous lookups fail open: the post remains visible. Empty results are never cached. Successful lookups remain cached without expiration. The user can clear the entire cache from the settings page if X changes an account's country or following relationship.
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
+28
View File
@@ -0,0 +1,28 @@
# Collaborative cloud cache
The optional cloud cache uses the Cloudflare Worker and D1 schema in `worker/`. It is disabled until a user enters a deployed Worker URL in extension settings. Contributing observations is a separate opt-in choice.
## 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 without automatic expiration. 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 optional collaborative cache is disabled until a Worker URL is configured. Cloud reads send SHA-256 hashes of public usernames. If contribution is enabled separately, signed reports also 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.
+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);
+4 -1
View File
@@ -4,7 +4,10 @@
const DEFAULT_SETTINGS = Object.freeze({
enabled: true,
blacklist: [],
showPlaceholder: false
showPlaceholder: false,
debugMode: false,
cloudCacheEndpoint: "",
contributeCloudCache: false
});
const COUNTRY_ALIASES = Object.freeze({
+13
View File
@@ -17,10 +17,23 @@
"host_permissions": [
"https://x.com/*"
],
"optional_host_permissions": [
"https://*/*"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [
"https://x.com/*"
],
"js": [
"page-bridge.js"
],
"run_at": "document_start",
"world": "MAIN"
},
{
"matches": [
"https://x.com/*"
+2 -1
View File
@@ -3,10 +3,11 @@ body { margin: 0; background: #0f1419; color: #e7e9ea; }
main { max-width: 650px; margin: 48px auto; padding: 0 24px; }
.brand { display:flex; align-items:center; gap:16px; }.brand img { width:64px; height:64px; object-fit:contain; flex:0 0 auto; }h1 { font-size: 32px; margin:0 0 4px; }.lead,.hint { color: #8b98a5; }.lead { margin:0; }.hint { margin: 6px 0 8px; font-size: 14px; }
fieldset { border: 0; padding: 0; margin: 28px 0 0; } legend { font-size: 18px; font-weight: 700; padding: 0; }
input[type=search] { box-sizing: border-box; flex: 1; min-width: 180px; border: 1px solid #536471; border-radius: 999px; background: #000; color: inherit; padding: 10px 14px; font: inherit; }
input[type=search],input[type=url] { box-sizing: border-box; flex: 1; width:100%; min-width: 180px; border: 1px solid #536471; border-radius: 999px; background: #000; color: inherit; padding: 10px 14px; 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; }
.country-tools { display: flex; gap: 12px; align-items: center; margin: 14px 0 8px; }.link-button { background: transparent; color: #1d9bf0; padding: 8px; white-space: nowrap; }
.selection-count { color: #8b98a5; margin: 8px 0; font-size: 14px; }.country-list { display: grid; grid-template-columns: repeat(auto-fill,minmax(190px,1fr)); gap: 6px; max-height: 430px; overflow: auto; border: 1px solid #2f3336; border-radius: 12px; padding: 10px; background: #000; }
.country-option { display: flex; align-items: center; gap: 9px; padding: 7px 8px; margin: 0; border-radius: 8px; cursor: pointer; }.country-option:hover { background: #16181c; }.country-option[hidden] { display: none; }.country-flag { font-size: 20px; line-height: 1; }.country-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cloud-settings { border-top:1px solid #2f3336; padding-top:24px; }.cloud-settings label:not(.check) { display:block; margin:14px 0 7px; font-weight:700; }
+10 -1
View File
@@ -12,7 +12,16 @@
<div id="country-list" class="country-list"></div>
</fieldset>
<label class="check"><input id="placeholder" type="checkbox"> Show a clickable placeholder for hidden posts</label>
<label class="check"><input id="debug-mode" type="checkbox"> Enable debug logging in the X page console</label>
<fieldset class="cloud-settings">
<legend>Collaborative cloud cache</legend>
<p class="hint">Optional. Confirmed results reduce requests to X. Deploy the included Cloudflare Worker and enter its HTTPS URL.</p>
<label for="cloud-endpoint">Worker URL</label>
<input id="cloud-endpoint" type="url" placeholder="https://x-geoblock-cache.example.workers.dev" autocomplete="url">
<label class="check"><input id="cloud-contribute" type="checkbox"> Contribute locally observed locations</label>
<p class="hint">Contributions send a SHA-256 hash of the public username and its location. Following relationships, posts, and your blacklist are never uploaded.</p>
</fieldset>
<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="../lib/countries.js"></script><script src="options.js"></script></body></html>
</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>
+22 -1
View File
@@ -3,10 +3,13 @@ const extensionApi = globalThis.browser || chrome;
const form = document.querySelector("#settings");
const enabled = document.querySelector("#enabled");
const placeholder = document.querySelector("#placeholder");
const debugMode = document.querySelector("#debug-mode");
const status = document.querySelector("#status");
const countryList = document.querySelector("#country-list");
const countrySearch = document.querySelector("#country-search");
const selectionCount = document.querySelector("#selection-count");
const cloudEndpoint = document.querySelector("#cloud-endpoint");
const cloudContribute = document.querySelector("#cloud-contribute");
renderCountries();
@@ -15,6 +18,9 @@ async function load() {
const value = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS);
enabled.checked = value.enabled;
placeholder.checked = value.showPlaceholder;
debugMode.checked = value.debugMode === true;
cloudEndpoint.value = value.cloudCacheEndpoint || "";
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));
@@ -64,10 +70,25 @@ document.querySelector("#clear-selection").addEventListener("click", () => {
form.addEventListener("submit", async (event) => {
event.preventDefault();
const endpoint = XGeoCloud.normalizeEndpoint(cloudEndpoint.value);
if (cloudEndpoint.value.trim() && !endpoint) {
status.textContent = "Enter a valid HTTPS Worker URL.";
return;
}
if (endpoint) {
const granted = await extensionApi.permissions.request({ origins: [`${endpoint}/*`] });
if (!granted) {
status.textContent = "Host permission is required to use the cloud cache.";
return;
}
}
await extensionApi.storage.sync.set({
enabled: enabled.checked,
blacklist: Array.from(countryList.querySelectorAll("input:checked"), (input) => input.value),
showPlaceholder: placeholder.checked
showPlaceholder: placeholder.checked,
debugMode: debugMode.checked,
cloudCacheEndpoint: endpoint,
contributeCloudCache: Boolean(endpoint) && cloudContribute.checked
});
status.textContent = "Settings saved.";
setTimeout(() => status.textContent = "", 2000);
+5 -2
View File
@@ -5,8 +5,11 @@
"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/countries.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"
+48
View File
@@ -0,0 +1,48 @@
(function () {
"use strict";
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"));
});
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;
const following = legacy.following ?? value.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;
}
})();
+2 -2
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", "icons", "lib", "options", "popup"
"background.js", "content.js", "content.css", "page-bridge.js", "icons", "lib", "options", "popup"
];
rmSync(dist, { recursive: true, force: true });
@@ -30,7 +30,7 @@ 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: {
+10
View File
@@ -3,6 +3,7 @@ const assert = require("node:assert/strict");
const { findUserRecord } = require("../lib/parser.js");
const { normalizeCountry, isBlacklisted } = require("../lib/config.js");
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" } } } } };
@@ -23,3 +24,12 @@ test("offers the full country checklist with unique values", () => {
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. Enter the resulting HTTPS Worker URL in the extension settings.
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"