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:
Garry Tan
2026-08-12 15:31:49 -07:00
parent 2ae38785a1
commit a2751b7cf2
14 changed files with 471 additions and 94 deletions
+1 -1
View File
@@ -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',
+178
View File
@@ -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);
});
});
+29 -6
View File
@@ -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 -7
View File
@@ -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