mirror of https://github.com/garrytan/gstack.git
fix(browse): extension token bootstrap moves to pinned-origin POST; /health carries no token
GET /health is now liveness/status only in every mode — both token carve-outs (headed-mode disjunct AND chrome-extension:// Origin disjunct) are removed. Token bootstrap is POST /extension-token on the local listener: the Origin header must be exactly chrome-extension://<GSTACK_EXTENSION_ID> and the Host header's hostname must parse to 127.0.0.1 or localhost (parsed via new URL, never literal equality — Host arrives as '127.0.0.1:34567'). Wrong origin/host → 403 with no detail. The tunnel surface 404s the endpoint (not in TUNNEL_PATHS, verified by test). The extension ID is pinned by a new "key" field (RSA public key) in extension/manifest.json; browse/scripts/extension-id.ts reproduces the ID derivation (first 16 bytes of SHA-256 of the DER public key, hex mapped 0-9a-f → a-p). The private key is not committed anywhere — unpacked/baked-in loads only need the public key. Extension side: background.js bootstraps and refreshes the token via POST /extension-token (403 → disconnected state); sidepanel.js direct connect path does the same; sidepanel-terminal.js's dead /health token fallback (read AUTH_TOKEN/authToken keys the server never sent, hardcoded port) is replaced with the window.gstackAuthToken path. MIGRATION NOTE: the manifest key pins the extension ID, so existing installs' side-panel local state (saved port, snoozes) resets once — explained in-product via a one-time notice (flag gstack_id_migrated_v162). After upgrading the server, restart the browser so the old service worker stops polling for a token GET /health no longer serves. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> (cherry picked from commit e9a0b6847a2d17fe6656a4686b4efd0c8380eb09)
This commit is contained in:
parent
2ae38785a1
commit
a2751b7cf2
12
CLAUDE.md
12
CLAUDE.md
|
|
@ -282,10 +282,14 @@ PTY via `window.gstackInjectToTerminal(text)`, exposed by
|
|||
`sidepanel-terminal.js`. No `/sidebar-command` POST — the live REPL is
|
||||
the only execution surface in the sidebar now.
|
||||
|
||||
**`/health` MUST NOT surface any shell-grant token.** It already leaks
|
||||
`AUTH_TOKEN` to localhost callers in headed mode (a v1.1+ TODO). Don't
|
||||
make that worse by adding the PTY session token there. PTY auth flows
|
||||
through `POST /pty-session` only.
|
||||
**`/health` MUST NOT surface any token — and it no longer does** (v1.62+).
|
||||
The historical headed-mode leak of `AUTH_TOKEN` is fixed: `GET /health` is
|
||||
liveness/status only in every mode. Token bootstrap is `POST /extension-token`,
|
||||
which validates the caller's Origin against the pinned extension identity
|
||||
(the `key` field in `extension/manifest.json` pins the extension ID —
|
||||
`GSTACK_EXTENSION_ID` in `browse/src/server.ts`, derivation reproducible via
|
||||
`bun browse/scripts/extension-id.ts`) plus a loopback Host. PTY auth still
|
||||
flows through `POST /pty-session` only. Don't add any token to `/health`.
|
||||
|
||||
**Transport-layer security** (v1.6.0.0+). When `pair-agent` starts an ngrok tunnel,
|
||||
the daemon binds two HTTP listeners: a local listener (127.0.0.1, full command
|
||||
|
|
|
|||
|
|
@ -0,0 +1,45 @@
|
|||
#!/usr/bin/env bun
|
||||
/**
|
||||
* Derive the Chrome extension ID from the "key" field in
|
||||
* extension/manifest.json.
|
||||
*
|
||||
* Chrome computes an extension's ID as the first 16 bytes of the SHA-256
|
||||
* hash of the DER-encoded public key, with each hex nibble mapped from
|
||||
* 0-9a-f to a-p (the "mpdecimal" alphabet). Pinning the public key in the
|
||||
* manifest pins the ID, which lets the browse server verify the Origin
|
||||
* header on POST /extension-token against a single known extension
|
||||
* identity (GSTACK_EXTENSION_ID in browse/src/server.ts).
|
||||
*
|
||||
* The private half of the keypair is intentionally NOT in the repo — the
|
||||
* extension is loaded unpacked (or baked into Browser.app), so only the
|
||||
* public key is needed to pin the ID. Regenerating the keypair changes
|
||||
* the ID and requires updating both the manifest "key" and the
|
||||
* GSTACK_EXTENSION_ID constant.
|
||||
*
|
||||
* Usage: bun browse/scripts/extension-id.ts [path/to/manifest.json]
|
||||
*/
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
|
||||
const manifestPath = process.argv[2]
|
||||
?? path.join(import.meta.dir, '../../extension/manifest.json');
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
|
||||
if (typeof manifest.key !== 'string' || manifest.key.length === 0) {
|
||||
console.error(`No "key" field in ${manifestPath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
export function extensionIdFromPublicKey(publicKeyBase64: string): string {
|
||||
const der = Buffer.from(publicKeyBase64, 'base64');
|
||||
const hex = createHash('sha256').update(der).digest('hex').slice(0, 32);
|
||||
let id = '';
|
||||
for (const c of hex) {
|
||||
id += String.fromCharCode('a'.charCodeAt(0) + parseInt(c, 16));
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
console.log(extensionIdFromPublicKey(manifest.key));
|
||||
|
|
@ -1561,8 +1561,8 @@ export class BrowserManager {
|
|||
if (extensionPath) {
|
||||
launchArgs.push(`--disable-extensions-except=${extensionPath}`);
|
||||
launchArgs.push(`--load-extension=${extensionPath}`);
|
||||
// Auth token is served via /health endpoint now (no file write needed).
|
||||
// Extension reads token from /health on connect.
|
||||
// Auth token is served via POST /extension-token (pinned-origin
|
||||
// bootstrap, no file write needed). /health is liveness-only.
|
||||
console.log(`[browse] Handoff: loading extension from ${extensionPath}`);
|
||||
} else {
|
||||
console.log('[browse] Handoff: extension not found — headed mode without side panel');
|
||||
|
|
|
|||
|
|
@ -306,6 +306,17 @@ const TUNNEL_PATHS = new Set<string>([
|
|||
'/sidebar-chat',
|
||||
]);
|
||||
|
||||
/**
|
||||
* The gstack sidebar extension's pinned Chrome extension ID. Derived from
|
||||
* the "key" field in extension/manifest.json (first 16 bytes of SHA-256 of
|
||||
* the DER public key, hex nibbles mapped 0-9a-f → a-p). Reproduce with:
|
||||
* bun browse/scripts/extension-id.ts
|
||||
* POST /extension-token releases AUTH_TOKEN only to an Origin of exactly
|
||||
* `chrome-extension://<this id>`. If the manifest keypair is ever rotated,
|
||||
* this constant must be updated in the same commit.
|
||||
*/
|
||||
export const GSTACK_EXTENSION_ID = 'dgbkdbjebeiblbajiilljmhjdpmiglep';
|
||||
|
||||
/**
|
||||
* Commands reachable via POST /command over the tunnel surface. A paired
|
||||
* remote agent can drive the browser (goto, click, text, etc.) but cannot
|
||||
|
|
@ -1770,7 +1781,51 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
|
|||
);
|
||||
}
|
||||
|
||||
// Health check — no auth required, does NOT reset idle timer
|
||||
// ─── POST /extension-token — pinned-origin token bootstrap ──────
|
||||
//
|
||||
// The ONLY endpoint that hands out AUTH_TOKEN. GET /health used to
|
||||
// carry the token (headed mode + any chrome-extension:// Origin),
|
||||
// which meant ANY extension — or any localhost caller in headed
|
||||
// mode — could read the root token. Now the token is released only
|
||||
// to the one extension identity we ship: the Origin header must be
|
||||
// exactly `chrome-extension://<GSTACK_EXTENSION_ID>`, where the ID
|
||||
// is pinned by the "key" field in extension/manifest.json (derive
|
||||
// it with `bun browse/scripts/extension-id.ts`). Chrome sets Origin
|
||||
// on cross-origin POSTs from extension contexts and web pages
|
||||
// cannot forge a chrome-extension:// Origin.
|
||||
//
|
||||
// Local listener only: NEVER added to TUNNEL_PATHS, so the tunnel
|
||||
// surface 404s it by default-deny.
|
||||
if (url.pathname === '/extension-token' && req.method === 'POST') {
|
||||
// Defense-in-depth alongside the 127.0.0.1 bind: a DNS-rebinding
|
||||
// page can't present a localhost Host header. Host arrives as
|
||||
// '127.0.0.1:34567', so parse out the hostname — never compare
|
||||
// the raw header (which carries the port) against a literal.
|
||||
let hostname: string | null = null;
|
||||
try {
|
||||
hostname = new URL(`http://${req.headers.get('host') ?? ''}`).hostname;
|
||||
} catch (err) {
|
||||
if (!(err instanceof TypeError)) throw err; // TypeError = malformed Host
|
||||
}
|
||||
const originOk =
|
||||
req.headers.get('origin') === `chrome-extension://${GSTACK_EXTENSION_ID}`;
|
||||
const hostOk = hostname === '127.0.0.1' || hostname === 'localhost';
|
||||
if (!originOk || !hostOk) {
|
||||
// No detail in the body — don't teach a probing caller which
|
||||
// check failed.
|
||||
return new Response(JSON.stringify({ error: 'Forbidden' }), {
|
||||
status: 403, headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ token: authToken }), {
|
||||
status: 200, headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
// Health check — no auth required, does NOT reset idle timer.
|
||||
// NEVER carries a token in any mode: token bootstrap is
|
||||
// POST /extension-token (pinned extension Origin) and shell auth
|
||||
// is POST /pty-session. Liveness/status only.
|
||||
if (url.pathname === '/health') {
|
||||
const healthy = await browserManager.isHealthy();
|
||||
return new Response(JSON.stringify({
|
||||
|
|
@ -1778,14 +1833,6 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
|
|||
mode: browserManager.getConnectionMode(),
|
||||
uptime: Math.floor((Date.now() - startTime) / 1000),
|
||||
tabs: browserManager.getTabCount(),
|
||||
// Auth token for extension bootstrap. Safe: /health is localhost-only.
|
||||
// Previously served unconditionally, but that leaks the token if the
|
||||
// server is tunneled to the internet (ngrok, SSH tunnel).
|
||||
// In headed mode the server is always local, so return token unconditionally
|
||||
// (fixes Playwright Chromium extensions that don't send Origin header).
|
||||
...(browserManager.getConnectionMode() === 'headed' ||
|
||||
req.headers.get('origin')?.startsWith('chrome-extension://')
|
||||
? { token: authToken } : {}),
|
||||
// The chat queue is gone — Terminal pane is the sole sidebar
|
||||
// surface. Keep `chatEnabled: false` so any older extension
|
||||
// build still treats the chat input as disabled.
|
||||
|
|
@ -2310,7 +2357,7 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
|
|||
// Dual-listener model: binds a SECOND Bun.serve listener on an
|
||||
// ephemeral 127.0.0.1 port dedicated to tunnel traffic, then points
|
||||
// ngrok.forward() at THAT port. The existing local listener (which
|
||||
// serves /health+token, /cookie-picker, /inspector/*, welcome, etc.)
|
||||
// serves /extension-token, /cookie-picker, /inspector/*, welcome, etc.)
|
||||
// is never exposed to ngrok.
|
||||
//
|
||||
// Hard fail if the tunnel listener bind fails — NEVER fall back to
|
||||
|
|
@ -2808,11 +2855,10 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
|
|||
|
||||
// GET /memory — diagnostic snapshot (auth required, does NOT reset idle).
|
||||
// Same auth model as /activity/stream and /inspector/events: Bearer header
|
||||
// OR view-only SSE-session cookie. Does NOT extend /health (which already
|
||||
// leaks AUTH_TOKEN to any localhost caller in headed mode — see TODOS.md
|
||||
// "Audit /health token distribution"); a separate endpoint with the
|
||||
// standard SSE auth keeps the future /health fix from cascading into the
|
||||
// sidebar footer poll.
|
||||
// OR view-only SSE-session cookie. Does NOT extend /health (which is
|
||||
// unauthenticated liveness-only — token bootstrap moved to the pinned
|
||||
// POST /extension-token); a separate endpoint with the standard SSE auth
|
||||
// keeps /health free of anything worth stealing.
|
||||
if (url.pathname === '/memory' && req.method === 'GET') {
|
||||
const cookieToken = extractSseCookie(req);
|
||||
if (!validateAuth(req) && !validateSseSessionToken(cookieToken)) {
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ describe('Tunnel path allowlist', () => {
|
|||
const paths = extractSetContents(SERVER_SRC, 'TUNNEL_PATHS');
|
||||
// These must never be on the tunnel surface
|
||||
const forbidden = [
|
||||
'/health', '/welcome', '/cookie-picker',
|
||||
'/health', '/extension-token', '/welcome', '/cookie-picker',
|
||||
'/inspector', '/inspector/pick', '/inspector/events', '/inspector/style',
|
||||
'/tunnel/start', '/tunnel/stop',
|
||||
'/pair', '/token', '/refs',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,178 @@
|
|||
/**
|
||||
* Live behavioral tests for the v1.62 token-bootstrap contract:
|
||||
*
|
||||
* - GET /health NEVER carries a token — not in headed mode, not for a
|
||||
* chrome-extension:// Origin (the two pre-v1.62 carve-outs). IRON-RULE
|
||||
* regression tests.
|
||||
* - POST /extension-token releases the token ONLY to the pinned extension
|
||||
* Origin (chrome-extension://GSTACK_EXTENSION_ID) with a loopback Host.
|
||||
* - Host arrives with a port ('127.0.0.1:34567') and must be parsed to a
|
||||
* hostname, not compared literally (amendment C9). 'localhost:34567'
|
||||
* is accepted too.
|
||||
* - The tunnel surface 404s /extension-token (not in TUNNEL_PATHS).
|
||||
*
|
||||
* Uses the buildFetchHandler factory (same pattern as server-factory.test.ts)
|
||||
* so no listener/browser is needed. Real-HTTP coverage (Host header set by
|
||||
* the network stack) lives in pair-agent-e2e.test.ts.
|
||||
*/
|
||||
|
||||
import { describe, test, expect, beforeEach } from 'bun:test';
|
||||
import * as crypto from 'crypto';
|
||||
import {
|
||||
buildFetchHandler,
|
||||
GSTACK_EXTENSION_ID,
|
||||
type ServerConfig,
|
||||
} from '../src/server';
|
||||
import { __resetRegistry } from '../src/token-registry';
|
||||
import { BrowserManager } from '../src/browser-manager';
|
||||
import { resolveConfig } from '../src/config';
|
||||
|
||||
const PINNED_ORIGIN = `chrome-extension://${GSTACK_EXTENSION_ID}`;
|
||||
|
||||
function makeConfig(overrides: Partial<ServerConfig> = {}): ServerConfig {
|
||||
const token = 'ext-token-test-' + crypto.randomBytes(16).toString('hex');
|
||||
return {
|
||||
authToken: token,
|
||||
browsePort: 34567,
|
||||
idleTimeoutMs: 1_800_000,
|
||||
config: resolveConfig(),
|
||||
browserManager: new BrowserManager(),
|
||||
startTime: Date.now(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function headedBrowserManager(): BrowserManager {
|
||||
const bm = new BrowserManager();
|
||||
// connectionMode is private; force the headed value the old /health
|
||||
// carve-out keyed on.
|
||||
(bm as any).connectionMode = 'headed';
|
||||
return bm;
|
||||
}
|
||||
|
||||
function tokenRequest(headers: Record<string, string>): Request {
|
||||
// Direct handler invocation — no network stack to synthesize Host, so
|
||||
// every test sets it explicitly (Bun.serve always delivers one).
|
||||
return new Request('http://127.0.0.1:34567/extension-token', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
describe('GET /health never carries a token (IRON RULE)', () => {
|
||||
beforeEach(() => __resetRegistry());
|
||||
|
||||
test('headed mode: no token field in the body', async () => {
|
||||
const handle = buildFetchHandler(makeConfig({ browserManager: headedBrowserManager() }));
|
||||
const resp = await handle.fetchLocal(new Request('http://127.0.0.1:34567/health'), null);
|
||||
expect(resp.status).toBe(200);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.token).toBeUndefined();
|
||||
expect(body.mode).toBe('headed');
|
||||
});
|
||||
|
||||
test('chrome-extension Origin (even the pinned one): no token field', async () => {
|
||||
const handle = buildFetchHandler(makeConfig());
|
||||
const resp = await handle.fetchLocal(new Request('http://127.0.0.1:34567/health', {
|
||||
headers: { Origin: PINNED_ORIGIN },
|
||||
}), null);
|
||||
expect(resp.status).toBe(200);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.token).toBeUndefined();
|
||||
});
|
||||
|
||||
test('headed mode AND pinned chrome-extension Origin together: still no token', async () => {
|
||||
const handle = buildFetchHandler(makeConfig({ browserManager: headedBrowserManager() }));
|
||||
const resp = await handle.fetchLocal(new Request('http://127.0.0.1:34567/health', {
|
||||
headers: { Origin: PINNED_ORIGIN },
|
||||
}), null);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.token).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /extension-token pinned-origin bootstrap', () => {
|
||||
beforeEach(() => __resetRegistry());
|
||||
|
||||
test('pinned Origin + Host with port → 200 with the token', async () => {
|
||||
const cfg = makeConfig();
|
||||
const handle = buildFetchHandler(cfg);
|
||||
const resp = await handle.fetchLocal(tokenRequest({
|
||||
Origin: PINNED_ORIGIN,
|
||||
Host: '127.0.0.1:34567',
|
||||
}), null);
|
||||
expect(resp.status).toBe(200);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.token).toBe(cfg.authToken);
|
||||
});
|
||||
|
||||
test("Host 'localhost:34567' is accepted too (C9 hostname parse)", async () => {
|
||||
const cfg = makeConfig();
|
||||
const handle = buildFetchHandler(cfg);
|
||||
const resp = await handle.fetchLocal(tokenRequest({
|
||||
Origin: PINNED_ORIGIN,
|
||||
Host: 'localhost:34567',
|
||||
}), null);
|
||||
expect(resp.status).toBe(200);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.token).toBe(cfg.authToken);
|
||||
});
|
||||
|
||||
test('wrong extension Origin → 403, no token, no detail', async () => {
|
||||
const handle = buildFetchHandler(makeConfig());
|
||||
const resp = await handle.fetchLocal(tokenRequest({
|
||||
Origin: 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
||||
Host: '127.0.0.1:34567',
|
||||
}), null);
|
||||
expect(resp.status).toBe(403);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.token).toBeUndefined();
|
||||
// No detail about WHICH check failed
|
||||
expect(JSON.stringify(body)).not.toContain('origin');
|
||||
expect(JSON.stringify(body)).not.toContain('host');
|
||||
});
|
||||
|
||||
test('missing Origin → 403', async () => {
|
||||
const handle = buildFetchHandler(makeConfig());
|
||||
const resp = await handle.fetchLocal(tokenRequest({
|
||||
Host: '127.0.0.1:34567',
|
||||
}), null);
|
||||
expect(resp.status).toBe(403);
|
||||
});
|
||||
|
||||
test('web-page Origin → 403 (DNS-rebinding page cannot mint a token)', async () => {
|
||||
const handle = buildFetchHandler(makeConfig());
|
||||
const resp = await handle.fetchLocal(tokenRequest({
|
||||
Origin: 'http://evil.example.com',
|
||||
Host: '127.0.0.1:34567',
|
||||
}), null);
|
||||
expect(resp.status).toBe(403);
|
||||
});
|
||||
|
||||
test('non-loopback Host → 403 even with the pinned Origin', async () => {
|
||||
const handle = buildFetchHandler(makeConfig());
|
||||
const resp = await handle.fetchLocal(tokenRequest({
|
||||
Origin: PINNED_ORIGIN,
|
||||
Host: 'evil.example.com:34567',
|
||||
}), null);
|
||||
expect(resp.status).toBe(403);
|
||||
});
|
||||
|
||||
test('malformed Host → 403, not a crash', async () => {
|
||||
const handle = buildFetchHandler(makeConfig());
|
||||
const resp = await handle.fetchLocal(tokenRequest({
|
||||
Origin: PINNED_ORIGIN,
|
||||
Host: ':::not a host:::',
|
||||
}), null);
|
||||
expect(resp.status).toBe(403);
|
||||
});
|
||||
|
||||
test('tunnel surface 404s /extension-token (not in TUNNEL_PATHS)', async () => {
|
||||
const handle = buildFetchHandler(makeConfig());
|
||||
const resp = await handle.fetchTunnel(tokenRequest({
|
||||
Origin: PINNED_ORIGIN,
|
||||
Host: '127.0.0.1:34567',
|
||||
}), null);
|
||||
expect(resp.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
|
@ -22,6 +22,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
|||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { GSTACK_EXTENSION_ID } from '../src/server';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '../..');
|
||||
const SERVER_ENTRY = path.join(ROOT, 'browse/src/server.ts');
|
||||
|
|
@ -94,22 +95,44 @@ describe('pair-agent flow end-to-end (HTTP only, no ngrok)', () => {
|
|||
if (daemon) killDaemon(daemon);
|
||||
});
|
||||
|
||||
test('GET /health returns daemon status and includes token for chrome-extension origin', async () => {
|
||||
test('GET /health returns daemon status and NEVER includes a token (even for chrome-extension origins)', async () => {
|
||||
const resp = await fetch(`${daemon.baseUrl}/health`, {
|
||||
headers: { Origin: 'chrome-extension://test-extension-id' },
|
||||
headers: { Origin: `chrome-extension://${GSTACK_EXTENSION_ID}` },
|
||||
});
|
||||
expect(resp.status).toBe(200);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.status).toBeDefined();
|
||||
// Extension bootstrap — local listener delivers the token
|
||||
expect(body.token).toBe(daemon.token);
|
||||
// v1.62: token bootstrap moved to POST /extension-token. /health is
|
||||
// liveness-only in every mode.
|
||||
expect(body.token).toBeUndefined();
|
||||
});
|
||||
|
||||
test('GET /health without chrome-extension origin does NOT include token', async () => {
|
||||
test('GET /health without origin does NOT include token', async () => {
|
||||
const resp = await fetch(`${daemon.baseUrl}/health`);
|
||||
expect(resp.status).toBe(200);
|
||||
const body = await resp.json() as any;
|
||||
// Headless mode + no chrome-extension origin → token withheld
|
||||
expect(body.token).toBeUndefined();
|
||||
});
|
||||
|
||||
test('POST /extension-token with pinned Origin over real HTTP (Host carries port) returns the token', async () => {
|
||||
// Real fetch → Host arrives as '127.0.0.1:<port>'; the server must parse
|
||||
// the hostname out rather than compare the raw header (amendment C9).
|
||||
const resp = await fetch(`${daemon.baseUrl}/extension-token`, {
|
||||
method: 'POST',
|
||||
headers: { Origin: `chrome-extension://${GSTACK_EXTENSION_ID}` },
|
||||
});
|
||||
expect(resp.status).toBe(200);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.token).toBe(daemon.token);
|
||||
});
|
||||
|
||||
test('POST /extension-token with a non-pinned extension Origin returns 403 without the token', async () => {
|
||||
const resp = await fetch(`${daemon.baseUrl}/extension-token`, {
|
||||
method: 'POST',
|
||||
headers: { Origin: 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' },
|
||||
});
|
||||
expect(resp.status).toBe(403);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.token).toBeUndefined();
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -22,14 +22,29 @@ function sliceBetween(source: string, startMarker: string, endMarker: string): s
|
|||
}
|
||||
|
||||
describe('Server auth security', () => {
|
||||
// Test 1: /health serves token conditionally (headed mode or chrome extension only)
|
||||
test('/health serves token only in headed mode or to chrome extensions', () => {
|
||||
// Test 1 (IRON RULE, inverted in v1.62): /health NEVER serves a token in
|
||||
// ANY mode. Both carve-outs (headed-mode disjunct + chrome-extension://
|
||||
// Origin disjunct) are gone. Token bootstrap moved to POST /extension-token
|
||||
// with a pinned extension Origin.
|
||||
test('/health never serves a token — no headed-mode or chrome-extension carve-out', () => {
|
||||
const healthBlock = sliceBetween(SERVER_SRC, "url.pathname === '/health'", "url.pathname === '/connect'");
|
||||
// v1.35.0.0: AUTH_TOKEN const was deleted; factory uses cfg-derived authToken.
|
||||
// Token must be conditional, not unconditional
|
||||
expect(healthBlock).toContain('token: authToken');
|
||||
expect(healthBlock).toContain('headed');
|
||||
expect(healthBlock).toContain('chrome-extension://');
|
||||
expect(healthBlock).not.toContain('token: authToken');
|
||||
expect(healthBlock).not.toContain("getConnectionMode() === 'headed'");
|
||||
expect(healthBlock).not.toContain("startsWith('chrome-extension://')");
|
||||
});
|
||||
|
||||
// Test 1a: the pinned-origin bootstrap endpoint exists and gates on both
|
||||
// the exact extension Origin and a loopback Host.
|
||||
test('POST /extension-token gates on pinned Origin and loopback Host', () => {
|
||||
const tokenBlock = sliceBetween(SERVER_SRC, "url.pathname === '/extension-token'", "url.pathname === '/health'");
|
||||
expect(tokenBlock).toContain('GSTACK_EXTENSION_ID');
|
||||
expect(tokenBlock).toContain('token: authToken');
|
||||
// Host is parsed to a hostname (arrives as '127.0.0.1:34567'), never
|
||||
// compared literally against the raw header.
|
||||
expect(tokenBlock).toContain('.hostname');
|
||||
expect(tokenBlock).toContain("'127.0.0.1'");
|
||||
expect(tokenBlock).toContain("'localhost'");
|
||||
expect(tokenBlock).toContain('403');
|
||||
});
|
||||
|
||||
// Test 1b: /health does not expose sensitive browsing state
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ All command endpoints require a Bearer token:
|
|||
Authorization: Bearer gsk_sess_...
|
||||
```
|
||||
|
||||
`/connect` is unauthenticated (rate-limited) — it's how a remote agent exchanges a setup key for a scoped session token. `/health` is unauthenticated on the local listener (bootstrap) but does NOT exist on the tunnel listener (404).
|
||||
`/connect` is unauthenticated (rate-limited) — it's how a remote agent exchanges a setup key for a scoped session token. `/health` is unauthenticated on the local listener (liveness/status only — never a token) but does NOT exist on the tunnel listener (404). Extension token bootstrap is `POST /extension-token` on the local listener, gated by the pinned `chrome-extension://` Origin; it is not on the tunnel surface either.
|
||||
|
||||
SSE endpoints (`/activity/stream`, `/inspector/events`) accept either a Bearer token or the HttpOnly `gstack_sse` cookie (minted via `POST /sse-session`, 30-minute TTL, stream-scope only — cannot be used against `/command`). As of v1.6.0.0 the `?token=<ROOT>` query-string auth is no longer accepted.
|
||||
|
||||
|
|
@ -80,6 +80,9 @@ Response: (plain text result of the command)
|
|||
|
||||
#### GET /health
|
||||
Server status. No auth required. Returns status, tabs, mode, uptime.
|
||||
Never carries a token — extension token bootstrap is `POST /extension-token`
|
||||
(local listener only, validates the pinned `chrome-extension://` Origin and a
|
||||
loopback Host; 403 otherwise). Not reachable over the tunnel (404).
|
||||
|
||||
### Commands
|
||||
|
||||
|
|
|
|||
|
|
@ -62,6 +62,10 @@ T+500ms terminal-agent.ts boots
|
|||
└── Probes claude → writes claude-available.json
|
||||
|
||||
T+1-3s Extension loads, sidebar opens
|
||||
├── background.js: GET /health (liveness only — no token) then
|
||||
│ POST /extension-token → AUTH_TOKEN. The server releases the
|
||||
│ token only to Origin chrome-extension://<pinned id>; the
|
||||
│ manifest "key" pins the ID (browse/scripts/extension-id.ts)
|
||||
├── sidepanel-terminal.js: setState(IDLE), shows "Starting Claude Code..."
|
||||
└── tryAutoConnect() polls until window.gstackServerPort + token are set
|
||||
|
||||
|
|
@ -105,7 +109,7 @@ The protocol-token path is what the browser actually uses.
|
|||
|
||||
| Token | Lives in | Used for | Lifetime |
|
||||
|-------|----------|----------|----------|
|
||||
| `AUTH_TOKEN` | `<stateDir>/browse.json`; in-memory in server.ts | `/pty-session` POST (mint cookie + token) | server lifetime |
|
||||
| `AUTH_TOKEN` | `<stateDir>/browse.json`; in-memory in server.ts; extension memory via pinned-origin `POST /extension-token` (never `GET /health`) | `/pty-session` POST (mint cookie + token) | server lifetime |
|
||||
| `gstack-pty.<...>` (Sec-WebSocket-Protocol) | Browser memory only; agent `validTokens` Set | `/ws` upgrade auth | 30 min, auto-revoked on WS close |
|
||||
| `INTERNAL_TOKEN` | `<stateDir>/terminal-internal-token`; in agent memory | server → agent loopback `/internal/grant` | agent lifetime |
|
||||
|
||||
|
|
|
|||
|
|
@ -32,22 +32,34 @@ function getBaseUrl() {
|
|||
|
||||
// ─── Auth Token Bootstrap ─────────────────────────────────────
|
||||
|
||||
// Token bootstrap: POST /extension-token. The server validates our Origin
|
||||
// (chrome-extension://<pinned id> — the manifest "key" pins the ID) before
|
||||
// releasing the token. GET /health is liveness/status only and never
|
||||
// carries a token. Returns true on success, false on failure; a 403 means
|
||||
// the server doesn't trust this extension identity — treat as disconnected
|
||||
// rather than retrying forever with a stale token.
|
||||
async function loadAuthToken() {
|
||||
if (authToken) return;
|
||||
// Get token from browse server /health endpoint (localhost-only, safe).
|
||||
// Previously read from .auth.json in extension dir, but that breaks
|
||||
// read-only .app bundles and codesigning.
|
||||
const base = getBaseUrl();
|
||||
if (!base) return;
|
||||
if (!base) return false;
|
||||
try {
|
||||
const resp = await fetch(`${base}/health`, { signal: AbortSignal.timeout(3000) });
|
||||
const resp = await fetch(`${base}/extension-token`, {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (resp.status === 403) {
|
||||
console.error('[gstack bg] /extension-token 403 — extension identity not trusted by server');
|
||||
authToken = null;
|
||||
setDisconnected();
|
||||
return false;
|
||||
}
|
||||
if (resp.ok) {
|
||||
const data = await resp.json();
|
||||
if (data.token) authToken = data.token;
|
||||
if (data.token) { authToken = data.token; return true; }
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[gstack bg] Failed to load auth token:', err.message);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ─── Health Polling ────────────────────────────────────────────
|
||||
|
|
@ -59,17 +71,16 @@ async function checkHealth() {
|
|||
return;
|
||||
}
|
||||
|
||||
// Retry loading auth token if we don't have one yet
|
||||
if (!authToken) await loadAuthToken();
|
||||
|
||||
try {
|
||||
const resp = await fetch(`${base}/health`, { signal: AbortSignal.timeout(3000) });
|
||||
if (!resp.ok) { setDisconnected(); return; }
|
||||
const data = await resp.json();
|
||||
if (data.status === 'healthy') {
|
||||
// Always refresh auth token from /health — the server generates a new
|
||||
// token on each restart, so the old one becomes stale.
|
||||
if (data.token) authToken = data.token;
|
||||
// Always refresh the auth token — the server generates a new token
|
||||
// on each restart, so the old one becomes stale. loadAuthToken()
|
||||
// already flips to disconnected on a 403.
|
||||
const gotToken = await loadAuthToken();
|
||||
if (!gotToken && !authToken) return;
|
||||
// Forward chatEnabled so sidepanel can show/hide chat tab
|
||||
setConnected({ ...data, chatEnabled: !!data.chatEnabled });
|
||||
} else {
|
||||
|
|
@ -577,27 +588,49 @@ chrome.tabs.onUpdated.addListener((_id, changeInfo) => {
|
|||
}
|
||||
});
|
||||
|
||||
// ─── v1.62 identity-pin migration notice ────────────────────────
|
||||
//
|
||||
// The manifest "key" added in v1.62 pins the extension ID, which changes
|
||||
// the ID for existing installs — chrome.storage.local is keyed by
|
||||
// extension ID, so panel-local state (saved port, snoozes) resets once.
|
||||
// Explain that in-product, one time.
|
||||
async function announceIdentityPinOnce() {
|
||||
try {
|
||||
const data = await chrome.storage.local.get('gstack_id_migrated_v162');
|
||||
if (data.gstack_id_migrated_v162) return;
|
||||
console.log('[gstack] gstack sidebar: extension identity pinned in v1.62 — panel state reset once.');
|
||||
chrome.runtime.sendMessage({
|
||||
type: 'gstack-migration-notice',
|
||||
message: 'gstack sidebar: extension identity pinned in v1.62 — panel state reset once.',
|
||||
}).catch(() => {
|
||||
// Expected: panel not open. The console line above still lands.
|
||||
});
|
||||
await chrome.storage.local.set({ gstack_id_migrated_v162: true });
|
||||
} catch (err) {
|
||||
console.debug('[gstack] identity-pin notice failed (non-fatal):', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Startup ────────────────────────────────────────────────────
|
||||
|
||||
// Fast-retry health check on startup. The server may not be listening yet
|
||||
// (Chromium launches before Bun.serve starts). Retry every 1s for the
|
||||
// first 15 seconds, then switch to 10s polling.
|
||||
loadAuthToken().then(() => {
|
||||
loadPort().then(() => {
|
||||
let startupAttempts = 0;
|
||||
const startupCheck = setInterval(async () => {
|
||||
startupAttempts++;
|
||||
await checkHealth();
|
||||
if (isConnected || startupAttempts >= 15) {
|
||||
clearInterval(startupCheck);
|
||||
// Switch to slow polling now that we're connected (or gave up)
|
||||
if (!healthInterval) {
|
||||
healthInterval = setInterval(checkHealth, 10000);
|
||||
}
|
||||
if (!isConnected) {
|
||||
console.log('[gstack] Startup health checks failed after 15 attempts, falling back to 10s polling');
|
||||
}
|
||||
announceIdentityPinOnce();
|
||||
loadPort().then(() => {
|
||||
let startupAttempts = 0;
|
||||
const startupCheck = setInterval(async () => {
|
||||
startupAttempts++;
|
||||
await checkHealth();
|
||||
if (isConnected || startupAttempts >= 15) {
|
||||
clearInterval(startupCheck);
|
||||
// Switch to slow polling now that we're connected (or gave up)
|
||||
if (!healthInterval) {
|
||||
healthInterval = setInterval(checkHealth, 10000);
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
if (!isConnected) {
|
||||
console.log('[gstack] Startup health checks failed after 15 attempts, falling back to 10s polling');
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
"name": "gstack browse",
|
||||
"version": "0.1.0",
|
||||
"description": "Live activity feed and @ref overlays for gstack browse",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApp4uyDmQADJ/MPoKybEvBPpuGWxsXiNMo5jJFFaEaC3yPJnB4y8E0UuvE56n2KlQzaqlnBOt4T8w0ApTbNABZpEnSGQJVmkbT8a62WXefYZm79bMgzW/bNIZ4QYWNEAtZb0wvncMNSOyU9mga1s3eGWtukHs2Zf5spXRLQGV/on9l8iN9QPRM/VB0AxtUc2DTYjwkTGCAOMFiaq02miP0/hW6AeltBW9R0aHgbnJw2H2YVrgQXRvGxD1DMQe6NzGVVqKGhpUdYGPw4ONWOKijdignz+j+90HSrCK06HUy80jiKAYmdZePnn++N5meIJY+bWk7RqxS6er8Ow2U65TywIDAQAB",
|
||||
"permissions": ["sidePanel", "storage", "activeTab", "scripting", "tabs"],
|
||||
"host_permissions": ["http://127.0.0.1:*/", "ws://127.0.0.1:*/"],
|
||||
"action": {
|
||||
|
|
|
|||
|
|
@ -504,7 +504,8 @@
|
|||
window.gstackScanForPTYInject = async function (text, origin) {
|
||||
if (!text) return { allow: false, verdict: 'BLOCK', reasons: ['empty-text'] };
|
||||
try {
|
||||
const resp = await fetch('http://127.0.0.1:34567/pty-inject-scan', {
|
||||
const serverPort = getServerPort() || 34567;
|
||||
const resp = await fetch(`http://127.0.0.1:${serverPort}/pty-inject-scan`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
|
|
@ -529,21 +530,13 @@
|
|||
};
|
||||
|
||||
// The auth token for /pty-inject-scan comes from the same source the
|
||||
// sidepanel uses for /pty-session — a runtime fetch from /health (which
|
||||
// already returns AUTH_TOKEN in headed mode per CLAUDE.md's v1.1 TODO).
|
||||
// We don't echo the token here; this helper is a thin proxy around the
|
||||
// existing pattern.
|
||||
// sidepanel uses for /pty-session — window.gstackAuthToken, set by
|
||||
// sidepanel.js after the pinned-origin POST /extension-token bootstrap.
|
||||
// The old fallback here fetched /health and read token keys the server
|
||||
// never sent (AUTH_TOKEN/authToken) — dead code since /health stopped
|
||||
// carrying any token.
|
||||
async function getAuthTokenForScan() {
|
||||
if (window.__gstackPtyScanToken) return window.__gstackPtyScanToken;
|
||||
try {
|
||||
const resp = await fetch('http://127.0.0.1:34567/health');
|
||||
const body = await resp.json();
|
||||
const token = body.AUTH_TOKEN || body.authToken || '';
|
||||
if (token) window.__gstackPtyScanToken = token;
|
||||
return token;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
return getAuthToken() || '';
|
||||
}
|
||||
|
||||
async function connect() {
|
||||
|
|
|
|||
|
|
@ -1304,21 +1304,36 @@ async function tryConnect() {
|
|||
});
|
||||
if (healthResp.ok) {
|
||||
const data = await healthResp.json();
|
||||
if (data.status === 'healthy' && data.token) {
|
||||
if (data.status === 'healthy') {
|
||||
// /health is liveness-only — the token comes from the pinned-origin
|
||||
// POST /extension-token bootstrap (our chrome-extension:// Origin
|
||||
// is validated server-side against the manifest-pinned ID).
|
||||
const tokenResp = await fetch(`http://127.0.0.1:${port}/extension-token`, {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(2000),
|
||||
});
|
||||
const tokenData = tokenResp.ok ? await tokenResp.json() : null;
|
||||
if (tokenData?.token) {
|
||||
setLoadingStatus(
|
||||
`Server healthy on port ${port}, connecting...`,
|
||||
`token: yes (from /extension-token)\nStarting SSE + activity feed...`
|
||||
);
|
||||
updateConnection(`http://127.0.0.1:${port}`, tokenData.token);
|
||||
// The SEC shield used to drive off /health.security via the chat
|
||||
// path's classifier; with the chat path ripped, the indicator is
|
||||
// not driven yet. Leaving the shield element hidden by default.
|
||||
return;
|
||||
}
|
||||
setLoadingStatus(
|
||||
`Server healthy on port ${port}, connecting...`,
|
||||
`token: yes (from /health)\nStarting SSE + activity feed...`
|
||||
`Server healthy but token bootstrap failed (attempt ${connectAttempts})`,
|
||||
`POST /extension-token → ${tokenResp.status}${tokenResp.status === 403 ? ' (extension identity not trusted)' : ''}`
|
||||
);
|
||||
} else {
|
||||
setLoadingStatus(
|
||||
`Server responded but not healthy (attempt ${connectAttempts})`,
|
||||
`status: ${data.status}`
|
||||
);
|
||||
updateConnection(`http://127.0.0.1:${port}`, data.token);
|
||||
// The SEC shield used to drive off /health.security via the chat
|
||||
// path's classifier; with the chat path ripped, the indicator is
|
||||
// not driven yet. Leaving the shield element hidden by default.
|
||||
return;
|
||||
}
|
||||
setLoadingStatus(
|
||||
`Server responded but not healthy (attempt ${connectAttempts})`,
|
||||
`status: ${data.status}\ntoken: ${data.token ? 'yes' : 'no'}`
|
||||
);
|
||||
} else {
|
||||
setLoadingStatus(
|
||||
`Server returned ${healthResp.status} (attempt ${connectAttempts})`,
|
||||
|
|
@ -1355,6 +1370,23 @@ chrome.runtime.onMessage.addListener((msg) => {
|
|||
fetchRefs();
|
||||
}
|
||||
}
|
||||
// One-time v1.62 identity-pin notice from background.js. Transient banner —
|
||||
// no dedicated element in sidepanel.html since this fires once per install.
|
||||
if (msg.type === 'gstack-migration-notice' && msg.message) {
|
||||
console.log('[gstack sidebar]', msg.message);
|
||||
try {
|
||||
const banner = document.createElement('div');
|
||||
banner.textContent = msg.message;
|
||||
banner.style.cssText =
|
||||
'position:fixed;left:8px;right:8px;bottom:40px;z-index:9999;' +
|
||||
'background:#1f2937;color:#f5a623;border:1px solid #f5a623;' +
|
||||
'border-radius:6px;padding:8px 10px;font-size:12px;text-align:left;';
|
||||
document.body.appendChild(banner);
|
||||
setTimeout(() => banner.remove(), 8000);
|
||||
} catch (err) {
|
||||
console.debug('[gstack sidebar] migration banner failed:', err && err.message);
|
||||
}
|
||||
}
|
||||
if (msg.type === 'inspectResult') {
|
||||
inspectorPickerActive = false;
|
||||
inspectorPickBtn.classList.remove('active');
|
||||
|
|
|
|||
Loading…
Reference in New Issue