mirror of
https://github.com/Dasemu/X-GeoBlock.git
synced 2026-11-26 07:16:10 +00:00
fix: query authenticated account location directly
This commit is contained in:
1 parent
8a5fecc731
commit
28b7175433
6 files changed
+116
-4
No files matched your search
@@ -5,7 +5,7 @@ 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 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. A narrowly scoped network rule allows only these `/about` subframes to render despite X's anti-framing headers.
|
||||
- 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.
|
||||
|
||||
@@ -174,6 +174,19 @@ async function fetchAbout(username, log = () => {}, tabId = null) {
|
||||
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);
|
||||
}
|
||||
|
||||
+28
-1
@@ -60,6 +60,10 @@ extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
|
||||
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 });
|
||||
@@ -123,7 +127,7 @@ function getFollowingHint(article, username) {
|
||||
};
|
||||
article.dataset.xGeoBlockRequestUser = username;
|
||||
article.addEventListener("x-geoblock-following-response", finish, { once: true });
|
||||
article.dispatchEvent(new Event("x-geoblock-following-request"));
|
||||
article.dispatchEvent(new Event("x-geoblock-following-request", { bubbles: true }));
|
||||
setTimeout(finish, 150);
|
||||
});
|
||||
}
|
||||
@@ -186,6 +190,29 @@ function createAboutFrame(username) {
|
||||
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(() => {
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
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 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. 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.
|
||||
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.
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
(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;
|
||||
@@ -10,6 +13,37 @@
|
||||
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) {
|
||||
|
||||
@@ -6,6 +6,7 @@ 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) {
|
||||
const { window, document } = parseHTML(html);
|
||||
@@ -90,3 +91,40 @@ test("blacklisted profile owner post is hidden", async () => {
|
||||
assert.equal(article.dataset.xGeoBlockCountry, "United States");
|
||||
assert.equal(article.closest('[data-testid="cellInnerDiv"]').classList.contains("x-geoblock-hidden"), 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" });
|
||||
});
|
||||
Reference in new issue
Block a user