diff --git a/.github/workflows/tron-headless.yml b/.github/workflows/tron-headless.yml new file mode 100644 index 0000000..365120e --- /dev/null +++ b/.github/workflows/tron-headless.yml @@ -0,0 +1,147 @@ +# Build, smoke-test and publish ghcr.io/profullstack/tron-headless: the +# TronBrowser engine headless with CDP on :9222, for c0mpute browser nodes. +# Contract: docker/tron-headless/README.md. +# +# Pull requests that touch the image: build + smoke test, push nothing. +# v* tags (every TronBrowser release) and workflow_dispatch: smoke test, then +# push :vX.Y.Z and :latest (linux/amd64). Nothing is uploaded as a workflow +# artifact; the registry is the only output. +# +# Visibility: GHCR creates org packages PRIVATE and has no API to change it, so +# it is one click by an org admin: github.com/orgs/profullstack/packages -> +# tron-headless -> Package settings -> Change visibility -> Public. The last +# step warns until an anonymous pull works. +name: tron-headless image + +on: + push: + tags: ['v*'] + pull_request: + paths: + - 'docker/tron-headless/**' + - '.github/workflows/tron-headless.yml' + workflow_dispatch: + inputs: + version: + description: 'Tag to publish, e.g. 3.21.0 (pushed as v3.21.0 and latest)' + required: true + +permissions: + contents: read + +env: + IMAGE: ghcr.io/profullstack/tron-headless + +concurrency: + group: tron-headless-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + smoke: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + # The smoke script has no dependencies; without this, setup-node v5 + # sees package.json's packageManager and looks for pnpm. + package-manager-cache: false + + - name: Build + run: docker build -t tron-headless:ci docker/tron-headless + + - name: Run with the c0mpute node's flags + run: | + docker run -d --name th \ + --cap-drop ALL --security-opt no-new-privileges \ + --shm-size 1g --memory 2g \ + -p 127.0.0.1:9222:9222 tron-headless:ci + test "$(docker exec th id -u):$(docker exec th id -g)" = "1000:1000" + + - name: CDP smoke test (version, attach, navigate, screencast, screenshot) + run: node docker/tron-headless/smoke.mjs http://127.0.0.1:9222 + + - name: The container exits when its command exits + run: | + set -eu + docker run -d --name th-exit --cap-drop ALL --security-opt no-new-privileges \ + --shm-size 1g tron-headless:ci bash -c 'sleep 3; exit 7' + code=$(timeout 60 docker wait th-exit) + test "$code" = "7" + + - name: Container logs + if: always() + run: docker logs th 2>&1 | grep -v -E 'dbus|GLib-GIO' | tail -40 || true + + publish: + needs: smoke + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + packages: write + steps: + - id: v + env: + EVENT: ${{ github.event_name }} + INPUT_VERSION: ${{ inputs.version }} + REF_NAME: ${{ github.ref_name }} + run: | + set -eu + if [ "$EVENT" = "workflow_dispatch" ]; then v="${INPUT_VERSION#v}"; else v="${REF_NAME#v}"; fi + echo "$v" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' || { echo "not a release version: $v" >&2; exit 1; } + echo "tag=v$v" >> "$GITHUB_OUTPUT" + echo "version=$v" >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@v5 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push + id: build + uses: docker/build-push-action@v6 + with: + context: docker/tron-headless + platforms: linux/amd64 + push: true + tags: | + ${{ env.IMAGE }}:${{ steps.v.outputs.tag }} + ${{ env.IMAGE }}:latest + labels: | + org.opencontainers.image.source=https://github.com/${{ github.repository }} + org.opencontainers.image.url=https://tronbrowser.dev + org.opencontainers.image.title=tron-headless + org.opencontainers.image.description=TronBrowser engine (ungoogled-chromium) headless, CDP on :9222, for c0mpute browser nodes + org.opencontainers.image.licenses=MIT + org.opencontainers.image.version=${{ steps.v.outputs.version }} + org.opencontainers.image.revision=${{ github.sha }} + + - name: Inspect + env: + TAG: ${{ steps.v.outputs.tag }} + DIGEST: ${{ steps.build.outputs.digest }} + run: | + docker buildx imagetools inspect "${IMAGE}:${TAG}" + echo "${IMAGE}:${TAG} @ ${DIGEST}" >> "$GITHUB_STEP_SUMMARY" + + - name: Check anonymous pull (package visibility) + env: + TAG: ${{ steps.v.outputs.tag }} + run: | + token=$(curl -fsS "https://ghcr.io/token?scope=repository:profullstack/tron-headless:pull" | jq -r .token) + code=$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $token" \ + -H 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json' \ + "https://ghcr.io/v2/profullstack/tron-headless/manifests/${TAG}") + if [ "$code" = "200" ]; then + echo "anonymous pull works" >> "$GITHUB_STEP_SUMMARY" + else + echo "::warning::ghcr.io/profullstack/tron-headless is not public (HTTP $code): an org admin must set Package settings -> Change visibility -> Public" + echo "ghcr.io/profullstack/tron-headless is PRIVATE (HTTP $code): make it public in package settings" >> "$GITHUB_STEP_SUMMARY" + fi diff --git a/.github/workflows/windows-pit.yml b/.github/workflows/windows-pit.yml index d58eb64..4e69f8d 100644 --- a/.github/workflows/windows-pit.yml +++ b/.github/workflows/windows-pit.yml @@ -5,7 +5,7 @@ on: branches: [main] paths: - 'apps/desktop/launcher/**' - - 'apps/desktop/test/test_windows_pit.py' + - 'apps/desktop/test/test_*.py' - 'apps/desktop/test/windows_pit_acceptance.py' - 'apps/desktop/test/windows-pit-browser.mjs' - 'apps/desktop/test/browser-driver/**' @@ -17,7 +17,7 @@ on: pull_request: paths: - 'apps/desktop/launcher/**' - - 'apps/desktop/test/test_windows_pit.py' + - 'apps/desktop/test/test_*.py' - 'apps/desktop/test/windows_pit_acceptance.py' - 'apps/desktop/test/windows-pit-browser.mjs' - 'apps/desktop/test/browser-driver/**' @@ -45,7 +45,7 @@ jobs: with: python-version: '3.12' - name: Test helper and Windows launcher (no certificate imports) - run: python -B -m unittest discover -s apps/desktop/test -p test_windows_pit.py -v + run: python -B -m unittest discover -s apps/desktop/test -p 'test_*.py' -v windows-browser: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository diff --git a/README.md b/README.md index d621a43..06db03d 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,16 @@ tron version > clearnet names untouched. For every app on the box run `moshcode dns enable` > instead. Details: [`docs/moshpit-pit-toggle.md`](docs/moshpit-pit-toggle.md). +> **🌱 Scallion** (Settings, and a sidebar button) is c0mpute's onion-style relay +> network. It is **off by default, experimental and unreviewed**, and today it +> cannot carry TronBrowser's traffic: the setting shows the c0mpute CLI's own +> readiness check and its blockers, and only routes once that check passes and a +> local Scallion SOCKS client is running. Details: [`docs/scallion.md`](docs/scallion.md). +> +> **`ghcr.io/profullstack/tron-headless`** is a headless Tron engine image with +> CDP on port 9222, used by c0mpute browser nodes. Details: +> [`docker/tron-headless/README.md`](docker/tron-headless/README.md). + Also packaged for **macOS · Windows · Debian/Ubuntu (.deb) · Fedora/RHEL (.rpm) · Arch (AUR) · Gentoo · NixOS · Snap · Flatpak · AppImage · FreeBSD** — and arm64 Linux phones (Librem 5 / PinePhone / Ubuntu Touch). See diff --git a/apps/desktop/extensions/ai-sidebar/background-helper.test.js b/apps/desktop/extensions/ai-sidebar/background-helper.test.js index 7055c8e..54c9a2f 100644 --- a/apps/desktop/extensions/ai-sidebar/background-helper.test.js +++ b/apps/desktop/extensions/ai-sidebar/background-helper.test.js @@ -71,6 +71,55 @@ describe('extension network helper requests', () => { expectSimpleRequests(); }); + it('refuses Scallion while the doctor is not ready and never touches the proxy', async () => { + fetchMock.mockImplementation(async (url) => ({ + ok: true, + json: async () => url.endsWith('/scallion/start') + ? { started: false, routing: false, ready: false, error: 'not-ready', blockers: ['independent security review is outstanding'] } + : {}, + })); + const res = await send({ type: 'scallion-set', on: true }); + expect(res).toMatchObject({ enabled: false, error: 'not-ready' }); + expect(res.status.blockers).toEqual(['independent security review is outstanding']); + expect(chrome.proxy.settings.set).not.toHaveBeenCalled(); + expect(helperCalls().map(([url, options]) => [new URL(url).pathname, options.method])) + .toEqual([['/scallion/start', 'POST']]); + expectSimpleRequests(); + }); + + it('routes through a ready Scallion SOCKS client and reverts when traffic does not flow', async () => { + let verify = false; + fetchMock.mockImplementation(async (url) => { + if (url.startsWith('https://my.ip.pit.world/')) { + if (!verify) throw new Error('socks dead'); + return { ok: true, json: async () => ({ ip: '203.0.113.7' }) }; + } + return { + ok: true, + json: async () => url.endsWith('/scallion/start') + ? { started: true, routing: true, ready: true, socks: '127.0.0.1:9095', host: '127.0.0.1', port: 9095 } + : { stopped: true }, + }; + }); + const failed = await send({ type: 'scallion-set', on: true }); + expect(failed).toMatchObject({ enabled: false, error: 'verify-failed' }); + const sets = chrome.proxy.settings.set.mock.calls.map(([arg]) => arg.value); + expect(sets[0].rules.singleProxy).toEqual({ scheme: 'socks5', host: '127.0.0.1', port: 9095 }); + expect(sets.at(-1)).toEqual({ mode: 'system' }); + expect(helperCalls().map(([url]) => new URL(url).pathname)).toEqual(['/scallion/start', '/scallion/stop']); + + verify = true; + expect(await send({ type: 'scallion-set', on: true })).toMatchObject({ enabled: true, check: { ok: true, ip: '203.0.113.7' } }); + expect(chrome.privacy.network.webRTCIPHandlingPolicy.set).toHaveBeenCalledWith({ value: 'disable_non_proxied_udp' }); + }); + + it('keeps Scallion and Tor exclusive', async () => { + chrome.storage.local.get.mockResolvedValue({ torEnabled: true }); + expect(await send({ type: 'scallion-set', on: true })).toMatchObject({ enabled: false, error: 'tor-on' }); + chrome.storage.local.get.mockResolvedValue({ scallionEnabled: true }); + expect(await send({ type: 'pit-set', on: true })).toMatchObject({ enabled: false, error: 'scallion-on' }); + }); + it('uses POST for Tor mutations and GET only for status', async () => { expect(await send({ type: 'tor-set', on: true })).toMatchObject({ enabled: true }); expect(await send({ type: 'tor-set', on: false })).toEqual({ enabled: false }); diff --git a/apps/desktop/extensions/ai-sidebar/background.js b/apps/desktop/extensions/ai-sidebar/background.js index 812596b..e3d05c0 100644 --- a/apps/desktop/extensions/ai-sidebar/background.js +++ b/apps/desktop/extensions/ai-sidebar/background.js @@ -1,5 +1,6 @@ import { decideInstallTarget, lookupInstalled } from './install-state.js'; import { PIT_SOCKS_PORT, pitProxyConfig } from './pit-proxy.js'; +import { SCALLION_CHECK_URL, parseLoopbackSocks, scallionProxyConfig } from './scallion.js'; import { installPush } from './push-client.js'; import { PIT_DIRECT_RULES, w3bsFromSearch } from './w3bs.js'; @@ -168,9 +169,9 @@ const TOR_CHECK_URL = 'https://check.torproject.org/api/ip'; // to Tor until the user flips it on. const TOR_HELPER = 'http://127.0.0.1:9061'; -async function helperJson(path, method) { +async function helperJson(path, method, timeoutMs = 8000) { const ctrl = new AbortController(); - const t = setTimeout(() => ctrl.abort(), 8000); + const t = setTimeout(() => ctrl.abort(), timeoutMs); try { const res = await fetch(`${TOR_HELPER}${path}`, { method, signal: ctrl.signal }); return await res.json().catch(() => ({})); @@ -287,11 +288,16 @@ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => { if (msg.on) { // Tor and the pit are exclusive: the pit's PAC asks the system resolver // about every host, which under Tor would leak lookups outside it. - const { pitEnabled } = await chrome.storage.local.get('pitEnabled'); + const { pitEnabled, scallionEnabled } = await chrome.storage.local.get(['pitEnabled', 'scallionEnabled']); if (pitEnabled) { await disablePit(); await stopPitViaHelper(); } + // Tor and Scallion both own the whole proxy; only one at a time. + if (scallionEnabled) { + await disableScallion(); + await stopScallionViaHelper(); + } const started = await startTorViaHelper(); if (started.error === 'unreachable') { sendResponse({ enabled: false, started: { error: 'unreachable' } }); @@ -483,9 +489,9 @@ async function enablePit() { } async function disablePit() { - // Only hand the proxy back to the OS when Tor is not holding it. - const { torEnabled } = await chrome.storage.local.get('torEnabled'); - if (!torEnabled) { + // Only hand the proxy back to the OS when Tor or Scallion is not holding it. + const { torEnabled, scallionEnabled } = await chrome.storage.local.get(['torEnabled', 'scallionEnabled']); + if (!torEnabled && !scallionEnabled) { try { await chrome.proxy.settings.set({ value: { mode: 'system' }, scope: 'regular' }); } catch (_) { /* fall through to clear */ } @@ -537,11 +543,15 @@ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => { if (msg?.type === 'pit-set') { (async () => { if (msg.on) { - const { torEnabled } = await chrome.storage.local.get('torEnabled'); + const { torEnabled, scallionEnabled } = await chrome.storage.local.get(['torEnabled', 'scallionEnabled']); if (torEnabled) { sendResponse({ enabled: false, error: 'tor-on' }); return; } + if (scallionEnabled) { + sendResponse({ enabled: false, error: 'scallion-on' }); + return; + } const started = await startPitViaHelper(); if (!started.started) { sendResponse({ enabled: false, error: started.error || 'pit-failed' }); @@ -566,25 +576,170 @@ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => { } }); +// --- Scallion (c0mpute network) ----------------------------------------- +// Off by default and fail closed. The helper decides whether routing is even +// allowed (doctor ready:true AND a loopback `socks` it can connect to); today it +// never is, so 'scallion-set' on returns the doctor's blockers. When it is, the +// proxy goes on exactly like Tor's (SOCKS5 + WebRTC guard), traffic is verified, +// and any failure reverts to normal browsing. Exclusive with Tor and the pit. +// Experimental and unreviewed; not anonymity. See docs/scallion.md. +async function scallionStatusViaHelper() { + try { + const st = await helperJson('/scallion/status', 'GET', 30000); + if (st && st.error === 'not-found') return { error: 'helper-stale' }; + return st; + } catch (_) { + return { error: 'unreachable' }; + } +} + +async function stopScallionViaHelper() { + try { + await helperJson('/scallion/stop', 'POST', 5000); + } catch (_) { /* helper not running: nothing to stop */ } +} + +async function setScallionBadge(on) { + try { + await chrome.action.setBadgeText({ text: on ? 'SCL' : '' }); + await chrome.action.setBadgeBackgroundColor({ color: '#c47f00' }); + await chrome.action.setTitle({ title: on ? 'TronBrowser: Scallion ON (experimental)' : 'TronBrowser' }); + } catch (_) { /* action API may be unavailable */ } +} + +async function enableScallion(socks) { + await chrome.proxy.settings.set({ value: scallionProxyConfig(socks), scope: 'regular' }); + try { + await chrome.privacy.network.webRTCIPHandlingPolicy.set({ value: 'disable_non_proxied_udp' }); + } catch (_) { /* privacy controlled elsewhere */ } + await chrome.storage.local.set({ scallionEnabled: true }); + try { await chrome.storage.session.set({ scallionSession: true }); } catch (_) { /* no-op */ } + await setScallionBadge(true); +} + +async function disableScallion() { + // Same order as Tor: force 'system' first so a stopped client never leaves a + // dead fixed_servers proxy behind. + try { + await chrome.proxy.settings.set({ value: { mode: 'system' }, scope: 'regular' }); + } catch (_) { /* fall through to clear */ } + try { await chrome.proxy.settings.clear({ scope: 'regular' }); } catch (_) { /* already clear */ } + try { await chrome.privacy.network.webRTCIPHandlingPolicy.clear({}); } catch (_) { /* already clear */ } + await chrome.storage.local.set({ scallionEnabled: false }); + try { await chrome.storage.session.remove('scallionSession'); } catch (_) { /* no-op */ } + await setScallionBadge(false); +} + +async function checkScallion() { + try { + const ctrl = new AbortController(); + const t = setTimeout(() => ctrl.abort(), 20000); + const res = await fetch(SCALLION_CHECK_URL, { cache: 'no-store', signal: ctrl.signal }); + clearTimeout(t); + if (!res.ok) return { ok: false, error: `HTTP ${res.status}` }; + const data = await res.json(); + return { ok: true, ip: data.ip || data.ipv4 || data.ipv6 || null }; + } catch (e) { + return { ok: false, error: String((e && e.message) || e) }; + } +} + +chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => { + if (msg?.type === 'scallion-status') { + (async () => { + const { scallionEnabled } = await chrome.storage.local.get('scallionEnabled'); + sendResponse({ enabled: !!scallionEnabled, status: await scallionStatusViaHelper() }); + })(); + return true; + } + if (msg?.type === 'scallion-install') { + (async () => { + let st; + try { + st = await helperJson('/scallion/install', 'POST', 300000); + if (st && st.error === 'not-found') st = { error: 'helper-stale' }; + } catch (_) { + st = { error: 'unreachable' }; + } + sendResponse({ enabled: false, status: st }); + })(); + return true; + } + if (msg?.type === 'scallion-set') { + (async () => { + if (!msg.on) { + await disableScallion(); + await stopScallionViaHelper(); + sendResponse({ enabled: false, status: await scallionStatusViaHelper() }); + return; + } + const { torEnabled, pitEnabled } = await chrome.storage.local.get(['torEnabled', 'pitEnabled']); + if (torEnabled) { + sendResponse({ enabled: false, error: 'tor-on' }); + return; + } + let started; + try { + started = await helperJson('/scallion/start', 'POST', 45000); + } catch (_) { + started = { error: 'unreachable' }; + } + if (started && started.error === 'not-found') started = { error: 'helper-stale' }; + const socks = started && started.started && started.routing && started.ready + ? parseLoopbackSocks(started.socks) + : null; + if (!socks) { + sendResponse({ enabled: false, error: (started && started.error) || 'scallion-failed', status: started }); + return; + } + if (pitEnabled) { + await disablePit(); + await stopPitViaHelper(); + } + await enableScallion(socks); + const check = await checkScallion(); + if (!check.ok) { + // Never leave a dead proxy: back to normal browsing. + await disableScallion(); + await stopScallionViaHelper(); + sendResponse({ enabled: false, error: 'verify-failed', check, status: started }); + return; + } + sendResponse({ enabled: true, check, status: started }); + })(); + return true; + } +}); + // Tor and the pit default OFF on every fresh browser start — nobody is routed // anywhere unless they flip a toggle. chrome.storage.session is wiped on // browser restart, so it tells a fresh launch from a service-worker restart // mid-session. (async () => { try { - const { torSession, pitSession } = await chrome.storage.session.get(['torSession', 'pitSession']); + const { torSession, pitSession, scallionSession } = + await chrome.storage.session.get(['torSession', 'pitSession', 'scallionSession']); if (torSession) { // Same session, SW just restarted → keep Tor on (re-apply the proxy). await enableTor(); } else if (pitSession) { await enablePit(); + } else if (scallionSession) { + // Re-apply only while the helper still has routing cleared; otherwise + // fail closed back to normal browsing. + const st = await scallionStatusViaHelper(); + const socks = st && st.routing && st.ready ? parseLoopbackSocks(st.socks) : null; + if (socks) await enableScallion(socks); + else await disableScallion(); } else { // Fresh browser start. If local still says a toggle was on (carried over // from the last run), clear it + any persisted proxy. Otherwise leave the // proxy untouched. - const { torEnabled, pitEnabled } = await chrome.storage.local.get(['torEnabled', 'pitEnabled']); + const { torEnabled, pitEnabled, scallionEnabled } = + await chrome.storage.local.get(['torEnabled', 'pitEnabled', 'scallionEnabled']); if (torEnabled) await disableTor(); else if (pitEnabled) { await disablePit(); await stopPitViaHelper(); } + else if (scallionEnabled) { await disableScallion(); await stopScallionViaHelper(); } } } catch (_) { /* best effort */ } })(); diff --git a/apps/desktop/extensions/ai-sidebar/options.html b/apps/desktop/extensions/ai-sidebar/options.html index 8b936da..a43cba8 100644 --- a/apps/desktop/extensions/ai-sidebar/options.html +++ b/apps/desktop/extensions/ai-sidebar/options.html @@ -46,6 +46,15 @@ .pw-dialog button { border-radius:8px; padding:8px 14px; font:inherit; cursor:pointer; background:transparent; color:var(--fg); border:1px solid var(--line); } .pw-dialog button.primary { background:var(--cyan); color:#04060c; border:0; font-weight:700; } + .scl-box { border:1px solid var(--line); border-radius:10px; padding:12px 14px; margin-top:12px; } + .scl-title { font-weight:700; } + .scl-title.warn { color:#ffcf6b; } .scl-title.on { color:#a6ff1a; } + .scl-blockers { margin:8px 0 0; padding-left:18px; color:var(--muted); font-size:12px; } + .scl-toggle { display:flex; gap:8px; align-items:center; color:var(--fg); } + .scl-toggle input { width:auto; } + .scl-toggle:has(input:disabled) { opacity:.55; } + .scl-tail { background:#04060c; border:1px solid var(--line); border-radius:8px; padding:8px; + font-size:11px; max-height:220px; overflow:auto; white-space:pre-wrap; } @@ -89,6 +98,33 @@

