fix: render about fallback in same-origin page frame

This commit is contained in:
Darío Sevilla committed 2026-10-15 08:09:14 +00:00
1 parent 067cbfd24c
commit 5a492b0cc3
7 files changed
+76 -99

No files matched your search

+1 -2
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 background. If X returns only its empty application shell, an isolated invisible extension frame renders the account data without opening tabs or windows. - Performs authenticated About-page requests in the background. If X returns only its empty application shell, an invisible same-origin frame inside the current X page renders the account data without opening tabs or windows.
- Caches account results locally for 30 days, with manual clearing available. - Caches account results locally for 30 days, with manual clearing available.
- 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.
@@ -55,7 +55,6 @@ 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.
- `declarativeNetRequestWithHostAccess`: permits only `x.com` subframes to render inside the isolated background document after X returns an empty application shell.
- `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
+21 -68
View File
@@ -3,7 +3,6 @@ if (typeof XGeoConfig === "undefined") importScripts("lib/config.js", "lib/cloud
const extensionApi = globalThis.browser || chrome; const extensionApi = globalThis.browser || chrome;
const CACHE_KEY = "userCache"; const CACHE_KEY = "userCache";
const FRAME_RULE_ID = 1;
const LOCAL_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000; const LOCAL_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const activeRequests = new Map(); const activeRequests = new Map();
const pendingFrameLookups = new Map(); const pendingFrameLookups = new Map();
@@ -13,7 +12,6 @@ let lastRequestAt = 0;
extensionApi.runtime.onInstalled.addListener(async () => { extensionApi.runtime.onInstalled.addListener(async () => {
const current = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS); const current = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS);
await extensionApi.storage.sync.set(current); await extensionApi.storage.sync.set(current);
await ensureFrameRule();
}); });
extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => { extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => {
@@ -30,7 +28,7 @@ extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => {
return true; return true;
} }
if (message?.type === "about-page-result") { if (message?.type === "about-page-result") {
finishFrameLookup(message); finishFrameLookup(message, sender?.tab?.id);
sendResponse({ ok: true }); sendResponse({ ok: true });
return false; return false;
} }
@@ -93,7 +91,7 @@ async function lookupUserInternal(username, key, followingHint, tabId) {
emitDebug(tabId, settings.debugMode, "Direct X lookup started", { username }); emitDebug(tabId, settings.debugMode, "Direct X lookup started", { username });
const lookupLog = (event, data = {}) => emitDebug(tabId, settings.debugMode, event, { username, ...data }); const lookupLog = (event, data = {}) => emitDebug(tabId, settings.debugMode, event, { username, ...data });
const result = await enqueue(() => fetchAbout(username, lookupLog)); const result = await enqueue(() => fetchAbout(username, lookupLog, tabId));
const record = { ...result, checkedAt: Date.now() }; const record = { ...result, checkedAt: Date.now() };
emitDebug(tabId, settings.debugMode, "Direct X lookup completed", { username, country: record.country, following: record.following }); emitDebug(tabId, settings.debugMode, "Direct X lookup completed", { username, country: record.country, following: record.following });
if (record.country || record.following === true) { if (record.country || record.following === true) {
@@ -116,7 +114,7 @@ async function lookupUserInternal(username, key, followingHint, tabId) {
function emitDebug(tabId, enabled, event, data = {}) { function emitDebug(tabId, enabled, event, data = {}) {
if (!enabled) return; if (!enabled) return;
console.debug("[X GeoBlock]", event, data); console.info("[X GeoBlock]", event, data);
if (Number.isInteger(tabId)) { if (Number.isInteger(tabId)) {
extensionApi.tabs.sendMessage(tabId, { type: "debug-event", event, data }).catch(() => {}); extensionApi.tabs.sendMessage(tabId, { type: "debug-event", event, data }).catch(() => {});
} }
@@ -143,7 +141,7 @@ function enqueue(task) {
return run; return run;
} }
async function fetchAbout(username, log = () => {}) { async function fetchAbout(username, log = () => {}, tabId = null) {
try { 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",
@@ -160,8 +158,8 @@ async function fetchAbout(username, log = () => {}) {
log("Background HTTP lookup failed", { error: error.message }); log("Background HTTP lookup failed", { error: error.message });
// X frequently serves an incomplete SPA shell to extension fetches. // X frequently serves an incomplete SPA shell to extension fetches.
} }
log("Falling back to isolated background frame"); log("Falling back to same-origin hidden frame");
return lookupViaBackgroundFrame(username, log); return lookupViaPageFrame(username, tabId, log);
} }
async function parseFetchedHtml(html, username) { async function parseFetchedHtml(html, username) {
@@ -173,17 +171,19 @@ async function parseFetchedHtml(html, username) {
return extensionApi.runtime.sendMessage({ type: "parse-about-html", html, username }); return extensionApi.runtime.sendMessage({ type: "parse-about-html", html, username });
} }
async function lookupViaBackgroundFrame(username, log = () => {}) { 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(); const key = username.toLowerCase();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const timer = setTimeout(() => { const timer = setTimeout(() => {
pendingFrameLookups.delete(key); pendingFrameLookups.delete(key);
removeBackgroundFrame(key); removePageFrame(tabId, key);
log("Isolated background frame timed out"); log("Same-origin hidden frame timed out");
reject(new Error(`Timed out while rendering @${username}'s About page in the background`)); reject(new Error(`Timed out while rendering @${username}'s About page`));
}, 25000); }, 25000);
pendingFrameLookups.set(key, { resolve, reject, timer, log }); pendingFrameLookups.set(key, { resolve, reject, timer, log, tabId });
createBackgroundFrame(username).then(() => log("Isolated background frame created")).catch((error) => { extensionApi.tabs.sendMessage(tabId, { type: "create-about-frame", username })
.then(() => log("Same-origin hidden frame created")).catch((error) => {
clearTimeout(timer); clearTimeout(timer);
pendingFrameLookups.delete(key); pendingFrameLookups.delete(key);
reject(error); reject(error);
@@ -191,10 +191,10 @@ async function lookupViaBackgroundFrame(username, log = () => {}) {
}); });
} }
function finishFrameLookup(message) { function finishFrameLookup(message, tabId) {
const key = String(message.username).toLowerCase(); const key = String(message.username).toLowerCase();
const pending = pendingFrameLookups.get(key); const pending = pendingFrameLookups.get(key);
if (!pending) return; if (!pending || pending.tabId !== tabId) return;
pending.log("Rendered About page reported a result", { country: message.country || null, following: message.following ?? null }); pending.log("Rendered About page reported a result", { country: message.country || null, following: message.following ?? null });
clearTimeout(pending.timer); clearTimeout(pending.timer);
pendingFrameLookups.delete(key); pendingFrameLookups.delete(key);
@@ -203,58 +203,11 @@ function finishFrameLookup(message) {
following: message.following === true, following: message.following === true,
profileLocation: message.profileLocation || null profileLocation: message.profileLocation || null
}); });
removeBackgroundFrame(key); removePageFrame(tabId, key);
} }
async function createBackgroundFrame(username) { function removePageFrame(tabId, username) {
await ensureFrameRule(); extensionApi.tabs.sendMessage(tabId, { type: "remove-about-frame", username }).catch(() => {});
if (typeof document !== "undefined") {
const frame = document.createElement("iframe");
frame.dataset.xGeoBlockUser = username.toLowerCase();
frame.hidden = true;
frame.src = `https://x.com/${encodeURIComponent(username)}/about`;
document.body.append(frame);
return;
}
await ensureOffscreenDocument();
await extensionApi.runtime.sendMessage({ type: "create-about-frame", username });
}
let frameRulePromise;
function ensureFrameRule() {
if (!frameRulePromise) {
frameRulePromise = extensionApi.declarativeNetRequest.updateSessionRules({
removeRuleIds: [FRAME_RULE_ID],
addRules: [{
id: FRAME_RULE_ID,
priority: 1,
action: {
type: "modifyHeaders",
responseHeaders: [
{ header: "x-frame-options", operation: "remove" },
{ header: "content-security-policy", operation: "remove" }
]
},
condition: {
urlFilter: "||x.com/",
resourceTypes: ["sub_frame"],
tabIds: [-1]
}
}]
}).catch((error) => {
frameRulePromise = null;
throw error;
});
}
return frameRulePromise;
}
function removeBackgroundFrame(username) {
if (typeof document !== "undefined") {
document.querySelector(`iframe[data-x-geo-block-user="${CSS.escape(username)}"]`)?.remove();
return;
}
extensionApi.runtime.sendMessage({ type: "remove-about-frame", username }).catch(() => {});
} }
async function ensureOffscreenDocument() { async function ensureOffscreenDocument() {
@@ -263,7 +216,7 @@ async function ensureOffscreenDocument() {
if (clients.some((client) => client.url === url)) return; if (clients.some((client) => client.url === url)) return;
await extensionApi.offscreen.createDocument({ await extensionApi.offscreen.createDocument({
url: "offscreen/offscreen.html", url: "offscreen/offscreen.html",
reasons: ["DOM_PARSER", "IFRAME_SCRIPTING"], reasons: ["DOM_PARSER"],
justification: "Parse and render account About pages entirely in the extension background." justification: "Parse account About HTML without opening a visible page."
}); });
} }
+50 -3
View File
@@ -51,10 +51,21 @@ extensionApi.storage.onChanged.addListener((changes, area) => {
if (settings.enabled) scheduleScan(); if (settings.enabled) scheduleScan();
}); });
extensionApi.runtime.onMessage.addListener((message) => { extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type === "debug-event" && settings.debugMode) { if (message?.type === "debug-event" && settings.debugMode) {
console.debug("[X GeoBlock]", message.event, message.data || {}); 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 === "remove-about-frame") {
removeAboutFrame(message.username);
sendResponse({ ok: true });
return false;
}
return false;
}); });
function scheduleScan() { function scheduleScan() {
@@ -144,7 +155,43 @@ function hideArticle(article, username, country) {
} }
function debug(event, data = {}) { function debug(event, data = {}) {
if (settings.debugMode) console.debug("[X GeoBlock]", 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 inspectAboutFrame(frame, username) {
const startedAt = Date.now();
const timer = setInterval(() => {
if (!frame.isConnected) return clearInterval(timer);
try {
const result = XGeoParser.parseAboutDocument(frame.contentDocument, 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() { function restoreAll() {
+1 -1
View File
@@ -5,7 +5,7 @@
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 fetched HTML to an offscreen document; Firefox can parse it in its background page. When X returns only its SPA shell, an invisible frame inside the isolated background document renders the same URL, reports the location row, and is immediately destroyed. This does not create a browser tab or window. 4. Chromium passes fetched HTML to an offscreen document; Firefox can parse it in its background page. When X returns only its SPA shell, an invisible same-origin frame inside the current X page renders the URL. 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. 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.
+2 -4
View File
@@ -11,8 +11,7 @@
}, },
"permissions": [ "permissions": [
"storage", "storage",
"offscreen", "offscreen"
"declarativeNetRequestWithHostAccess"
], ],
"host_permissions": [ "host_permissions": [
"https://x.com/*" "https://x.com/*"
@@ -45,8 +44,7 @@
"css": [ "css": [
"content.css" "content.css"
], ],
"run_at": "document_idle", "run_at": "document_idle"
"all_frames": true
} }
], ],
"options_page": "options/options.html", "options_page": "options/options.html",
+1 -1
View File
@@ -1,3 +1,3 @@
<!doctype html> <!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>X GeoBlock parser</title></head> <html lang="en"><head><meta charset="utf-8"><title>X GeoBlock parser</title></head>
<body><div id="frames"></div><script src="../lib/parser.js"></script><script src="offscreen.js"></script></body></html> <body><script src="../lib/parser.js"></script><script src="offscreen.js"></script></body></html>
-20
View File
@@ -12,25 +12,5 @@ extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
} }
return false; return false;
} }
if (message?.type === "create-about-frame") {
removeFrame(message.username);
const frame = document.createElement("iframe");
frame.dataset.xGeoBlockUser = message.username.toLowerCase();
frame.hidden = true;
frame.src = `https://x.com/${encodeURIComponent(message.username)}/about`;
document.querySelector("#frames").append(frame);
sendResponse({ ok: true });
return false;
}
if (message?.type === "remove-about-frame") {
removeFrame(message.username);
sendResponse({ ok: true });
return false;
}
return false; return false;
}); });
function removeFrame(username) {
const key = String(username).toLowerCase();
document.querySelector(`iframe[data-x-geo-block-user="${CSS.escape(key)}"]`)?.remove();
}