From 0944faab3ee241c87eaf114955ab6f667a612314 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Sevilla?= <24dasemu@gmail.com> Date: Thu, 15 Oct 2026 07:22:51 +0000 Subject: [PATCH] feat: add cross-browser X GeoBlock extension --- .github/workflows/release.yml | 74 ++++++++++++++++++++++ .gitignore | 5 ++ CONTRIBUTING.md | 10 +++ LICENSE | 21 +++++++ README.md | 60 ++++++++++++++++++ background.js | 114 ++++++++++++++++++++++++++++++++++ content.css | 9 +++ content.js | 97 +++++++++++++++++++++++++++++ docs/architecture.md | 25 ++++++++ docs/privacy.md | 7 +++ docs/releases.md | 15 +++++ lib/config.js | 43 +++++++++++++ lib/parser.js | 96 ++++++++++++++++++++++++++++ manifest.json | 26 ++++++++ offscreen/offscreen.html | 3 + offscreen/offscreen.js | 14 +++++ options/options.css | 9 +++ options/options.html | 15 +++++ options/options.js | 33 ++++++++++ package.json | 13 ++++ popup/popup.css | 1 + popup/popup.html | 2 + popup/popup.js | 10 +++ scripts/build.mjs | 53 ++++++++++++++++ scripts/bump-version.mjs | 31 +++++++++ tests/parser.test.js | 17 +++++ 26 files changed, 803 insertions(+) create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 background.js create mode 100644 content.css create mode 100644 content.js create mode 100644 docs/architecture.md create mode 100644 docs/privacy.md create mode 100644 docs/releases.md create mode 100644 lib/config.js create mode 100644 lib/parser.js create mode 100644 manifest.json create mode 100644 offscreen/offscreen.html create mode 100644 offscreen/offscreen.js create mode 100644 options/options.css create mode 100644 options/options.html create mode 100644 options/options.js create mode 100644 package.json create mode 100644 popup/popup.css create mode 100644 popup/popup.html create mode 100644 popup/popup.js create mode 100644 scripts/build.mjs create mode 100644 scripts/bump-version.mjs create mode 100644 tests/parser.test.js diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2327da3 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,74 @@ +name: Build and release extensions + +on: + push: + branches: [main] + +permissions: + contents: write + pull-requests: read + +concurrency: + group: release-main + cancel-in-progress: false + +jobs: + release: + if: ${{ !contains(github.event.head_commit.message, '[skip release]') }} + runs-on: ubuntu-latest + steps: + - name: Check out the triggering commit + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Detect release type + id: release_type + env: + GH_TOKEN: ${{ github.token }} + run: | + source_branch="$(gh api \ + -H 'Accept: application/vnd.github+json' \ + "/repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls" \ + --jq 'map(select(.base.ref == "main")) | .[0].head.ref // ""')" + if [ "$source_branch" = "development" ]; then + echo "kind=minor" >> "$GITHUB_OUTPUT" + else + echo "kind=patch" >> "$GITHUB_OUTPUT" + fi + + - name: Update main and bump version + id: version + env: + RELEASE_KIND: ${{ steps.release_type.outputs.kind }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git checkout main + git pull --ff-only origin main + version="$(node scripts/bump-version.mjs "$RELEASE_KIND")" + git add manifest.json package.json + git commit -m "chore(release): v${version} [skip release]" + git push origin main + echo "version=$version" >> "$GITHUB_OUTPUT" + + - name: Run checks + run: npm run check + + - name: Build browser packages + run: npm run build + + - name: Create tag and GitHub release + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.version.outputs.version }} + RELEASE_KIND: ${{ steps.release_type.outputs.kind }} + run: | + git tag "v${VERSION}" + git push origin "v${VERSION}" + gh release create "v${VERSION}" \ + "dist/x-geoblock-chrome-v${VERSION}.zip" \ + "dist/x-geoblock-firefox-v${VERSION}.xpi" \ + --target "$(git rev-parse HEAD)" \ + --title "X GeoBlock v${VERSION}" \ + --generate-notes diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..14ba4b6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +node_modules/ +*.zip +*.xpi +dist/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..29d54f2 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,10 @@ +# Contributing + +Contributions are welcome. Keep the extension dependency-free unless a new dependency has a clear maintenance or security benefit. + +1. Create a focused branch. +2. Run `npm run check`. +3. Load the repository as an unpacked extension and test a timeline, infinite scrolling, settings changes, cache clearing, a followed account, and a blacklisted account. +4. Describe any X markup samples used to update the parser, removing personal or session data first. + +Do not commit captured X pages, cookies, authentication headers, or user cache data. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7f7171d --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 X GeoBlock contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b32bfe8 --- /dev/null +++ b/README.md @@ -0,0 +1,60 @@ +# X GeoBlock + +X GeoBlock is a Manifest V3 browser extension for Chromium and Firefox. While you browse `x.com`, it checks each post author's public **About this account** page and hides posts from countries in your blacklist. Accounts you follow are always allowed. + +## 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). +- 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. + +## Install from source in Chromium + +1. Open `chrome://extensions` in Chrome, Edge, Brave, or another Chromium browser. +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. + +No build step or dependency installation is required. + +## Install from source in Firefox + +1. Run `npm run build`. +2. Open `about:debugging#/runtime/this-firefox`. +3. Select **Load Temporary Add-on**. +4. Choose `dist/firefox/manifest.json`. + +The generated XPI is unsigned and is intended for temporary installation or submission to Mozilla Add-ons. Standard Firefox releases require Mozilla signing for permanent installation. + +## Development + +The extension uses plain JavaScript, HTML, and CSS. Node.js 18 or newer is needed only for tests: + +```sh +npm test +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). + +## 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. + +## Permissions + +- `storage`: saves settings and the local user cache. +- `offscreen`: parses returned HTML without opening visible tabs. +- `https://x.com/*`: reads About pages and runs the feed filter on X. + +## License + +[MIT](LICENSE) diff --git a/background.js b/background.js new file mode 100644 index 0000000..5994628 --- /dev/null +++ b/background.js @@ -0,0 +1,114 @@ +if (typeof XGeoConfig === "undefined") importScripts("lib/config.js"); + +const extensionApi = globalThis.browser || chrome; + +const CACHE_KEY = "userCache"; +const activeRequests = new Map(); +let queueTail = Promise.resolve(); +let lastRequestAt = 0; + +extensionApi.runtime.onInstalled.addListener(async () => { + const current = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS); + await extensionApi.storage.sync.set(current); +}); + +extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => { + if (message?.type === "lookup-user") { + lookupUser(message.username).then(sendResponse).catch((error) => { + sendResponse({ ok: false, error: error.message }); + }); + return true; + } + if (message?.type === "clear-cache") { + extensionApi.storage.local.remove(CACHE_KEY).then(() => sendResponse({ ok: true })); + return true; + } + return false; +}); + +function validUsername(username) { + return typeof username === "string" && /^[A-Za-z0-9_]{1,15}$/.test(username); +} + +async function lookupUser(username) { + 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)); + activeRequests.set(key, promise); + return promise; +} + +async function lookupUserInternal(username, key) { + const settings = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS); + 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) { + return decision(cached, settings, true); + } + + 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); +} + +function decision(record, settings, cached) { + return { + ok: true, + country: record.country, + following: record.following === true, + blocked: record.following !== true && XGeoConfig.isBlacklisted(record.country, settings.blacklist), + 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(); + }); + 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"); + if (typeof DOMParser !== "undefined" && typeof XGeoParser !== "undefined") { + const document = new DOMParser().parseFromString(html, "text/html"); + return XGeoParser.parseAboutDocument(document, username); + } + await ensureOffscreenDocument(); + return extensionApi.runtime.sendMessage({ type: "parse-about-html", html, username }); +} + +async function ensureOffscreenDocument() { + const url = extensionApi.runtime.getURL("offscreen/offscreen.html"); + const clients = await self.clients.matchAll(); + if (clients.some((client) => client.url === url)) return; + await extensionApi.offscreen.createDocument({ + url: "offscreen/offscreen.html", + reasons: ["DOM_PARSER"], + justification: "Parse the account About page without opening a visible tab." + }); +} + +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]; +} diff --git a/content.css b/content.css new file mode 100644 index 0000000..7fad1e6 --- /dev/null +++ b/content.css @@ -0,0 +1,9 @@ +.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-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.x-geoblock-revealed > .x-geoblock-placeholder { display: block; opacity: .7; } diff --git a/content.js b/content.js new file mode 100644 index 0000000..36bf726 --- /dev/null +++ b/content.js @@ -0,0 +1,97 @@ +"use strict"; + +const extensionApi = globalThis.browser || chrome; +const processed = new WeakSet(); +const hiddenByUser = new Map(); +let settings = { enabled: true, showPlaceholder: false }; +let scanQueued = false; + +initialize(); + +async function initialize() { + settings = await extensionApi.storage.sync.get({ enabled: true, showPlaceholder: false }); + scan(document); + new MutationObserver((mutations) => { + if (mutations.some((mutation) => mutation.addedNodes.length)) scheduleScan(); + }).observe(document.documentElement, { childList: true, subtree: true }); +} + +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; + restoreAll(); + document.querySelectorAll("article").forEach((article) => processed.delete(article)); + if (settings.enabled) scheduleScan(); +}); + +function scheduleScan() { + if (scanQueued) return; + scanQueued = true; + requestAnimationFrame(() => { + scanQueued = false; + scan(document); + }); +} + +function scan(root) { + if (!settings.enabled) return; + const articles = root.matches?.("article") ? [root] : root.querySelectorAll?.("article") || []; + for (const article of articles) processArticle(article); +} + +async function processArticle(article) { + if (processed.has(article)) return; + const identity = getTweetIdentity(article); + if (!identity) return; + processed.add(article); + article.dataset.xGeoBlockState = "checking"; + + try { + const result = await extensionApi.runtime.sendMessage({ type: "lookup-user", username: identity.username }); + if (!article.isConnected || !result?.ok) { + delete article.dataset.xGeoBlockState; + return; + } + article.dataset.xGeoBlockCountry = result.country || "unknown"; + if (result.blocked) hideArticle(article, identity.username, result.country); + else article.dataset.xGeoBlockState = result.following ? "followed" : "allowed"; + } catch (_) { + delete article.dataset.xGeoBlockState; + } +} + +function getTweetIdentity(article) { + const links = article.querySelectorAll('a[href*="/status/"]'); + for (const link of links) { + const match = new URL(link.href, location.origin).pathname.match(/^\/([A-Za-z0-9_]{1,15})\/status\/(\d+)/); + if (match) return { username: match[1], statusId: match[2] }; + } + return null; +} + +function hideArticle(article, username, country) { + article.dataset.xGeoBlockState = "blocked"; + const container = article.closest('[data-testid="cellInnerDiv"]') || article; + container.classList.add("x-geoblock-hidden"); + let entries = hiddenByUser.get(username.toLowerCase()); + if (!entries) hiddenByUser.set(username.toLowerCase(), entries = new Set()); + entries.add(container); + + if (settings.showPlaceholder && !container.querySelector(":scope > .x-geoblock-placeholder")) { + const placeholder = document.createElement("button"); + placeholder.className = "x-geoblock-placeholder"; + placeholder.type = "button"; + placeholder.textContent = `Post hidden by X GeoBlock · @${username} · ${country}`; + placeholder.addEventListener("click", () => container.classList.toggle("x-geoblock-revealed")); + container.prepend(placeholder); + } +} + +function restoreAll() { + document.querySelectorAll(".x-geoblock-hidden").forEach((node) => { + node.classList.remove("x-geoblock-hidden", "x-geoblock-revealed"); + node.querySelector(":scope > .x-geoblock-placeholder")?.remove(); + }); + hiddenByUser.clear(); +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..57529b4 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,25 @@ +# Architecture + +## Request flow + +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//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. +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. The cache is limited to 2,000 entries and pruned to the 1,500 most recently checked entries when the limit is exceeded. + +## Browser components + +- `background.js`: networking, throttling, cache, and decisions. +- `content.js`: timeline observation and post visibility. +- `offscreen/`: isolated HTML parsing with `DOMParser`. +- `lib/parser.js`: DOM and embedded-data extraction. +- `lib/config.js`: defaults and country normalization. +- `options/` and `popup/`: user controls. + +## 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. diff --git a/docs/privacy.md b/docs/privacy.md new file mode 100644 index 0000000..ca216f9 --- /dev/null +++ b/docs/privacy.md @@ -0,0 +1,7 @@ +# Privacy + +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 post author links in X timelines only to decide whether to display those posts. It does not read or store post text. diff --git a/docs/releases.md b/docs/releases.md new file mode 100644 index 0000000..add97c4 --- /dev/null +++ b/docs/releases.md @@ -0,0 +1,15 @@ +# Releases + +Every non-release commit that reaches `main` starts `.github/workflows/release.yml`. The workflow updates the version in `manifest.json` and `package.json`, commits that change to `main`, runs the checks, builds both browser packages, creates a version tag, and publishes a GitHub release containing: + +- `x-geoblock-chrome-vX.Y.Z.zip` +- `x-geoblock-firefox-vX.Y.Z.xpi` + +The Firefox XPI is unsigned. It can be used for temporary installation and as the input for Mozilla Add-ons signing. + +## Version rules + +- A pull request whose head branch is exactly `development` and whose base is `main` increments the minor component and resets patch to zero: `1.4.7` becomes `1.5.0`. +- Every other commit reaching `main`, including direct commits and merges from `hotfix/*`, increments the patch component: `1.4.7` becomes `1.4.8`. + +The automated version commit contains `[skip release]`, preventing a second workflow release. The repository must allow GitHub Actions to push commits and tags to `main`; if branch protection is enabled, grant the Actions bot an appropriate bypass or use an equivalent ruleset exception. diff --git a/lib/config.js b/lib/config.js new file mode 100644 index 0000000..b9efed9 --- /dev/null +++ b/lib/config.js @@ -0,0 +1,43 @@ +(function (root) { + "use strict"; + + const DEFAULT_SETTINGS = Object.freeze({ + enabled: true, + blacklist: ["Belarus", "China", "Iran", "North Korea", "Russia"], + cacheTtlHours: 168, + showPlaceholder: false + }); + + const COUNTRY_ALIASES = Object.freeze({ + "russian federation": "russia", + "people's republic of china": "china", + "iran, islamic republic of": "iran", + "democratic people's republic of korea": "north korea", + "dprk": "north korea", + "republic of korea": "south korea", + "united states of america": "united states", + "usa": "united states", + "uk": "united kingdom" + }); + + function normalizeCountry(value) { + const normalized = String(value || "") + .normalize("NFKD") + .replace(/[\u0300-\u036f]/g, "") + .trim() + .replace(/\s+/g, " ") + .toLowerCase(); + return COUNTRY_ALIASES[normalized] || normalized; + } + + function isBlacklisted(country, blacklist) { + const candidate = normalizeCountry(country); + return Boolean(candidate) && (blacklist || []).some( + (entry) => normalizeCountry(entry) === candidate + ); + } + + const api = { DEFAULT_SETTINGS, normalizeCountry, isBlacklisted }; + root.XGeoConfig = api; + if (typeof module !== "undefined") module.exports = api; +})(typeof globalThis !== "undefined" ? globalThis : this); diff --git a/lib/parser.js b/lib/parser.js new file mode 100644 index 0000000..7f472df --- /dev/null +++ b/lib/parser.js @@ -0,0 +1,96 @@ +(function (root) { + "use strict"; + + const LOCATION_PATH_PREFIX = "M12 7c-1.93 0-3.5 1.57-3.5 3.5"; + const BASED_IN_LABELS = [ + "account based in", "cuenta con sede en", "compte basé en", "konto mit sitz in", + "account gevestigd in", "conta sediada em", "account con sede in" + ]; + const FOLLOWING_LABELS = ["following", "siguiendo", "abonné", "abonniert", "seguindo", "seguiti"]; + + function clean(value) { + return String(value || "").replace(/\s+/g, " ").trim(); + } + + function findUserRecord(value, username, seen = new Set(), depth = 0) { + if (!value || typeof value !== "object" || depth > 14 || seen.has(value)) return null; + seen.add(value); + + const legacy = value.legacy && typeof value.legacy === "object" ? value.legacy : value; + const screenName = legacy.screen_name || value.screen_name || value.username; + if (screenName && String(screenName).toLowerCase() === username.toLowerCase()) { + const following = legacy.following ?? value.following; + const location = legacy.location || value.location; + return { + following: typeof following === "boolean" ? following : null, + location: typeof location === "string" ? clean(location) : null + }; + } + + for (const child of Object.values(value)) { + const found = findUserRecord(child, username, seen, depth + 1); + if (found) return found; + } + return null; + } + + function extractEmbeddedUser(document, username) { + for (const script of document.querySelectorAll("script")) { + const text = script.textContent && script.textContent.trim(); + if (!text || text.length < 2 || (text[0] !== "{" && text[0] !== "[")) continue; + try { + const found = findUserRecord(JSON.parse(text), username); + if (found) return found; + } catch (_) { + // Most scripts are JavaScript, not JSON. + } + } + return null; + } + + function extractCountryFromDom(document) { + const paths = Array.from(document.querySelectorAll("svg path")); + const locationPath = paths.find((path) => (path.getAttribute("d") || "").startsWith(LOCATION_PATH_PREFIX)); + if (locationPath) { + const row = locationPath.closest('[data-testid="pivot"]') || locationPath.closest('[role="tab"]'); + if (row) { + const values = Array.from(row.querySelectorAll("span")) + .map((span) => clean(span.textContent)) + .filter(Boolean); + if (values.length >= 2) return values[values.length - 1]; + } + } + + for (const element of document.querySelectorAll("span, div")) { + const label = clean(element.textContent).toLowerCase(); + if (!BASED_IN_LABELS.includes(label)) continue; + const row = element.closest('[data-testid="pivot"]') || element.parentElement?.parentElement; + const values = row ? Array.from(row.querySelectorAll("span")).map((node) => clean(node.textContent)).filter(Boolean) : []; + const index = values.findIndex((value) => BASED_IN_LABELS.includes(value.toLowerCase())); + if (index >= 0 && values[index + 1]) return values[index + 1]; + } + return null; + } + + function extractFollowingFromDom(document) { + const button = document.querySelector('[data-testid$="-unfollow"]'); + if (button) return true; + const labels = Array.from(document.querySelectorAll("button, [role=button]")) + .map((node) => clean(node.textContent).toLowerCase()); + if (labels.some((label) => FOLLOWING_LABELS.includes(label))) return true; + return null; + } + + function parseAboutDocument(document, username) { + const embedded = extractEmbeddedUser(document, username) || {}; + return { + country: extractCountryFromDom(document), + following: embedded.following ?? extractFollowingFromDom(document), + profileLocation: embedded.location || null + }; + } + + const api = { clean, findUserRecord, extractCountryFromDom, parseAboutDocument }; + root.XGeoParser = api; + if (typeof module !== "undefined") module.exports = api; +})(typeof globalThis !== "undefined" ? globalThis : this); diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..786788d --- /dev/null +++ b/manifest.json @@ -0,0 +1,26 @@ +{ + "manifest_version": 3, + "name": "X GeoBlock", + "version": "1.0.0", + "description": "Hide posts from X accounts based in countries you choose.", + "permissions": ["storage", "offscreen"], + "host_permissions": ["https://x.com/*"], + "background": { + "service_worker": "background.js" + }, + "content_scripts": [ + { + "matches": ["https://x.com/*"], + "js": ["content.js"], + "css": ["content.css"], + "run_at": "document_idle" + } + ], + "options_page": "options/options.html", + "action": { + "default_title": "X GeoBlock", + "default_popup": "popup/popup.html" + }, + "web_accessible_resources": [], + "minimum_chrome_version": "109" +} diff --git a/offscreen/offscreen.html b/offscreen/offscreen.html new file mode 100644 index 0000000..041691d --- /dev/null +++ b/offscreen/offscreen.html @@ -0,0 +1,3 @@ + +X GeoBlock parser + diff --git a/offscreen/offscreen.js b/offscreen/offscreen.js new file mode 100644 index 0000000..40cef32 --- /dev/null +++ b/offscreen/offscreen.js @@ -0,0 +1,14 @@ +"use strict"; + +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 }); + } + return false; +}); diff --git a/options/options.css b/options/options.css new file mode 100644 index 0000000..3edceaf --- /dev/null +++ b/options/options.css @@ -0,0 +1,9 @@ +: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; } diff --git a/options/options.html b/options/options.html new file mode 100644 index 0000000..96ffb2c --- /dev/null +++ b/options/options.html @@ -0,0 +1,15 @@ + +X GeoBlock settings +
+