Name resolution

name still needs the certificate that moshcode dns enable installs.

+

Scallion (c0mpute network)

+

+ Scallion is the onion-style relay network being built on + c0mpute. It is + experimental and unreviewed: no independent security review, no + multi-host or leak testing yet. It is off by default, and it is + not anonymity. TronBrowser only routes through it when the c0mpute CLI's own + check (c0mpute scallion doctor) says the Scallion client is ready and + a local Scallion SOCKS client is running; otherwise nothing changes. Like + 🧅 Tor and 🤘 Pit, only one of the three can be on at a time. +

+
+
Checking…
+
+ + +
+ + +
+ + +

Details: docs/scallion.md

+
+

Push notifications

Sites send browser notifications through a push service the browser chooses. @@ -193,5 +229,6 @@

Import / export O + diff --git a/apps/desktop/extensions/ai-sidebar/scallion-settings.js b/apps/desktop/extensions/ai-sidebar/scallion-settings.js new file mode 100644 index 0000000..42ebf38 --- /dev/null +++ b/apps/desktop/extensions/ai-sidebar/scallion-settings.js @@ -0,0 +1,81 @@ +// Settings page: the Scallion (c0mpute network) section. Everything goes +// through the background, which talks to the launcher's helper. See scallion.js +// for the states and docs/scallion.md for the contract. +import { SCALLION_INSTALL_COMMAND, scallionView } from './scallion.js'; + +const el = (id) => document.getElementById(id); +const ERRORS = { + 'tor-on': 'Turn 🧅 Tor off first: Tor and Scallion each take over the whole proxy.', + 'verify-failed': 'Traffic did not get through the Scallion client, so TronBrowser switched back to normal browsing.', + 'socks-unreachable': 'The doctor named a Scallion SOCKS client, but nothing answers on it.', +}; + +function render(res, note = '') { + const status = res && res.status; + const view = scallionView(status, !!(res && res.enabled)); + const title = el('sclTitle'); + title.textContent = view.title; + title.className = 'scl-title ' + (view.on ? 'on' : view.state === 'ready' ? '' : 'warn'); + el('sclDetail').textContent = (note ? note + ' ' : '') + view.detail; + + const list = el('sclBlockers'); + list.replaceChildren(...view.blockers.map((b) => { + const li = document.createElement('li'); + li.textContent = b; + return li; + })); + list.hidden = !view.blockers.length; + + const toggle = el('sclToggle'); + toggle.checked = view.on; + toggle.disabled = !view.canToggle; + + el('sclInstall').hidden = !view.canInstall; + el('sclInstallHint').hidden = !view.canInstall; + + const tail = status && status.install && Array.isArray(status.install.tail) ? status.install.tail : []; + const pre = el('sclTail'); + pre.textContent = tail.join('\n'); + pre.hidden = !tail.length; +} + +async function refresh(note) { + try { + render(await chrome.runtime.sendMessage({ type: 'scallion-status' }), note); + } catch (_) { + render({ status: { error: 'unreachable' } }, note); + } +} + +el('sclInstallCmd').textContent = SCALLION_INSTALL_COMMAND; + +el('sclRefresh').addEventListener('click', () => refresh()); + +el('sclInstall').addEventListener('click', async () => { + const btn = el('sclInstall'); + btn.disabled = true; + el('sclTitle').textContent = 'Installing the c0mpute CLI…'; + el('sclDetail').textContent = 'This can take a minute.'; + try { + const res = await chrome.runtime.sendMessage({ type: 'scallion-install' }); + const failed = res && res.status && res.status.install && res.status.install.error; + render(res, failed ? `Install did not finish (${failed}).` : ''); + } catch (e) { + await refresh(`Install failed: ${(e && e.message) || e}.`); + } finally { + btn.disabled = false; + } +}); + +el('sclToggle').addEventListener('change', async (e) => { + const on = e.target.checked; + e.target.disabled = true; + try { + const res = await chrome.runtime.sendMessage({ type: 'scallion-set', on }); + await refresh(res && !res.enabled && on ? ERRORS[res.error] || '' : ''); + } catch (err) { + await refresh(`Could not switch Scallion: ${(err && err.message) || err}.`); + } +}); + +refresh(); diff --git a/apps/desktop/extensions/ai-sidebar/scallion.js b/apps/desktop/extensions/ai-sidebar/scallion.js new file mode 100644 index 0000000..3947638 --- /dev/null +++ b/apps/desktop/extensions/ai-sidebar/scallion.js @@ -0,0 +1,92 @@ +// Scallion (c0mpute network): what the Scallion setting shows and installs. +// +// Scallion is c0mpute's onion-style relay network. Its client cannot carry +// browser traffic yet: `c0mpute scallion doctor` says ready:false and there is +// no local SOCKS client. So the setting is off by default and fails closed: the +// launcher's helper (tron-tor-helper, /scallion/*) clears routing only when the +// doctor says ready:true AND names a loopback `socks` endpoint, and the +// extension then routes through it the way the Tor toggle does (chrome.proxy +// SOCKS5 + the WebRTC guard), verifies, and reverts on failure. +// Experimental and unreviewed; never described as anonymity. Pure functions. +// See docs/scallion.md. + +/** Where the background confirms traffic still flows once the proxy is set. */ +export const SCALLION_CHECK_URL = 'https://my.ip.pit.world/?format=json'; + +/** The one-liner the Install button runs through the helper (CLI only, no worker service). */ +export const SCALLION_INSTALL_COMMAND = + 'curl -fsSL https://c0mpute.com/install.sh | sh -s -- --minimal --no-start --no-exec'; + +/** {host, port} for a loopback SOCKS endpoint "127.0.0.1:PORT", else null. */ +export function parseLoopbackSocks(value) { + if (typeof value !== 'string') return null; + const m = /^(127\.0\.0\.1|localhost|\[::1\]):(\d{1,5})$/.exec(value.trim()); + if (!m) return null; + const port = Number(m[2]); + if (!Number.isInteger(port) || port <= 0 || port > 65535) return null; + return { host: m[1] === '[::1]' ? '::1' : m[1], port }; +} + +/** chrome.proxy.settings value for the Scallion route (same shape as Tor's). */ +export function scallionProxyConfig(socks) { + const s = typeof socks === 'string' ? parseLoopbackSocks(socks) : socks; + if (!s || !s.host || !Number.isInteger(s.port)) throw new Error(`bad scallion socks: ${socks}`); + return { + mode: 'fixed_servers', + rules: { + // SOCKS5: Chromium resolves names at the proxy, so lookups go through it. + singleProxy: { scheme: 'socks5', host: s.host, port: s.port }, + bypassList: ['localhost', '127.0.0.1', '[::1]'], + }, + }; +} + +function blockersOf(status) { + const list = status && status.doctor && Array.isArray(status.doctor.blockers) ? status.doctor.blockers : []; + return list.filter((b) => typeof b === 'string'); +} + +/** + * What the UI says for a helper status + the extension's own routing flag. + * Returns { state, title, detail, blockers, canInstall, canToggle, on }. + * state: 'unreachable' | 'stale' | 'not-installed' | 'installing' | 'unknown' + * | 'not-ready' | 'ready' | 'on' + */ +export function scallionView(status, enabled = false) { + const base = { blockers: [], canInstall: false, canToggle: false, on: false, detail: '' }; + if (!status || status.error === 'unreachable') { + return { ...base, state: 'unreachable', title: 'TronBrowser helper not running', + detail: 'Scallion needs the launcher helper. Start TronBrowser through the launcher (or run tron upgrade). TronBrowser traffic is NOT going through Scallion.' }; + } + if (status.error === 'helper-stale' || status.error === 'not-found') { + return { ...base, state: 'stale', title: 'Helper is out of date', + detail: 'The running helper predates Scallion. Quit TronBrowser completely and relaunch it. TronBrowser traffic is NOT going through Scallion.' }; + } + if (status.install && status.install.running) { + return { ...base, state: 'installing', title: 'Installing the c0mpute CLI…', + detail: 'This can take a minute.' }; + } + if (!status.installed) { + return { ...base, state: 'not-installed', title: 'Not installed', canInstall: true, + detail: 'Scallion needs the c0mpute CLI. Install adds the CLI only (no worker service, nothing runs in the background). TronBrowser traffic is NOT going through Scallion.' }; + } + const version = status.version ? `c0mpute v${status.version}` : 'c0mpute'; + if (enabled && status.routing && status.ready) { + return { ...base, state: 'on', on: true, canToggle: true, title: 'On: routed through Scallion', + detail: `TronBrowser traffic goes through the Scallion SOCKS client at ${status.socks}. Scallion is experimental and unreviewed; this is not anonymity.` }; + } + if (!status.doctor) { + return { ...base, state: 'unknown', title: `Installed (${version})`, + detail: `Its Scallion doctor did not answer${status.error ? ` (${status.error})` : ''}; this CLI may predate Scallion. TronBrowser traffic is NOT going through Scallion.` }; + } + if (!status.ready) { + const blockers = blockersOf(status); + const why = status.doctor.ready === true && !status.socks + ? 'the doctor reports ready but no local Scallion SOCKS client is running' + : blockers.length ? blockers.join('; ') : 'the doctor reports not ready'; + return { ...base, state: 'not-ready', blockers, title: `Installed (${version}). Scallion client not ready`, + detail: `Scallion client not ready: ${why}. TronBrowser traffic is NOT going through Scallion.` }; + } + return { ...base, state: 'ready', canToggle: true, title: `Installed (${version}). Scallion client ready`, + detail: `A Scallion SOCKS client is up at ${status.socks}. Off: TronBrowser traffic is NOT going through Scallion. Scallion is experimental and unreviewed.` }; +} diff --git a/apps/desktop/extensions/ai-sidebar/scallion.test.js b/apps/desktop/extensions/ai-sidebar/scallion.test.js new file mode 100644 index 0000000..5bc6fb1 --- /dev/null +++ b/apps/desktop/extensions/ai-sidebar/scallion.test.js @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'vitest'; +import { parseLoopbackSocks, scallionProxyConfig, scallionView } from './scallion.js'; + +// What `c0mpute scallion doctor --mode native --json` prints today. +const DOCTOR_TODAY = { + mode: 'native', + ready: false, + production_ready: false, + blockers: ['native TUN client transport is not implemented', 'independent security review is outstanding'], + built_experimental: ['signed relay descriptors'], +}; +const installed = (extra = {}) => ({ + installed: true, path: '/home/u/.c0mpute/bin/c0mpute', version: '0.3.130', + doctor: DOCTOR_TODAY, ready: false, socks: null, routing: false, error: null, + install: { running: false, exitCode: null, tail: [], error: null }, ...extra, +}); + +describe('parseLoopbackSocks', () => { + it('accepts loopback endpoints only', () => { + expect(parseLoopbackSocks('127.0.0.1:9095')).toEqual({ host: '127.0.0.1', port: 9095 }); + expect(parseLoopbackSocks('[::1]:1080')).toEqual({ host: '::1', port: 1080 }); + for (const bad of ['10.0.0.1:9050', 'evil.example:1080', '127.0.0.1', '127.0.0.1:0', '127.0.0.1:99999', null, 9050]) { + expect(parseLoopbackSocks(bad)).toBeNull(); + } + }); +}); + +describe('scallionProxyConfig', () => { + it('is a SOCKS5 fixed_servers route with loopback bypassed, like Tor', () => { + expect(scallionProxyConfig('127.0.0.1:9095')).toEqual({ + mode: 'fixed_servers', + rules: { + singleProxy: { scheme: 'socks5', host: '127.0.0.1', port: 9095 }, + bypassList: ['localhost', '127.0.0.1', '[::1]'], + }, + }); + }); + it('refuses anything that is not a loopback endpoint', () => { + expect(() => scallionProxyConfig('10.0.0.1:9050')).toThrow(/bad scallion socks/); + }); +}); + +describe('scallionView', () => { + it('says not installed and offers Install', () => { + const v = scallionView({ installed: false, install: { running: false, tail: [] } }); + expect(v.state).toBe('not-installed'); + expect(v.title).toBe('Not installed'); + expect(v.canInstall).toBe(true); + expect(v.canToggle).toBe(false); + expect(v.detail).toContain('NOT going through Scallion'); + }); + + it('today: installed, not ready, toggle disabled, blockers listed', () => { + const v = scallionView(installed()); + expect(v.state).toBe('not-ready'); + expect(v.title).toBe('Installed (c0mpute v0.3.130). Scallion client not ready'); + expect(v.detail).toContain('native TUN client transport is not implemented'); + expect(v.detail).toContain('TronBrowser traffic is NOT going through Scallion.'); + expect(v.blockers).toEqual(DOCTOR_TODAY.blockers); + expect(v.canToggle).toBe(false); + expect(v.on).toBe(false); + }); + + it('a doctor that says ready without a SOCKS client is still not ready', () => { + const v = scallionView(installed({ doctor: { ...DOCTOR_TODAY, ready: true, blockers: [] } })); + expect(v.state).toBe('not-ready'); + expect(v.detail).toContain('no local Scallion SOCKS client'); + expect(v.canToggle).toBe(false); + }); + + it('ready: toggle enabled but still off until routed', () => { + const v = scallionView(installed({ ready: true, socks: '127.0.0.1:9095', doctor: { ...DOCTOR_TODAY, ready: true, socks: '127.0.0.1:9095', blockers: [] } })); + expect(v.state).toBe('ready'); + expect(v.canToggle).toBe(true); + expect(v.on).toBe(false); + expect(v.detail).toContain('NOT going through Scallion'); + }); + + it('only says "On" when the extension routes AND the helper cleared it', () => { + const ready = installed({ ready: true, socks: '127.0.0.1:9095', routing: true }); + expect(scallionView(ready, true).title).toBe('On: routed through Scallion'); + expect(scallionView(ready, false).on).toBe(false); + expect(scallionView({ ...ready, routing: false }, true).on).toBe(false); + expect(scallionView(ready, true).detail).toContain('not anonymity'); + }); + + it('covers a missing or stale helper', () => { + expect(scallionView({ error: 'unreachable' }).state).toBe('unreachable'); + expect(scallionView(undefined).state).toBe('unreachable'); + expect(scallionView({ error: 'helper-stale' }).state).toBe('stale'); + }); + + it('never promises anonymity', () => { + const states = [installed(), installed({ ready: true, socks: '127.0.0.1:1' }), + installed({ ready: true, socks: '127.0.0.1:1', routing: true })]; + for (const s of states) { + const text = Object.values(scallionView(s, true)).join(' '); + expect(text).not.toMatch(/\banonymous\b/i); + for (const m of text.matchAll(/anonymity/gi)) expect(text.slice(m.index - 4, m.index)).toBe('not '); + } + }); +}); diff --git a/apps/desktop/extensions/ai-sidebar/sidepanel.css b/apps/desktop/extensions/ai-sidebar/sidepanel.css index df666e7..23dd3a2 100644 --- a/apps/desktop/extensions/ai-sidebar/sidepanel.css +++ b/apps/desktop/extensions/ai-sidebar/sidepanel.css @@ -29,6 +29,8 @@ header button { background: transparent; border: 1px solid var(--line); color: v .tor-btn.busy { opacity: .6; cursor: progress; } /* The pit wears moshcode's acid green, so ON reads as "pit", not "Tor". */ #pit[aria-pressed="true"] { background: #a6ff1a; border-color: #a6ff1a; color: #0a1400; } +#scallion[aria-pressed="true"] { background: #c47f00; border-color: #c47f00; color: #fff; } +#scallion[aria-disabled="true"]:not([aria-pressed="true"]) { opacity: .55; } .tor-status { padding: 6px 12px; font-size: 12px; border-bottom: 1px solid var(--line); background: #0b1020; color: var(--muted); } .tor-status.ok { color: #6ee7a8; } diff --git a/apps/desktop/extensions/ai-sidebar/sidepanel.html b/apps/desktop/extensions/ai-sidebar/sidepanel.html index 1717e75..84c5741 100644 --- a/apps/desktop/extensions/ai-sidebar/sidepanel.html +++ b/apps/desktop/extensions/ai-sidebar/sidepanel.html @@ -16,6 +16,7 @@ + diff --git a/apps/desktop/extensions/ai-sidebar/sidepanel.js b/apps/desktop/extensions/ai-sidebar/sidepanel.js index bfbfe35..e2638fe 100644 --- a/apps/desktop/extensions/ai-sidebar/sidepanel.js +++ b/apps/desktop/extensions/ai-sidebar/sidepanel.js @@ -2,6 +2,7 @@ import { PROVIDERS, chatStream, effectiveConfig, DEFAULT_PROVIDER } from './prov import { renderMarkdown } from './markdown.js'; import { storageGet } from './net.js'; import { PIT_SOCKS_PORT } from './pit-proxy.js'; +import { scallionView } from './scallion.js'; const el = (id) => document.getElementById(id); @@ -284,6 +285,7 @@ async function toggleTor() { torBtn.classList.remove('busy'); torBtn.disabled = false; refreshPitState(); // turning Tor on takes the pit down + refreshScallionState(); // and Scallion } } @@ -348,6 +350,8 @@ async function togglePit() { const err = res && res.error; if (err === 'tor-on') { showNetStatus('warn', 'Turn 🧅 Tor off first — Moshpit names can’t resolve through Tor, and checking them would leak lookups outside it.'); + } else if (err === 'scallion-on') { + showNetStatus('warn', 'Turn 🌱 Scallion off first: it holds the whole proxy, and checking pit names would leak lookups outside it.'); } else if (err === 'unreachable') { showNetStatus('warn', 'Couldn’t reach the TronBrowser helper. Restart through the TronBrowser launcher. On Windows, use the complete ZIP and install Python 3.9+; loading only the extension cannot start the helper. On Linux/macOS, run tron upgrade if needed.'); } else if (err === 'pit-port-busy') { @@ -369,6 +373,72 @@ async function togglePit() { pitBtn.addEventListener('click', togglePit); +// --- Scallion toggle ----------------------------------------------------- +// c0mpute's relay network. Off by default and only switchable when the helper +// says the Scallion client is actually ready (it is not, today); otherwise a +// click shows the plain status. Install and details live in Settings. +const scallionBtn = el('scallion'); +function escHtml(s) { + const d = document.createElement('div'); + d.textContent = String(s ?? ''); + return d.innerHTML; +} +function setScallionButton(view) { + scallionBtn.setAttribute('aria-pressed', view.on ? 'true' : 'false'); + scallionBtn.setAttribute('aria-disabled', view.canToggle ? 'false' : 'true'); + scallionBtn.textContent = view.on ? '🌱 Scallion ON' : '🌱 Scallion'; + scallionBtn.title = `Scallion (c0mpute network, experimental): ${view.title}`; +} +function showScallionView(view, prefix = '') { + const kind = view.on ? 'ok' : view.state === 'ready' ? '' : 'warn'; + showNetStatus(kind, `${prefix}Scallion: ${escHtml(view.title)}. ${escHtml(view.detail)} ` + + 'Scallion settings'); + el('scallion-settings')?.addEventListener('click', (e) => { e.preventDefault(); chrome.runtime.openOptionsPage(); }); +} +async function scallionState() { + try { + const res = await chrome.runtime.sendMessage({ type: 'scallion-status' }); + return scallionView(res && res.status, !!(res && res.enabled)); + } catch (_) { + return scallionView({ error: 'unreachable' }); + } +} +async function refreshScallionState() { + setScallionButton(await scallionState()); +} + +const SCALLION_ERRORS = { + 'tor-on': 'Turn 🧅 Tor off first: Tor and Scallion each take over the whole proxy.', + 'verify-failed': 'Traffic did not get through the Scallion client, so TronBrowser switched back to normal browsing.', + 'socks-unreachable': 'The doctor named a Scallion SOCKS client, but nothing answers on it.', +}; + +async function toggleScallion() { + const view = await scallionState(); + setScallionButton(view); + if (!view.canToggle) { showScallionView(view); return; } + const turningOn = !view.on; + scallionBtn.classList.add('busy'); + scallionBtn.disabled = true; + if (turningOn) showNetStatus('', 'Checking the Scallion client…'); + try { + const res = await chrome.runtime.sendMessage({ type: 'scallion-set', on: turningOn }); + const after = await scallionState(); + setScallionButton(after); + if (!turningOn) hideNetStatus(); + else if (res && res.enabled) showScallionView(after); + else showScallionView(after, SCALLION_ERRORS[res && res.error] ? `${escHtml(SCALLION_ERRORS[res.error])} ` : ''); + } catch (e) { + showNetStatus('warn', 'Could not toggle Scallion: ' + escHtml((e && e.message) || e)); + } finally { + scallionBtn.classList.remove('busy'); + scallionBtn.disabled = false; + refreshTorState(); + refreshPitState(); + } +} +scallionBtn.addEventListener('click', toggleScallion); + // The ? next to the Tor button opens the same explainer on demand (info mode — // never enables Tor, whatever button closes it). el('tor-info').addEventListener('click', () => { @@ -377,4 +447,4 @@ el('tor-info').addEventListener('click', () => { torWarnDlg.showModal(); }); -(async () => { await loadConfig(); await consumePendingQuery(); await refreshTorState(); await refreshPitState(); })(); +(async () => { await loadConfig(); await consumePendingQuery(); await refreshTorState(); await refreshPitState(); await refreshScallionState(); })(); diff --git a/apps/desktop/launcher/tron-tor-helper b/apps/desktop/launcher/tron-tor-helper index e86682c..32e8cd9 100755 --- a/apps/desktop/launcher/tron-tor-helper +++ b/apps/desktop/launcher/tron-tor-helper @@ -19,6 +19,11 @@ Endpoints (POST/GET on 127.0.0.1): /pit/start start the Moshpit SOCKS5 resolver → {"started": true, "check": {…}} /pit/stop stop it → {"stopped": true} /pit/status {"running": bool, "port": int, "doh": url, "trust": {…}} + /scallion/status GET: c0mpute CLI + `scallion doctor` state (see docs/scallion.md) + /scallion/install install the c0mpute CLI only, on an explicit click + /scallion/start clear routing ONLY if the doctor is ready and names a + loopback SOCKS endpoint; otherwise 409 with the blockers + /scallion/stop → {"stopped": true} Single-instance: binds a fixed loopback port; a second copy exits cleanly when the port is taken, so the launcher can fire-and-forget it every launch. @@ -39,6 +44,7 @@ import ssl import struct import subprocess import sys +import tempfile import threading import time import urllib.error @@ -54,7 +60,7 @@ BUNDLED_DIR = os.environ.get("TRON_TOR_BIN_DIR", "") PIDFILE = os.environ.get("TRON_TOR_PIDFILE", "") # Bumped whenever the helper protocol/behaviour changes; the launcher kills a # stale helper so the current version always runs. -HELPER_VERSION = "3.4.4" +HELPER_VERSION = "3.5.0" _lock = threading.Lock() _proc = None # the running tor subprocess (or None) _ready = False # True once tor reported Bootstrapped 100% @@ -779,6 +785,273 @@ def pit_status(): "helper": "tronbrowser-network", "pid": os.getpid()} +# --- Scallion (c0mpute network) --------------------------------------------- +# Scallion is c0mpute's onion-style relay network. Its client cannot carry a +# browser's traffic yet: `c0mpute scallion doctor --mode native --json` says +# ready:false and lists the blockers, and there is no local SOCKS client. So this +# section is deliberately honest and fails closed: +# - status: is the c0mpute CLI installed, what does its doctor say; +# - install: the c0mpute CLI only (no worker service), on an explicit click; +# - start: refuses unless the doctor says ready:true AND names a loopback +# `socks` endpoint ("127.0.0.1:PORT", the contract a future c0mpute SOCKS +# client fills in) that actually accepts connections. +# The helper never starts a Scallion client itself and never claims anonymity. +# Routing (chrome.proxy) happens in the extension, the same path Tor uses. +# See docs/scallion.md. +SCALLION_INSTALL_URL = os.environ.get("TRON_SCALLION_INSTALL_URL", "https://c0mpute.com/install.sh") +# --minimal skips coinpay/infernet/transcode/tui/threatcrush; --no-start keeps +# the installer from enabling and starting the c0mpute worker service (it is on +# by default even with --minimal); --no-exec stops it from exec'ing a shell. +SCALLION_INSTALL_ARGS = ["--minimal", "--no-start", "--no-exec"] +SCALLION_INSTALL_WAIT = 240 # seconds POST /scallion/install waits before answering "still running" +SCALLION_DOCTOR_TIMEOUT = 30 +_scallion_lock = threading.Lock() +_scallion_routing = None # (host, port) the extension was cleared to route through, or None +_scallion_install = {"running": False, "exitCode": None, "tail": [], "error": None} +_scallion_install_lock = threading.Lock() +_scallion_install_done = threading.Event() +_scallion_install_done.set() +_ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]") + + +def c0mpute_candidates(): + """Where the c0mpute CLI may live: TRON_C0MPUTE_BIN, PATH, then the + installer's own locations ($C0MPUTE_HOME/bin, default ~/.c0mpute/bin) and + ~/.local/bin. The launcher's PATH often lacks ~/.c0mpute/bin, hence the list.""" + override = os.environ.get("TRON_C0MPUTE_BIN", "") + if override: + return [override] + home = os.environ.get("C0MPUTE_HOME") or os.path.expanduser("~/.c0mpute") + cands = [shutil.which("c0mpute"), + os.path.expanduser("~/.local/bin/c0mpute"), + os.path.join(home, "bin", "c0mpute"), + os.path.expanduser("~/.c0mpute/bin/c0mpute")] + out = [] + for cand in cands: + if cand and cand not in out: + out.append(cand) + return out + + +def c0mpute_binary(): + for cand in c0mpute_candidates(): + if os.path.isfile(cand) and os.access(cand, os.X_OK): + return cand + return None + + +def _c0mpute_env(): + env = os.environ.copy() + env["C0MPUTE_NO_AUTO_UPDATE"] = "1" # a status probe must never upgrade the CLI + env.setdefault("NO_COLOR", "1") + return env + + +def c0mpute_version(binary): + try: + out = subprocess.run([binary, "--version"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, timeout=15, env=_c0mpute_env()).stdout + except (OSError, subprocess.TimeoutExpired): + return None + m = re.search(r"(\d+\.\d+\.\d+[0-9A-Za-z.+-]*)", out or "") + return m.group(1) if m else None + + +def parse_doctor_output(text): + """The doctor's JSON object from its output, or None. It exits non-zero when + not ready and may print a log line first, so take the outermost {...}.""" + if not text: + return None + start, end = text.find("{"), text.rfind("}") + if start < 0 or end <= start: + return None + try: + data = json.loads(text[start:end + 1]) + except ValueError: + return None + return data if isinstance(data, dict) else None + + +def scallion_doctor(binary): + """(doctor dict or None, error or None).""" + try: + res = subprocess.run([binary, "scallion", "doctor", "--mode", "native", "--json"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=SCALLION_DOCTOR_TIMEOUT, env=_c0mpute_env()) + except subprocess.TimeoutExpired: + return None, "doctor-timeout" + except OSError as exc: + return None, "doctor-failed: %s" % exc + doc = parse_doctor_output(res.stdout) or parse_doctor_output(res.stderr) + if doc is None: + # Older CLIs have no `scallion` subcommand at all. + tail = _ANSI.sub("", (res.stderr or res.stdout or "").strip())[-300:] + return None, "doctor-unavailable: %s" % (tail or "exit %d" % res.returncode) + return doc, None + + +def parse_loopback_socks(value): + """(host, port) for a loopback SOCKS endpoint "127.0.0.1:PORT" (also + localhost / [::1]), else None. A doctor that names any other host is not + trusted: routing a browser to a remote proxy is not this setting's job.""" + if not isinstance(value, str): + return None + m = re.fullmatch(r"(127\.0\.0\.1|localhost|\[::1\]):(\d{1,5})", value.strip()) + if not m: + return None + port = int(m.group(2)) + if not 0 < port < 65536: + return None + return m.group(1), port + + +def _socks_accepts(host, port): + try: + with socket.create_connection((host.strip("[]"), port), timeout=1.5): + return True + except OSError: + return False + + +def scallion_status(): + binary = c0mpute_binary() + with _scallion_install_lock: + install = {"running": _scallion_install["running"], "exitCode": _scallion_install["exitCode"], + "tail": list(_scallion_install["tail"]), "error": _scallion_install["error"]} + with _scallion_lock: + routing = _scallion_routing + st = {"installed": binary is not None, "path": binary, "version": None, "doctor": None, + "ready": False, "socks": None, "routing": routing is not None, "error": None, + "install": install, "helper": HELPER_VERSION} + if not binary: + return st + st["version"] = c0mpute_version(binary) + doc, err = scallion_doctor(binary) + st["doctor"], st["error"] = doc, err + if doc is not None: + socks = parse_loopback_socks(doc.get("socks")) + st["socks"] = "%s:%d" % socks if socks else None + st["ready"] = doc.get("ready") is True and socks is not None + return st + + +def scallion_blockers(doc): + blockers = doc.get("blockers") if isinstance(doc, dict) else None + return [b for b in blockers if isinstance(b, str)] if isinstance(blockers, list) else [] + + +def start_scallion(): + """Clear the extension to route through Scallion, or refuse with the reason. + Returns (ok, status dict).""" + global _scallion_routing + st = scallion_status() + doc = st["doctor"] + reason = None + if not st["installed"]: + reason = "not-installed" + elif doc is None: + reason = st["error"] or "doctor-failed" + elif doc.get("ready") is not True: + reason = "not-ready" + elif not st["socks"]: + reason = "no-socks" # ready, but no local SOCKS client advertised + else: + host, port = parse_loopback_socks(st["socks"]) + if not _socks_accepts(host, port): + reason = "socks-unreachable" + if reason: + with _scallion_lock: + _scallion_routing = None + st.update(started=False, routing=False, error=reason, blockers=scallion_blockers(doc)) + log("scallion: start refused (%s)" % reason) + return False, st + host, port = parse_loopback_socks(st["socks"]) + with _scallion_lock: + _scallion_routing = (host, port) + st.update(started=True, routing=True, host=host.strip("[]"), port=port) + log("scallion: cleared to route through SOCKS %s" % st["socks"]) + return True, st + + +def stop_scallion(): + global _scallion_routing + with _scallion_lock: + was, _scallion_routing = _scallion_routing, None + if was: + log("scallion: routing stopped") + + +def _scallion_install_line(line): + line = _ANSI.sub("", line.rstrip("\n")).rstrip() + if not line: + return + with _scallion_install_lock: + tail = _scallion_install["tail"] + tail.append(line[-400:]) + del tail[:-40] + + +def _run_scallion_install(): + """Background: fetch the c0mpute installer and run it CLI-only. Downloaded + to a file first (not piped) so a failed download is a failed install rather + than `sh` running half a script.""" + code, error = None, None + workdir = None + try: + if not shutil.which("curl"): + raise RuntimeError("curl-missing") + base = os.path.expanduser("~/.tronbrowser") + os.makedirs(base, mode=0o700, exist_ok=True) + workdir = tempfile.mkdtemp(prefix="scallion-install-", dir=base) + script = os.path.join(workdir, "install.sh") + dl = subprocess.run(["curl", "-fsSL", "--max-time", "60", "-o", script, SCALLION_INSTALL_URL], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=90) + if dl.returncode != 0: + for line in (dl.stdout or "").splitlines(): + _scallion_install_line(line) + raise RuntimeError("download-failed") + env = _c0mpute_env() + env["NO_EXEC"] = "1" + _scallion_install_line("$ curl -fsSL %s | sh -s -- %s" % (SCALLION_INSTALL_URL, " ".join(SCALLION_INSTALL_ARGS))) + # No stdin and a new session: the installer finds no terminal, so it asks + # nothing and any sudo it tries fails fast instead of waiting on a prompt. + proc = subprocess.Popen(["sh", script] + SCALLION_INSTALL_ARGS, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + env=env, cwd=workdir, start_new_session=True) + with proc.stdout: + for line in proc.stdout: + _scallion_install_line(line) + code = proc.wait() + if code != 0: + error = "install-failed" + except (OSError, RuntimeError, subprocess.TimeoutExpired) as exc: + error = str(exc) if isinstance(exc, RuntimeError) else "install-failed: %s" % exc + finally: + if workdir: + shutil.rmtree(workdir, ignore_errors=True) + with _scallion_install_lock: + _scallion_install.update(running=False, exitCode=code, error=error) + _scallion_install_done.set() + log("scallion: c0mpute install finished (exit %s%s)" % (code, ", " + error if error else "")) + + +def install_scallion(wait=SCALLION_INSTALL_WAIT): + """Start the install (once at a time) and wait up to `wait` seconds. + Returns the status dict with its `install` block.""" + if platform.system() == "Windows": + st = scallion_status() + st["install"] = {"running": False, "exitCode": None, "tail": [], "error": "unsupported-platform"} + return st + with _scallion_install_lock: + if not _scallion_install["running"]: + _scallion_install.update(running=True, exitCode=None, tail=[], error=None) + _scallion_install_done.clear() + threading.Thread(target=_run_scallion_install, daemon=True, name="scallion-install").start() + log("scallion: installing the c0mpute CLI from %s" % SCALLION_INSTALL_URL) + _scallion_install_done.wait(timeout=wait) + return scallion_status() + + class Handler(BaseHTTPRequestHandler): def _send(self, code, obj): body = json.dumps(obj).encode("utf-8") @@ -804,7 +1077,7 @@ class Handler(BaseHTTPRequestHandler): self._send(403, {"error": "invalid-origin"}) return path = self.path.split("?", 1)[0].rstrip("/") or "/" - if path not in ("/", "/status", "/pit/status") and self.command != "POST": + if path not in ("/", "/status", "/pit/status", "/scallion/status") and self.command != "POST": self._send(405, {"error": "post-required"}) return if path == "/start": @@ -835,6 +1108,18 @@ class Handler(BaseHTTPRequestHandler): self._send(200, {"stopped": True}) elif path == "/pit/status": self._send(200, pit_status()) + elif path == "/scallion/status": + self._send(200, scallion_status()) + elif path == "/scallion/install": + st = install_scallion() + failed = st["install"]["error"] and not st["installed"] + self._send(500 if failed else 200, st) + elif path == "/scallion/start": + ok, st = start_scallion() + self._send(200 if ok else 409, st) + elif path == "/scallion/stop": + stop_scallion() + self._send(200, {"stopped": True, "routing": False}) else: log("no such route: %s (helper v%s)" % (path, HELPER_VERSION)) self._send(404, {"error": "not-found"}) diff --git a/apps/desktop/launcher/tronbrowser b/apps/desktop/launcher/tronbrowser index 12711bf..bf8c212 100755 --- a/apps/desktop/launcher/tronbrowser +++ b/apps/desktop/launcher/tronbrowser @@ -260,13 +260,13 @@ if [ "$TOR" != "1" ]; then elif [ -x "$DIR/tor-bin/tor" ]; then _torbin="$DIR/tor-bin/tor (auto-installed)"; elif command -v tor >/dev/null 2>&1; then _torbin="$(command -v tor)"; else _torbin="NOT FOUND — run 'tron tor' to install it"; fi - echo "TronBrowser: Tor + Pit toggles ready — helper control on 127.0.0.1:9061, Tor SOCKS on 127.0.0.1:$TOR_SOCKS_PORT (tor: $_torbin), Moshpit resolver on 127.0.0.1:9081. Click 🧅 Tor or 🤘 Pit in the AI sidebar. Log: $DATA/tor-helper.log" >&2 + echo "TronBrowser: Tor, Pit + Scallion toggles ready. Helper control on 127.0.0.1:9061, Tor SOCKS on 127.0.0.1:$TOR_SOCKS_PORT (tor: $_torbin), Moshpit resolver on 127.0.0.1:9081. Click 🧅 Tor or 🤘 Pit in the AI sidebar. Log: $DATA/tor-helper.log" >&2 # The helper persists across launches, so an OLD one (from before an upgrade) # would keep answering the toggle with stale code. Replace it ONLY when the # running helper isn't this version — otherwise leave a healthy current # helper alone (don't drop an active Tor session). All backgrounded so the # kill+settle never holds up the browser launch. - HELPER_VERSION=3.4.4 + HELPER_VERSION=3.5.0 ( _pf="$DATA/tor-helper.pid" _rv="$(curl -fsS --max-time 1 http://127.0.0.1:9061/status 2>/dev/null | sed -n 's/.*"version"[^"]*"\([^"]*\)".*/\1/p')" diff --git a/apps/desktop/test/test_scallion_helper.py b/apps/desktop/test/test_scallion_helper.py new file mode 100644 index 0000000..9e09c46 --- /dev/null +++ b/apps/desktop/test/test_scallion_helper.py @@ -0,0 +1,210 @@ +"""Scallion endpoints of tron-tor-helper. Stdlib only, no network: the c0mpute +CLI and its installer are small fake shell scripts.""" +import http.client +import json +import os +from pathlib import Path +import runpy +import socket +import stat +import tempfile +import textwrap +import threading +import unittest +from unittest import mock + +LAUNCHER = Path(__file__).resolve().parents[1] / "launcher" + +NOT_READY = { + "mode": "native", "ready": False, "production_ready": False, + "blockers": ["native TUN client transport is not implemented", + "independent security review is outstanding"], + "built_experimental": ["signed relay descriptors"], +} + + +def helper(): + return runpy.run_path(str(LAUNCHER / "tron-tor-helper")) + + +def write_exec(path, body): + path.write_text(body) + path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + +def fake_c0mpute(directory, doctor, exit_code=2): + """A c0mpute CLI that prints a version, a log line, then the doctor JSON.""" + doc = directory / "doctor.json" + doc.write_text(json.dumps(doctor)) + binary = directory / "c0mpute" + write_exec(binary, textwrap.dedent("""\ + #!/bin/sh + if [ "$1" = "--version" ]; then echo "c0mpute 0.3.130"; exit 0; fi + if [ "$1 $2" = "scallion doctor" ]; then + echo "2026-11-30T00:00:00Z INFO c0mpute_core: tracing initialised" >&2 + cat "%s"; exit %d + fi + exit 64 + """ % (doc, exit_code))) + return binary + + +@unittest.skipIf(os.name == "nt", "the fake c0mpute CLI is a POSIX shell script") +class ScallionHelperTests(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, ignore_errors=True)) + self.h = helper() + + def env(self, **values): + patch = mock.patch.dict(os.environ, values) + patch.start() + self.addCleanup(patch.stop) + + def test_parses_doctor_json_after_a_log_line(self): + parsed = self.h["parse_doctor_output"]("INFO tracing initialised\n" + json.dumps(NOT_READY)) + self.assertEqual(parsed["ready"], False) + self.assertIsNone(self.h["parse_doctor_output"]("no json here")) + self.assertIsNone(self.h["parse_doctor_output"]("")) + + def test_socks_must_be_loopback(self): + parse = self.h["parse_loopback_socks"] + self.assertEqual(parse("127.0.0.1:9095"), ("127.0.0.1", 9095)) + self.assertEqual(parse("localhost:1080"), ("localhost", 1080)) + self.assertEqual(parse("[::1]:1080"), ("[::1]", 1080)) + for bad in ("10.0.0.1:9050", "example.com:1080", "127.0.0.1", "127.0.0.1:0", + "127.0.0.1:70000", "socks5://127.0.0.1:1080", None, 9050): + with self.subTest(bad=bad): + self.assertIsNone(parse(bad)) + + def test_not_installed(self): + self.env(TRON_C0MPUTE_BIN=str(self.tmp / "missing")) + st = self.h["scallion_status"]() + self.assertFalse(st["installed"]) + self.assertFalse(st["ready"]) + self.assertFalse(st["routing"]) + ok, st = self.h["start_scallion"]() + self.assertFalse(ok) + self.assertEqual(st["error"], "not-installed") + + def test_today_the_doctor_says_not_ready_and_start_refuses(self): + self.env(TRON_C0MPUTE_BIN=str(fake_c0mpute(self.tmp, NOT_READY))) + st = self.h["scallion_status"]() + self.assertTrue(st["installed"]) + self.assertEqual(st["version"], "0.3.130") + self.assertEqual(st["doctor"]["blockers"], NOT_READY["blockers"]) + self.assertFalse(st["ready"]) + self.assertIsNone(st["socks"]) + ok, st = self.h["start_scallion"]() + self.assertFalse(ok) + self.assertEqual(st["error"], "not-ready") + self.assertEqual(st["blockers"], NOT_READY["blockers"]) + self.assertFalse(st["routing"]) + + def test_ready_without_a_socks_field_still_refuses(self): + for socks in (None, "10.0.0.1:9050"): + with self.subTest(socks=socks): + doctor = {**NOT_READY, "ready": True, "blockers": []} + if socks: + doctor["socks"] = socks + self.env(TRON_C0MPUTE_BIN=str(fake_c0mpute(self.tmp, doctor, exit_code=0))) + ok, st = self.h["start_scallion"]() + self.assertFalse(ok) + self.assertEqual(st["error"], "no-socks") + + def test_ready_with_a_dead_socks_port_refuses(self): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + doctor = {**NOT_READY, "ready": True, "blockers": [], "socks": "127.0.0.1:%d" % port} + self.env(TRON_C0MPUTE_BIN=str(fake_c0mpute(self.tmp, doctor, exit_code=0))) + ok, st = self.h["start_scallion"]() + self.assertFalse(ok) + self.assertEqual(st["error"], "socks-unreachable") + + def test_ready_with_a_live_socks_port_routes_and_stop_clears(self): + listener = socket.socket() + listener.bind(("127.0.0.1", 0)) + listener.listen(4) + self.addCleanup(listener.close) + port = listener.getsockname()[1] + doctor = {**NOT_READY, "ready": True, "blockers": [], "socks": "127.0.0.1:%d" % port} + self.env(TRON_C0MPUTE_BIN=str(fake_c0mpute(self.tmp, doctor, exit_code=0))) + ok, st = self.h["start_scallion"]() + self.assertTrue(ok) + self.assertEqual((st["host"], st["port"]), ("127.0.0.1", port)) + self.assertTrue(self.h["scallion_status"]()["routing"]) + self.h["stop_scallion"]() + self.assertFalse(self.h["scallion_status"]()["routing"]) + + def test_install_runs_the_cli_only_installer_without_a_terminal(self): + record = self.tmp / "args.txt" + target = self.tmp / "home-bin" / "c0mpute" + installer = self.tmp / "install.sh" + installer.write_text(textwrap.dedent("""\ + echo "$*" > "%s" + if [ -t 0 ]; then echo tty >> "%s"; fi + mkdir -p "%s" + printf '#!/bin/sh\\necho "c0mpute 0.3.131"\\n' > "%s" + chmod +x "%s" + printf '\\033[32mok\\033[0m installed c0mpute\\n' + """ % (record, record, target.parent, target, target))) + self.env(TRON_C0MPUTE_BIN=str(target)) + self.h["install_scallion"].__globals__["SCALLION_INSTALL_URL"] = installer.as_uri() + st = self.h["install_scallion"](wait=30) + self.assertEqual(record.read_text().split("\n")[0], "--minimal --no-start --no-exec") + self.assertNotIn("tty", record.read_text()) + self.assertFalse(st["install"]["running"]) + self.assertEqual(st["install"]["exitCode"], 0) + self.assertIn("ok installed c0mpute", st["install"]["tail"]) + self.assertTrue(st["installed"]) + self.assertEqual(st["version"], "0.3.131") + + def test_install_reports_a_failed_download(self): + self.env(TRON_C0MPUTE_BIN=str(self.tmp / "missing")) + self.h["install_scallion"].__globals__["SCALLION_INSTALL_URL"] = (self.tmp / "nope.sh").as_uri() + st = self.h["install_scallion"](wait=30) + self.assertFalse(st["installed"]) + self.assertEqual(st["install"]["error"], "download-failed") + + +@unittest.skipIf(os.name == "nt", "the fake c0mpute CLI is a POSIX shell script") +class ScallionRouteTests(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, ignore_errors=True)) + patch = mock.patch.dict(os.environ, {"TRON_C0MPUTE_BIN": str(fake_c0mpute(self.tmp, NOT_READY))}) + patch.start() + self.addCleanup(patch.stop) + h = helper() + self.server = h["HelperServer"](("127.0.0.1", 0), h["Handler"]) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + + def request(self, method, path, headers=None): + conn = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=30) + conn.request(method, path, headers=headers or {}) + res = conn.getresponse() + body = json.loads(res.read() or b"{}") + conn.close() + return res.status, body + + def test_status_is_a_get_and_mutations_need_post(self): + status, body = self.request("GET", "/scallion/status") + self.assertEqual(status, 200) + self.assertEqual(body["doctor"]["ready"], False) + self.assertEqual(self.request("GET", "/scallion/start")[0], 405) + self.assertEqual(self.request("GET", "/scallion/install")[0], 405) + status, body = self.request("POST", "/scallion/start") + self.assertEqual(status, 409) + self.assertEqual(body["error"], "not-ready") + self.assertEqual(self.request("POST", "/scallion/stop"), (200, {"stopped": True, "routing": False})) + + def test_web_origins_are_refused(self): + status, _ = self.request("POST", "/scallion/install", {"Origin": "https://evil.example"}) + self.assertEqual(status, 403) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/desktop/test/test_windows_pit.py b/apps/desktop/test/test_windows_pit.py index 61d4b2e..53e076b 100644 --- a/apps/desktop/test/test_windows_pit.py +++ b/apps/desktop/test/test_windows_pit.py @@ -37,7 +37,7 @@ def unused_port(): def state(**overrides): - return dict(helper="tronbrowser-network", version="3.4.4", running=False, + return dict(helper="tronbrowser-network", version="3.5.0", running=False, port=9081, pid=123, **overrides) diff --git a/docker/tron-headless/Dockerfile b/docker/tron-headless/Dockerfile new file mode 100644 index 0000000..06bf2df --- /dev/null +++ b/docker/tron-headless/Dockerfile @@ -0,0 +1,64 @@ +# tron-headless: TronBrowser's engine (portable ungoogled-chromium) running +# headless with the Chrome DevTools Protocol on port 9222, for c0mpute browser +# nodes ("distributed browsing"). Published as ghcr.io/profullstack/tron-headless +# by .github/workflows/tron-headless.yml. Contract: docker/tron-headless/README.md. +# +# Build from the repo root: +# docker build -f docker/tron-headless/Dockerfile -t tron-headless docker/tron-headless + +# Same engine version as the root Dockerfile (the MCP relay) and the launcher's +# bundled engine. Bump both together, with the new sha256. +ARG UNGOOGLED_CHROMIUM_VERSION=152.0.7977.82-1 +ARG UNGOOGLED_CHROMIUM_SHA256=2c6e464e030f87145e42553c5aa539f6e62163ce677d3eace3c51b4fcbd5e347 + +# debian:bookworm-slim, pinned by its multi-arch index digest. +FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e AS engine +ARG UNGOOGLED_CHROMIUM_VERSION +ARG UNGOOGLED_CHROMIUM_SHA256 +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl xz-utils \ + && rm -rf /var/lib/apt/lists/* +RUN set -eu; \ + url="https://github.com/ungoogled-software/ungoogled-chromium-portablelinux/releases/download/${UNGOOGLED_CHROMIUM_VERSION}/ungoogled-chromium-${UNGOOGLED_CHROMIUM_VERSION}-x86_64_linux.tar.xz"; \ + curl -fsSL -o /tmp/uc.tar.xz "$url"; \ + echo "${UNGOOGLED_CHROMIUM_SHA256} /tmp/uc.tar.xz" | sha256sum -c -; \ + mkdir -p /opt/ungoogled-chromium; \ + tar -xJf /tmp/uc.tar.xz --strip-components=1 -C /opt/ungoogled-chromium; \ + rm /tmp/uc.tar.xz; \ + test -x /opt/ungoogled-chromium/chrome + +FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e +ARG UNGOOGLED_CHROMIUM_VERSION +LABEL org.opencontainers.image.source="https://github.com/profullstack/tronbrowser.dev" \ + org.opencontainers.image.title="tron-headless" \ + org.opencontainers.image.description="TronBrowser engine (ungoogled-chromium) headless, CDP on :9222, for c0mpute browser nodes" \ + org.opencontainers.image.licenses="MIT" \ + dev.tronbrowser.engine="ungoogled-chromium ${UNGOOGLED_CHROMIUM_VERSION}" + +# The lib* rows are what the portable Chromium links against (same list as the +# root Dockerfile). Fonts: Latin, emoji and CJK so pages render. socat exposes +# CDP; tini reaps and forwards signals. +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates socat tini \ + libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 \ + libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2 libpango-1.0-0 \ + libcairo2 libatspi2.0-0 libxshmfence1 libx11-6 libx11-xcb1 libxcb1 libxext6 libglib2.0-0 \ + libdbus-1-3 libexpat1 \ + fonts-liberation fonts-dejavu-core fonts-noto-color-emoji fonts-noto-cjk \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=engine /opt/ungoogled-chromium /opt/ungoogled-chromium +COPY entrypoint.sh /usr/local/bin/tron-headless +RUN chmod 0755 /usr/local/bin/tron-headless \ + && groupadd --gid 1000 tron \ + && useradd --uid 1000 --gid 1000 --create-home --home-dir /home/tron --shell /bin/bash tron + +USER 1000:1000 +ENV HOME=/home/tron \ + TRON_CHROME=/opt/ungoogled-chromium/chrome +WORKDIR /home/tron +EXPOSE 9222 + +# tini -g: signals go to the whole process group (Chromium, socat, the CMD). +ENTRYPOINT ["/usr/bin/tini", "-g", "--", "/usr/local/bin/tron-headless"] +CMD ["sleep", "infinity"] diff --git a/docker/tron-headless/README.md b/docker/tron-headless/README.md new file mode 100644 index 0000000..55de80d --- /dev/null +++ b/docker/tron-headless/README.md @@ -0,0 +1,83 @@ +# tron-headless + +TronBrowser's engine (portable ungoogled-chromium, the same pinned build the +launcher bundles and the MCP relay runs) headless in a container, with the +Chrome DevTools Protocol published on port 9222. c0mpute browser nodes run it +for distributed browsing. + +``` +docker run --rm --cap-drop ALL --security-opt no-new-privileges \ + --shm-size 1g --memory 2g -p 127.0.0.1:9222:9222 \ + ghcr.io/profullstack/tron-headless:latest +curl -s http://127.0.0.1:9222/json/version +``` + +Image: `ghcr.io/profullstack/tron-headless`, tags `vX.Y.Z` (each TronBrowser +release) and `latest`, `linux/amd64`. Built and pushed by +`.github/workflows/tron-headless.yml` on `v*` tags (and by hand via +workflow_dispatch); every PR that touches this directory builds it and runs the +smoke test below. + +## Contract + +| | | +| --- | --- | +| Base | `debian:bookworm-slim`, pinned by digest | +| Engine | ungoogled-chromium portable Linux `152.0.7977.82-1` at `/opt/ungoogled-chromium/chrome`, tarball sha256-verified at build | +| Fonts | Liberation, DejaVu, Noto Color Emoji, Noto CJK | +| User | `1000:1000` (`tron`), `HOME=/home/tron` (writable), profile at `$HOME/profile` | +| Entrypoint | `tini -g -- /usr/local/bin/tron-headless` | +| CMD | `sleep infinity` (replace it with your own; see Lifecycle) | +| Port | `9222`: CDP, socat to Chromium's `127.0.0.1:9223` | + +Chromium is started with: + +``` +--headless=new --remote-debugging-address=127.0.0.1 --remote-debugging-port=9223 +--user-data-dir=$HOME/profile --window-size=${TRON_WINDOW:-1280,800} +--no-first-run --no-default-browser-check --disable-background-networking +--disable-sync --disable-component-update --disable-gpu --mute-audio --no-sandbox +[--proxy-server=$TRON_PROXY] (only when TRON_PROXY is set) +about:blank (so one page target exists) +``` + +`--no-sandbox` is deliberate: the container runs as uid 1000 with +`--cap-drop ALL` and `no-new-privileges`, so Chromium cannot set up the user +namespaces its own sandbox needs. The container is the sandbox. + +### Env + +| Var | Default | Effect | +| --- | --- | --- | +| `TRON_WINDOW` | `1280,800` | `--window-size` (new headless reserves some of it for browser UI; set the page size with `Emulation.setDeviceMetricsOverride` if you need exact pixels) | +| `TRON_PROXY` | unset | `--proxy-server` value, e.g. `socks5://10.0.0.2:1080` | + +### Lifecycle + +The entrypoint starts Chromium, waits for its DevTools port, starts socat, then +runs the CMD in the foreground. **Whichever of Chromium, socat or the CMD exits +first ends the container**, with that process's exit status; the others get +SIGTERM, then SIGKILL after 5 s. `docker stop` exits 143. So a node can bound a +session with a CMD that loops until an expiry file passes. + +### Connecting + +`GET http:///json/version` returns +`webSocketDebuggerUrl` built from the request's `Host` header, so it points at +the published address. Chromium refuses DevTools requests whose `Host` is not +an IP address or `localhost`, so connect by IP (as the published port does), +not by a container DNS name. Then over that WebSocket: `Target.getTargets`, +`Target.attachToTarget {flatten: true}`, and `Page.*` on the session. + +## Smoke test + +``` +docker build -t tron-headless docker/tron-headless +docker run -d --name th --cap-drop ALL --security-opt no-new-privileges \ + --shm-size 1g --memory 2g -p 127.0.0.1:9222:9222 tron-headless +node docker/tron-headless/smoke.mjs http://127.0.0.1:9222 shot.png # Node 22+ +``` + +It polls `/json/version`, attaches to the page, navigates to a `data:` URL, +reads `document.title`, takes a screencast frame and a PNG screenshot, and exits +non-zero if any step is missing. diff --git a/docker/tron-headless/entrypoint.sh b/docker/tron-headless/entrypoint.sh new file mode 100644 index 0000000..2024355 --- /dev/null +++ b/docker/tron-headless/entrypoint.sh @@ -0,0 +1,92 @@ +#!/bin/bash +# tron-headless entrypoint: headless Chromium with CDP on 127.0.0.1:9223, +# socat publishing it on 0.0.0.0:9222, then the container CMD in the +# foreground. Whichever of the three exits first ends the container (the +# c0mpute node's CMD loops until an expiry file passes). +# +# Env: +# TRON_WINDOW window size, default 1280,800 +# TRON_PROXY passed to --proxy-server when set (e.g. socks5://10.0.0.2:1080) +set -euo pipefail + +: "${HOME:=/home/tron}" +CHROME="${TRON_CHROME:-/opt/ungoogled-chromium/chrome}" +PROFILE="$HOME/profile" +mkdir -p "$PROFILE" + +flags=( + --headless=new + --remote-debugging-address=127.0.0.1 + --remote-debugging-port=9223 + --user-data-dir="$PROFILE" + --window-size="${TRON_WINDOW:-1280,800}" + --no-first-run + --no-default-browser-check + --disable-background-networking + --disable-sync + --disable-component-update + --disable-gpu + --mute-audio + # The container is the sandbox: it runs as uid 1000 with --cap-drop ALL and + # no-new-privileges, so Chromium cannot create the user namespaces its own + # sandbox needs. Isolation comes from the container boundary instead. + --no-sandbox +) +if [ -n "${TRON_PROXY:-}" ]; then + flags+=(--proxy-server="$TRON_PROXY") +fi + +pids=() +cleanup() { + trap - TERM INT EXIT + for p in "${pids[@]}"; do kill "$p" 2>/dev/null || true; done + # Give them 5 s to go, then SIGKILL whatever is left. + for _ in $(seq 1 50); do + alive=0 + for p in "${pids[@]}"; do kill -0 "$p" 2>/dev/null && alive=1; done + [ "$alive" -eq 0 ] && break + sleep 0.1 + done + for p in "${pids[@]}"; do kill -KILL "$p" 2>/dev/null || true; done + wait 2>/dev/null || true +} +trap 'cleanup; exit 143' TERM +trap 'cleanup; exit 130' INT +trap cleanup EXIT + +# One page target (about:blank) exists from the start. +"$CHROME" "${flags[@]}" about:blank & +chrome_pid=$! +pids+=("$chrome_pid") + +# Wait for the DevTools port before publishing it (up to 30 s). +for _ in $(seq 1 300); do + if (exec 3<>/dev/tcp/127.0.0.1/9223) 2>/dev/null; then break; fi + if ! kill -0 "$chrome_pid" 2>/dev/null; then + wait "$chrome_pid" || status=$? + echo "tron-headless: chromium exited before DevTools came up (status ${status:-0})" >&2 + exit "${status:-1}" + fi + sleep 0.1 +done + +socat TCP-LISTEN:9222,bind=0.0.0.0,fork,reuseaddr TCP:127.0.0.1:9223 & +socat_pid=$! +pids+=("$socat_pid") +echo "tron-headless: CDP on 0.0.0.0:9222 (chromium pid $chrome_pid)" >&2 + +if [ "$#" -eq 0 ]; then set -- sleep infinity; fi +"$@" & +cmd_pid=$! +pids+=("$cmd_pid") + +status=0 +wait -n "$chrome_pid" "$socat_pid" "$cmd_pid" || status=$? +if ! kill -0 "$chrome_pid" 2>/dev/null; then + echo "tron-headless: chromium exited (status $status)" >&2 +elif ! kill -0 "$cmd_pid" 2>/dev/null; then + echo "tron-headless: command exited (status $status)" >&2 +else + echo "tron-headless: socat exited (status $status)" >&2 +fi +exit "$status" diff --git a/docker/tron-headless/smoke.mjs b/docker/tron-headless/smoke.mjs new file mode 100644 index 0000000..afb7c0c --- /dev/null +++ b/docker/tron-headless/smoke.mjs @@ -0,0 +1,104 @@ +// Smoke test for a running tron-headless container, from OUTSIDE it, the way a +// c0mpute node uses it: /json/version → browser ws URL → attach to the page +// (flatten) → navigate → screencast frame → screenshot. Node 22+ (global WebSocket). +// +// node docker/tron-headless/smoke.mjs [http://127.0.0.1:9222] [out.png] +import { writeFileSync } from 'node:fs'; + +const base = process.argv[2] || 'http://127.0.0.1:9222'; +const out = process.argv[3] || ''; +const fail = (msg) => { console.error(`smoke: FAIL: ${msg}`); process.exit(1); }; +const deadline = (ms, what) => new Promise((_, rej) => setTimeout(() => rej(new Error(`timeout: ${what}`)), ms)); + +async function version() { + const until = Date.now() + 60_000; + let last; + while (Date.now() < until) { + try { + const res = await fetch(`${base}/json/version`); + if (res.ok) return await res.json(); + last = `HTTP ${res.status}`; + } catch (e) { + last = e.message; + } + await new Promise((r) => setTimeout(r, 500)); + } + fail(`/json/version never answered (${last})`); +} + +const info = await version(); +console.log(`smoke: ${info.Browser} ${info['Protocol-Version']}`); +if (!(info.webSocketDebuggerUrl || '').startsWith(`ws://${new URL(base).host}/devtools/browser/`)) { + fail(`unexpected webSocketDebuggerUrl ${info.webSocketDebuggerUrl}`); +} + +const ws = new WebSocket(info.webSocketDebuggerUrl); +await Promise.race([ + new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error('ws error')); }), + deadline(10_000, 'ws open'), +]); + +let nextId = 0; +const pending = new Map(); +const waiters = []; +ws.onmessage = (ev) => { + const msg = JSON.parse(ev.data); + if (msg.id && pending.has(msg.id)) { + const { res, rej } = pending.get(msg.id); + pending.delete(msg.id); + msg.error ? rej(new Error(`${msg.error.message} (${msg.error.code})`)) : res(msg.result); + return; + } + for (const w of waiters.slice()) { + if (w.method === msg.method && (!w.sessionId || w.sessionId === msg.sessionId)) { + waiters.splice(waiters.indexOf(w), 1); + w.res(msg); + } + } +}; +const send = (method, params = {}, sessionId) => { + const id = ++nextId; + ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })); + return Promise.race([new Promise((res, rej) => pending.set(id, { res, rej })), deadline(30_000, method)]); +}; +const once = (method, sessionId) => Promise.race([ + new Promise((res) => waiters.push({ method, sessionId, res })), deadline(30_000, method), +]); + +const { targetInfos } = await send('Target.getTargets'); +const page = targetInfos.find((t) => t.type === 'page'); +if (!page) fail(`no page target (targets: ${targetInfos.map((t) => t.type).join(',')})`); +console.log(`smoke: page target ${page.targetId} ${page.url}`); + +const { sessionId } = await send('Target.attachToTarget', { targetId: page.targetId, flatten: true }); +await send('Page.enable', {}, sessionId); +const html = 'tron-headless smoke

