fix: resolve account country from rendered about page

This commit is contained in:
Darío Sevilla committed 2026-10-15 07:42:06 +00:00
1 parent 3811ae9cfc
commit d6c31bdf95
5 files changed
+96 -11

No files matched your search

+2 -1
View File
@@ -5,7 +5,7 @@ X GeoBlock is a Manifest V3 browser extension for Chromium and Firefox. While yo
## Features ## Features
- Processes posts already on the page and posts loaded by infinite scrolling. - Processes posts already on the page and posts loaded by infinite scrolling.
- Performs authenticated About-page requests in the extension service worker. - Performs authenticated About-page requests in the background. If X returns only its empty application shell, the extension briefly uses an inactive tab so X can render the account data, then closes it automatically.
- Caches account results locally without expiration until you clear the cache. - Caches account results locally without expiration until you clear the cache.
- Coalesces duplicate lookups and spaces network requests to reduce load on X. - Coalesces duplicate lookups and spaces network requests to reduce load on X.
- Skips followed accounts. - Skips followed accounts.
@@ -53,6 +53,7 @@ The location picker contains the ISO 3166-1 countries, plus Kosovo, using Englis
- `storage`: saves settings and the local user cache. - `storage`: saves settings and the local user cache.
- `offscreen`: parses returned HTML without opening visible tabs. - `offscreen`: parses returned HTML without opening visible tabs.
- `tabs`: opens and closes inactive About tabs when X requires client-side rendering.
- `https://x.com/*`: reads About pages and runs the feed filter on X. - `https://x.com/*`: reads About pages and runs the feed filter on X.
## License ## License
+66 -7
View File
@@ -4,6 +4,7 @@ const extensionApi = globalThis.browser || chrome;
const CACHE_KEY = "userCache"; const CACHE_KEY = "userCache";
const activeRequests = new Map(); const activeRequests = new Map();
const pendingTabLookups = new Map();
let queueTail = Promise.resolve(); let queueTail = Promise.resolve();
let lastRequestAt = 0; let lastRequestAt = 0;
@@ -12,7 +13,7 @@ extensionApi.runtime.onInstalled.addListener(async () => {
await extensionApi.storage.sync.set(current); await extensionApi.storage.sync.set(current);
}); });
extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => { extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type === "lookup-user") { if (message?.type === "lookup-user") {
lookupUser(message.username).then(sendResponse).catch((error) => { lookupUser(message.username).then(sendResponse).catch((error) => {
sendResponse({ ok: false, error: error.message }); sendResponse({ ok: false, error: error.message });
@@ -23,7 +24,20 @@ extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
extensionApi.storage.local.remove(CACHE_KEY).then(() => sendResponse({ ok: true })); extensionApi.storage.local.remove(CACHE_KEY).then(() => sendResponse({ ok: true }));
return true; return true;
} }
if (message?.type === "about-page-result" && Number.isInteger(sender?.tab?.id)) {
finishTabLookup(sender.tab.id, message);
sendResponse({ ok: true });
return false; return false;
}
return false;
});
extensionApi.tabs.onRemoved.addListener((tabId) => {
const pending = pendingTabLookups.get(tabId);
if (!pending) return;
clearTimeout(pending.timer);
pendingTabLookups.delete(tabId);
pending.reject(new Error("The background About tab closed before X loaded the account data"));
}); });
function validUsername(username) { function validUsername(username) {
@@ -45,14 +59,20 @@ async function lookupUserInternal(username, key) {
const stored = await extensionApi.storage.local.get(CACHE_KEY); const stored = await extensionApi.storage.local.get(CACHE_KEY);
const cache = stored[CACHE_KEY] || {}; const cache = stored[CACHE_KEY] || {};
const cached = cache[key]; const cached = cache[key];
if (cached) { if (cached && (cached.country || cached.following === true)) {
return decision(cached, settings, true); return decision(cached, settings, true);
} }
const result = await enqueue(() => fetchAbout(username)); const result = await enqueue(() => fetchAbout(username));
cache[key] = { ...result, checkedAt: Date.now() }; const record = { ...result, checkedAt: Date.now() };
if (record.country || record.following === true) {
cache[key] = record;
await extensionApi.storage.local.set({ [CACHE_KEY]: cache }); await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
return decision(cache[key], settings, false); } else if (cached) {
delete cache[key];
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
}
return decision(record, settings, false);
} }
function decision(record, settings, cached) { function decision(record, settings, cached) {
@@ -77,14 +97,23 @@ function enqueue(task) {
} }
async function fetchAbout(username) { async function fetchAbout(username) {
try {
const response = await fetch(`https://x.com/${encodeURIComponent(username)}/about`, { const response = await fetch(`https://x.com/${encodeURIComponent(username)}/about`, {
credentials: "include", credentials: "include",
headers: { "Accept-Language": "en-US,en;q=0.9" }, headers: { "Accept-Language": "en-US,en;q=0.9" },
redirect: "follow" redirect: "follow"
}); });
if (!response.ok) throw new Error(`X returned HTTP ${response.status}`); if (response.ok && !/\/i\/flow\/login/i.test(response.url)) {
const html = await response.text(); const parsed = await parseFetchedHtml(await response.text(), username);
if (/\/i\/flow\/login/i.test(response.url)) throw new Error("X authentication is required"); if (parsed?.country) return parsed;
}
} catch (_) {
// X frequently serves an incomplete SPA shell to extension fetches.
}
return lookupViaBackgroundTab(username);
}
async function parseFetchedHtml(html, username) {
if (typeof DOMParser !== "undefined" && typeof XGeoParser !== "undefined") { if (typeof DOMParser !== "undefined" && typeof XGeoParser !== "undefined") {
const document = new DOMParser().parseFromString(html, "text/html"); const document = new DOMParser().parseFromString(html, "text/html");
return XGeoParser.parseAboutDocument(document, username); return XGeoParser.parseAboutDocument(document, username);
@@ -93,6 +122,36 @@ async function fetchAbout(username) {
return extensionApi.runtime.sendMessage({ type: "parse-about-html", html, username }); return extensionApi.runtime.sendMessage({ type: "parse-about-html", html, username });
} }
async function lookupViaBackgroundTab(username) {
const tab = await extensionApi.tabs.create({
url: `https://x.com/${encodeURIComponent(username)}/about`,
active: false
});
if (!Number.isInteger(tab.id)) throw new Error("The browser did not create the background About tab");
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingTabLookups.delete(tab.id);
extensionApi.tabs.remove(tab.id).catch(() => {});
reject(new Error(`Timed out while loading @${username}'s About page`));
}, 25000);
pendingTabLookups.set(tab.id, { username: username.toLowerCase(), resolve, reject, timer });
});
}
function finishTabLookup(tabId, message) {
const pending = pendingTabLookups.get(tabId);
if (!pending || String(message.username).toLowerCase() !== pending.username) return;
clearTimeout(pending.timer);
pendingTabLookups.delete(tabId);
pending.resolve({
country: message.country || null,
following: message.following === true,
profileLocation: message.profileLocation || null
});
extensionApi.tabs.remove(tabId).catch(() => {});
}
async function ensureOffscreenDocument() { async function ensureOffscreenDocument() {
const url = extensionApi.runtime.getURL("offscreen/offscreen.html"); const url = extensionApi.runtime.getURL("offscreen/offscreen.html");
const clients = await self.clients.matchAll(); const clients = await self.clients.matchAll();
+23
View File
@@ -9,6 +9,11 @@ let scanQueued = false;
initialize(); initialize();
async function initialize() { async function initialize() {
const aboutMatch = location.pathname.match(/^\/([A-Za-z0-9_]{1,15})\/about\/?$/);
if (aboutMatch) {
reportRenderedAboutPage(aboutMatch[1]);
return;
}
settings = await extensionApi.storage.sync.get({ enabled: true, showPlaceholder: false }); settings = await extensionApi.storage.sync.get({ enabled: true, showPlaceholder: false });
scan(document); scan(document);
new MutationObserver((mutations) => { new MutationObserver((mutations) => {
@@ -16,6 +21,24 @@ async function initialize() {
}).observe(document.documentElement, { childList: true, subtree: true }); }).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) => { extensionApi.storage.onChanged.addListener((changes, area) => {
if (area !== "sync") return; if (area !== "sync") return;
if (changes.enabled) settings.enabled = changes.enabled.newValue; if (changes.enabled) settings.enabled = changes.enabled.newValue;
+2 -2
View File
@@ -5,11 +5,11 @@
1. The content script observes X's timeline and extracts an author from each canonical `/user/status/id` link. 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. 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. 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. 4. Chromium passes fetched HTML to an offscreen document; Firefox can parse it in its background page. When X returns only its SPA shell, the extension opens the same URL in an inactive tab, waits for X to render the location row, reports the result, and closes the tab.
5. The worker caches the result and compares the country with the configured blacklist. 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 only when the country matches and the account is not followed.
Failed or ambiguous lookups fail open: the post remains visible. 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 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.
## Browser components ## Browser components
+3 -1
View File
@@ -11,7 +11,8 @@
}, },
"permissions": [ "permissions": [
"storage", "storage",
"offscreen" "offscreen",
"tabs"
], ],
"host_permissions": [ "host_permissions": [
"https://x.com/*" "https://x.com/*"
@@ -25,6 +26,7 @@
"https://x.com/*" "https://x.com/*"
], ],
"js": [ "js": [
"lib/parser.js",
"content.js" "content.js"
], ],
"css": [ "css": [