X GeoBlock

Hide posts based on the country shown in an account's About page.

+
+ + +

Enter one country per line, exactly as X displays it.

+ + + +
+

+
+
diff --git a/options/options.js b/options/options.js new file mode 100644 index 0000000..18ac54e --- /dev/null +++ b/options/options.js @@ -0,0 +1,33 @@ +"use strict"; +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 status = document.querySelector("#status"); + +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; +} +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 + }); + status.textContent = "Settings saved."; + setTimeout(() => status.textContent = "", 2000); +}); +document.querySelector("#clear").addEventListener("click", async () => { + await extensionApi.runtime.sendMessage({ type: "clear-cache" }); + status.textContent = "User cache cleared."; + setTimeout(() => status.textContent = "", 2000); +}); diff --git a/package.json b/package.json new file mode 100644 index 0000000..d6d1c73 --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "x-geoblock", + "version": "1.0.0", + "private": true, + "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" + }, + "engines": { "node": ">=18" }, + "license": "MIT" +} diff --git a/popup/popup.css b/popup/popup.css new file mode 100644 index 0000000..2145069 --- /dev/null +++ b/popup/popup.css @@ -0,0 +1 @@ +: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; } diff --git a/popup/popup.html b/popup/popup.html new file mode 100644 index 0000000..c6fb14b --- /dev/null +++ b/popup/popup.html @@ -0,0 +1,2 @@ +X GeoBlock +