tron-headless 🌱 日本語

'; +const loaded = once('Page.loadEventFired', sessionId); +await send('Page.navigate', { url: `data:text/html;charset=utf-8,${encodeURIComponent(html)}` }, sessionId); +await loaded; +const { result } = await send('Runtime.evaluate', { expression: 'document.title', returnByValue: true }, sessionId); +if (result.value !== 'tron-headless smoke') fail(`title is ${JSON.stringify(result.value)}`); +console.log('smoke: navigated'); + +const frame = once('Page.screencastFrame', sessionId); +await send('Page.startScreencast', { format: 'jpeg', quality: 60, maxWidth: 640, maxHeight: 400, everyNthFrame: 1 }, sessionId); +// A static page only paints once; nudge a repaint so a frame is produced. +await send('Runtime.evaluate', { expression: 'document.body.style.background = "#a6ff1a"' }, sessionId); +const f = await frame; +await send('Page.screencastFrameAck', { sessionId: f.params.sessionId }, sessionId); +await send('Page.stopScreencast', {}, sessionId); +if (!f.params.data || Buffer.from(f.params.data, 'base64').subarray(0, 2).toString('hex') !== 'ffd8') { + fail('screencast frame is not a JPEG'); +} +console.log(`smoke: screencast frame ${f.params.metadata.deviceWidth}x${f.params.metadata.deviceHeight}`); + +const shot = await send('Page.captureScreenshot', { format: 'png' }, sessionId); +const png = Buffer.from(shot.data, 'base64'); +if (png.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') fail('screenshot is not a PNG'); +if (png.length < 1000) fail(`screenshot suspiciously small (${png.length} bytes)`); +if (out) writeFileSync(out, png); +console.log(`smoke: screenshot ${png.length} bytes${out ? ` -> ${out}` : ''}`); + +ws.close(); +console.log('smoke: OK'); +process.exit(0); diff --git a/docs/scallion.md b/docs/scallion.md new file mode 100644 index 0000000..3c2d43a --- /dev/null +++ b/docs/scallion.md @@ -0,0 +1,131 @@ +# Scallion (c0mpute network) + +**Status:** setting shipped, routing fails closed (helper 3.5.0) +**Owner:** desktop (`apps/desktop`) +**Scope:** an honest switch for c0mpute's relay network. **Experimental, unreviewed, not anonymity.** + +--- + +## What it is + +Scallion is the onion-style relay network being built on +[c0mpute](https://c0mpute.com): signed relay descriptors, a three-hop telescoped +handshake, and a stream layer with an exit policy, carried over the c0mpute +libp2p network. It is not Tor and has none of Tor's review history. + +## What TronBrowser does with it today + +Nothing reaches the network. Today's c0mpute CLI says so itself: + +``` +$ c0mpute scallion doctor --mode native --json +{"mode":"native","ready":false,"blockers":[...],"built_experimental":[...],"production_ready":false} +``` + +and there is no local Scallion SOCKS client yet. So TronBrowser's Scallion +setting is **off by default** and **fails closed**: + +| State | What Settings and the sidebar say | Toggle | +| --- | --- | --- | +| c0mpute CLI not found | "Not installed", with an **Install** button | disabled | +| Installed, doctor not ready (today) | "Installed (c0mpute vX). Scallion client not ready: *blockers*. TronBrowser traffic is NOT going through Scallion." | disabled | +| Doctor ready but no `socks` field | "Scallion client not ready: the doctor reports ready but no local Scallion SOCKS client is running." | disabled | +| Doctor ready + loopback `socks` that accepts connections | "Scallion client ready". Off until switched on. | enabled | +| Switched on, verified | "On: routed through Scallion" | enabled | + +Where it lives: + +- **Settings** (the options page) has the full **Scallion (c0mpute network)** + section: state, the doctor's blockers, Install, the switch, and the installer + output tail. +- The **AI sidebar** has a **🌱 Scallion** button next to 🧅 Tor and 🤘 Pit. It is + greyed out while Scallion cannot route; clicking it shows the plain status and + a link to Settings. + +## Back end: the network helper + +The same loopback helper that runs Tor and the pit resolver +(`apps/desktop/launcher/tron-tor-helper`, `127.0.0.1:9061`) serves: + +| Route | Does | +| --- | --- | +| `GET /scallion/status` | `{installed, path, version, doctor, ready, socks, routing, error, install}` | +| `POST /scallion/install` | Installs the c0mpute **CLI only** (see below), waits up to 240 s, returns the status with `install: {running, exitCode, tail, error}` | +| `POST /scallion/start` | 200 `{started: true, routing: true, socks, host, port}` only when allowed; otherwise 409 `{started: false, error, blockers}` | +| `POST /scallion/stop` | `{stopped: true, routing: false}` | + +Same rules as the other routes: literal `127.0.0.1` Host, no web origins, POST +for anything that changes state. + +**Finding the CLI:** `TRON_C0MPUTE_BIN` if set, else `c0mpute` on `PATH`, then +`~/.local/bin/c0mpute`, `$C0MPUTE_HOME/bin/c0mpute` and `~/.c0mpute/bin/c0mpute` +(where the c0mpute installer puts it; the launcher's `PATH` often lacks it). +Every call sets `C0MPUTE_NO_AUTO_UPDATE=1`, so checking status never upgrades +the CLI. + +**Install** runs only on an explicit click: + +``` +curl -fsSL https://c0mpute.com/install.sh | sh -s -- --minimal --no-start --no-exec +``` + +`--minimal` skips CoinPay, Infernet, transcode, the TUI and ThreatCrush. +`--no-start` matters: without it the c0mpute installer enables and starts the +worker service even with `--minimal`. `--no-exec` stops it from exec'ing a new +shell. The helper downloads the script to a file first (a failed download is a +failed install, not half a script), runs it with no stdin and in a new session +(no terminal, so it asks nothing and any `sudo` fails fast), and keeps the last +40 lines of output. Not offered on Windows. + +**Start** (`POST /scallion/start`) is allowed only when **all** of these hold: + +1. the CLI is installed and `c0mpute scallion doctor --mode native --json` parses; +2. the doctor says `"ready": true`; +3. the doctor JSON carries `"socks": "127.0.0.1:PORT"` (also `localhost:PORT` or + `[::1]:PORT`; any non-loopback host is ignored, since pointing a browser at a + remote proxy is not this setting's job); +4. something accepts a TCP connection on that port. + +Otherwise it refuses with the reason (`not-installed`, `doctor-unavailable: …`, +`not-ready`, `no-socks`, `socks-unreachable`) and the doctor's `blockers`. The +helper never starts a Scallion client itself. + +## Routing in the extension + +When the helper clears it, the background routes exactly like the 🧅 Tor +toggle: `chrome.proxy` `fixed_servers` SOCKS5 to that endpoint (loopback +bypassed), plus the WebRTC guard (`disable_non_proxied_udp`). It then fetches +`https://my.ip.pit.world/?format=json` through the proxy; if that fails it puts +the proxy back to `system`, tells the helper to stop, and reports +`verify-failed`. It never leaves a dead proxy behind. + +**Exclusive with Tor and the pit**, the same way those two are with each other: + +- Tor on: refuses Scallion (`tor-on`); turning Tor on takes Scallion down first. +- Scallion on: turns the pit off first; turning the pit on refuses (`scallion-on`), + because the pit's PAC asks the system resolver about every host, which would + leak lookups outside the proxy. + +Like the other toggles it is off again on every fresh browser start; a service +worker restart mid-session re-applies the proxy only if the helper still has +routing cleared and the doctor still says ready. + +## The contract for the c0mpute side + +A future c0mpute Scallion client turns this on without a TronBrowser release by: + +1. running a local SOCKS5 server (CONNECT, domain names resolved by the client + inside Scallion) on a loopback port, and +2. making `c0mpute scallion doctor --mode native --json` print `"ready": true` + and `"socks": "127.0.0.1:PORT"` while it is up. + +Exit code and stray log lines do not matter: the helper parses the outermost +JSON object from stdout (then stderr). + +## What this is NOT + +- **Not anonymity.** Scallion has had no independent security review and no + multi-host, leak or adversarial testing. Never rely on it for safety. For + that, use [Tor Browser](https://www.torproject.org/). +- **Not a relay.** TronBrowser only ever acts as a client here; installing the + CLI with these flags starts no worker and carries nobody else's traffic.