X GeoBlock

diff --git a/popup/popup.js b/popup/popup.js new file mode 100644 index 0000000..a8bc57a --- /dev/null +++ b/popup/popup.js @@ -0,0 +1,10 @@ +"use strict"; +const extensionApi = globalThis.browser || chrome; +const enabled = document.querySelector("#enabled"); +const summary = document.querySelector("#summary"); +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.`; +}); +enabled.addEventListener("change", () => extensionApi.storage.sync.set({ enabled: enabled.checked })); +document.querySelector("#settings").addEventListener("click", () => extensionApi.runtime.openOptionsPage()); diff --git a/scripts/build.mjs b/scripts/build.mjs new file mode 100644 index 0000000..86682c7 --- /dev/null +++ b/scripts/build.mjs @@ -0,0 +1,53 @@ +import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +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" +]; + +rmSync(dist, { recursive: true, force: true }); +mkdirSync(dist, { recursive: true }); + +function prepare(target, manifest, extraFiles = []) { + const targetDirectory = join(dist, target); + mkdirSync(targetDirectory, { recursive: true }); + for (const source of [...sharedFiles, ...extraFiles]) { + cpSync(join(root, source), join(targetDirectory, source), { recursive: true }); + } + writeFileSync(join(targetDirectory, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); + return targetDirectory; +} + +const chromeDirectory = prepare("chrome", baseManifest, ["offscreen"]); + +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"] +}; +firefoxManifest.browser_specific_settings = { + gecko: { + id: "x-geoblock@dasemu.github.io", + strict_min_version: "109.0" + } +}; +const firefoxDirectory = prepare("firefox", firefoxManifest); + +function archive(directory, filename) { + const result = spawnSync("zip", ["-q", "-r", join(dist, filename), "."], { + cwd: directory, + stdio: "inherit" + }); + if (result.status !== 0) throw new Error(`zip failed for ${filename}`); +} + +archive(chromeDirectory, `x-geoblock-chrome-v${version}.zip`); +archive(firefoxDirectory, `x-geoblock-firefox-v${version}.xpi`); +console.log(`Built Chromium ZIP and Firefox XPI for v${version}.`); diff --git a/scripts/bump-version.mjs b/scripts/bump-version.mjs new file mode 100644 index 0000000..fc61a34 --- /dev/null +++ b/scripts/bump-version.mjs @@ -0,0 +1,31 @@ +import { readFileSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const kind = process.argv[2]; +if (!new Set(["patch", "minor"]).has(kind)) { + console.error("Usage: node scripts/bump-version.mjs "); + process.exit(2); +} + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const manifestPath = resolve(root, "manifest.json"); +const packagePath = resolve(root, "package.json"); +const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); +const packageJson = JSON.parse(readFileSync(packagePath, "utf8")); +const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(manifest.version); +if (!match) throw new Error(`Unsupported version: ${manifest.version}`); + +let [, major, minor, patch] = match.map(Number); +if (kind === "minor") { + minor += 1; + patch = 0; +} else { + patch += 1; +} +const version = `${major}.${minor}.${patch}`; +manifest.version = version; +packageJson.version = version; +writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); +writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`); +console.log(version); diff --git a/tests/parser.test.js b/tests/parser.test.js new file mode 100644 index 0000000..7f5e954 --- /dev/null +++ b/tests/parser.test.js @@ -0,0 +1,17 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { findUserRecord } = require("../lib/parser.js"); +const { normalizeCountry, isBlacklisted } = require("../lib/config.js"); + +test("finds following state in nested X user data", () => { + const source = { data: { user: { result: { legacy: { screen_name: "Alice", following: true, location: "Berlin" } } } } }; + assert.deepEqual(findUserRecord(source, "alice"), { following: true, location: "Berlin" }); +}); +test("does not confuse another user record", () => { + assert.equal(findUserRecord({ legacy: { screen_name: "Bob", following: false } }, "alice"), null); +}); +test("normalizes country aliases", () => { + assert.equal(normalizeCountry(" Russian Federation "), "russia"); + assert.equal(isBlacklisted("Russian Federation", ["Russia"]), true); + assert.equal(isBlacklisted("Germany", ["Russia"]), false); +});