From ba8c0cf09aa2a20b9730fd75b36ef090230ad2f3 Mon Sep 17 00:00:00 2001 From: LavonTMCQ Date: Tue, 24 Nov 2026 16:40:14 -0500 Subject: [PATCH] fix(connect): narrow what a relayed machine stream can reach A web-machine stream now replays only GET and HEAD of the notice pages and static files, carries no local credential, and opens no loopback realtime socket. Plugin streams are refused because their grants arrive as plain claims the Mac cannot verify. Co-Authored-By: Claude Opus 5.5 --- docs/internals/connect-contract.md | 85 ++++----- docs/operations/browser-console-removal.md | 4 +- src/lib/connect/machine-attach.test.ts | 123 ++++++------ src/lib/connect/machine-attach.ts | 191 +++++-------------- src/lib/connect/machine-full-surface.test.ts | 57 ++---- src/lib/connect/plugin-relay.ts | 35 ---- src/lib/connect/web-machine-surface.ts | 18 ++ src/lib/mobile/relay-http-replay.ts | 10 - tests/plugin-front-door-real-path.test.ts | 14 +- tests/plugin-relay-real-path.test.ts | 178 +++-------------- tests/plugin-task-draft-real-path.test.ts | 9 +- 11 files changed, 216 insertions(+), 508 deletions(-) delete mode 100644 src/lib/connect/plugin-relay.ts diff --git a/docs/internals/connect-contract.md b/docs/internals/connect-contract.md index 874feaf344..efab7e1daf 100644 --- a/docs/internals/connect-contract.md +++ b/docs/internals/connect-contract.md @@ -243,29 +243,30 @@ No relay client or relay-server code is part of phase 1a because none of those i The account-authenticated `/web/machine/:machineId` socket is one virtual browser session. The relay allocates one `sid` for it and sends `mux-open` to the -registered machine. The desktop opens one loopback `/ws` connection for that -`sid`, using the local operator token only on the loopback URL. After the local -socket opens, the desktop returns `mux-ready`. - -The web edge uses that single session in two ways: - -1. HTTP requests use the existing - `http-req { rid, method, path, headers, bodyB64 }` control frame. Documents, - Next.js chunks, CSS, fonts, images, and API responses all return through - `http-res` plus ordered `http-res-part` frames. Response bodies are base64, - split at 256 KiB of encoded data per frame, and include the decoded - `content-length` plus the safe content, cache, range, and validator headers. -2. Every non-HTTP frame is a raw `/ws` application frame. The desktop forwards - it unchanged to the loopback realtime socket, and returns each loopback frame - unchanged on the web session. This mirrors the phone connector's inner - realtime shape without sharing its routing map, device credential, E2EE - handshake, or `/mac` code path. - -The browser host exposes this session to the loaded mobile application as -`window.__O8_WEB_MACHINE_TRANSPORT__`: `fetch` maps same-origin page/API requests -to HTTP control frames, while `openWebSocket('/ws')` maps the mobile realtime -hook to raw frames on the same session. The web host owns the authenticated -account handshake; browser code never supplies an account ID. +registered machine, and the desktop answers `mux-ready`. + +Relay frames are not end-to-end encrypted, so the desktop limits what a +web-machine stream can reach: + +1. HTTP requests use the `http-req { rid, method, path, headers, bodyB64 }` + control frame. Only `GET` and `HEAD` of the desktop-app notice pages (`/`, + `/mobile`, `/dashboard`), `/icon.png`, `/favicon.ico` and `/_next/static/*` + are replayed (`webMachineRouteAllowed` in + `src/lib/connect/web-machine-surface.ts`). Any other route or method gets + `403 web_machine_route_forbidden` and never reaches the local server. + Responses return through `http-res` plus ordered `http-res-part` frames, + base64 bodies split at 256 KiB of encoded data per frame. +2. A replay carries no credential. Any `Authorization` in the frame is dropped, + and the local operator token is never attached. The allowlisted pages need + none. +3. Realtime (non-HTTP) frames are dropped. The desktop opens no loopback `/ws` + connection for a relayed stream. + +A `mux-open` with `surface: "plugin"` is refused with +`mux-close 4403 plugin_grant_unverifiable`. The relay sends plugin grants as +plain claims, which the desktop cannot verify. Plugin streams stay off until the +account service signs each grant with a key the desktop pins, binding the +account, machine, client, scopes, stream and expiry. ### Local credential exclusion @@ -285,19 +286,14 @@ requires all three canonical facts before emitting the safe must not contain the local `ws-token` meta value. On that safe browser surface, `#tk=` is scrubbed without being read or stored, -the paired-phone localStorage credential is ignored, API fetches use the web -machine transport, and `/ws` never falls back to a direct local URL. The local -operator token exists only in the desktop's server-side HTTP Authorization -override and loopback WebSocket URL; no relay frame or remote document contains -it. As a final fail-closed boundary, the machine replay scans each decoded local -response for the exact operator token and returns -`502 local_credential_exposure_blocked` with an empty body if any page, asset, -credential-export endpoint, or reflected response contains it. -Outbound loopback realtime frames receive the same exact-value check; a match -closes that web stream with `4403 local_credential_exposure_blocked`. - -Closing the web session sends `mux-close` and closes its loopback HTTP/realtime -state. Dropping the active machine socket without a replacement closes its +the paired-phone localStorage credential is ignored, and `/ws` never falls back +to a direct local URL. No relay replay carries the local operator token. As a +final fail-closed boundary, the machine replay scans each decoded local response +for the exact operator token and returns `502 local_credential_exposure_blocked` +with an empty body if any page or asset contains it. + +Closing the web session sends `mux-close` and aborts its in-flight local HTTP +requests. Dropping the active machine socket without a replacement closes its local streams and every attached web session with `1012 machine_disconnected`. Ticket refresh supersedes the machine socket in-place and reopens the existing `sid` on the replacement. Any browser @@ -403,9 +399,9 @@ and account-token `/web/machine/:machineId` paths are unchanged. Surface CORS responses are emitted only for `https://o8.run` and `https://www.o8.run`. HTML sets `frame-ancestors` to those two origins. A ticket for machine A receives `403 machine_mismatch` when presented to machine B. The -desktop's cut 3a token-free render marker, `#tk=` scrubbing, server-side -Authorization override, response byte scan, and realtime byte scan remain the -credential boundary; the relay never receives or forwards the local ws-token. +desktop's cut 3a route allowlist, credential-free replay, token-free render +marker, `#tk=` scrubbing and response byte scan remain the credential boundary; +the relay never receives or forwards the local ws-token. The prompt-launch path must: @@ -415,14 +411,15 @@ The prompt-launch path must: 4. Forward the prompt to the selected machine's existing local orchestrator API through the relay. 5. Return the existing thread/turn identity so the website can show progress without inventing a second orchestration model. -The Cut 2 desktop mux carries the existing generic `http-req` frames and -replays them through the local operator gate. Phase 3 can therefore use +Relay replay does not reach these routes today. A web-machine stream replays +only the notice pages and static files, with no local credential (see cut 3a). +Prompt launch over the relay waits for end-to-end encryption between the +browser and the desktop. When it lands, it would use `GET /api/panel/repos` for repository discovery, `POST /api/orchestrator/spawn-prompt` for prompt submission, and `GET /api/orchestrator/lane-events` plus -`GET /api/mobile/orchestrator/threads` for progress and thread summaries. The -machine connector replaces any web-supplied authorization with the local -operator token before replay, so these routes do not gain a second auth path. +`GET /api/mobile/orchestrator/threads` for progress and thread summaries, each +under a credential scoped to that encrypted session. `spawn-prompt` preserves an explicit positive safe-integer `count`, including counts above five. An omitted count defaults to one. Null, strings, fractions, diff --git a/docs/operations/browser-console-removal.md b/docs/operations/browser-console-removal.md index 6ff807b301..d253675bf5 100644 --- a/docs/operations/browser-console-removal.md +++ b/docs/operations/browser-console-removal.md @@ -93,8 +93,8 @@ Two relay paths share the same tunnel protocol The web-machine surface marks those page loads (`src/lib/connect/web-machine-surface.ts`; read in `src/components/shell-layout.tsx`, `ApiBearerBootstrap`, the theme pre-paint stamp and - `src/lib/mobile/ws-token-client.ts`). The same transport carries plugin - relay grants (`src/lib/connect/plugin-relay.ts`). + `src/lib/mobile/ws-token-client.ts`). Plugin streams over this + transport are refused until the account service signs plugin grants. With the pages gone, a remote browser session reaches only the notice and the voice pages. Removing the browser-session part of machine attach, and the diff --git a/src/lib/connect/machine-attach.test.ts b/src/lib/connect/machine-attach.test.ts index 1da5ff238c..5edcbceeac 100644 --- a/src/lib/connect/machine-attach.test.ts +++ b/src/lib/connect/machine-attach.test.ts @@ -123,41 +123,44 @@ afterEach(async () => { }); describe('machine relay attach real path', () => { - it('presents the machine ticket and serves generic web HTTP mux through the local operator gate', async () => { - let responseFrame: Record | null = null; - const localWebSocket = await startRelay(); + it('presents the machine ticket and replays only notice-page reads, with no local credential', async () => { + const responses = new Map>(); const relay = await startRelay((socket) => { socket.send(JSON.stringify({ t: 'mux-open', sid: 'web-1' })); socket.on('message', (raw) => { const outer = parseFrame(raw); if (outer.t === 'mux-ready') { - socket.send(JSON.stringify({ - t: 'mux', - sid: 'web-1', - seq: 1, - payload: Buffer.from(JSON.stringify({ - t: 'http-req', - rid: 'request-1', - method: 'GET', - path: '/api/panel/repos', - authorization: 'Bearer untrusted-web-value', - }), 'utf8').toString('base64'), - })); + const requests = [ + { rid: 'page', method: 'GET', path: '/mobile', authorization: 'Bearer untrusted-web-value' }, + { rid: 'asset', method: 'GET', path: '/_next/static/chunks/app.js', headers: { Authorization: 'Bearer untrusted-web-value' } }, + { rid: 'api', method: 'GET', path: '/api/panel/repos' }, + { rid: 'write', method: 'POST', path: '/mobile' }, + { rid: 'escape', method: 'GET', path: '/_next/static/%2e%2e/api/panel/repos' }, + ]; + for (const request of requests) { + socket.send(JSON.stringify({ + t: 'mux', + sid: 'web-1', + seq: 1, + payload: Buffer.from(JSON.stringify({ t: 'http-req', ...request }), 'utf8').toString('base64'), + })); + } return; } if (outer.t === 'mux' && typeof outer.payload === 'string') { - responseFrame = JSON.parse( + const response = JSON.parse( Buffer.from(outer.payload, 'base64').toString('utf8'), ) as Record; + responses.set(String(response.rid), response); } }); }); const fetchCalls: Array<{ url: string; init?: RequestInit }> = []; const fetchImpl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { fetchCalls.push({ url: String(input), init }); - return new Response(JSON.stringify({ repos: [{ localPath: '/work/repo' }] }), { + return new Response('notice', { status: 200, - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'text/html' }, }); }) as typeof fetch; const machineId = 'machine_01HREALPATH'; @@ -166,7 +169,6 @@ describe('machine relay attach real path', () => { machineId, relayUrl: relay.url, apiBase: 'http://127.0.0.1:47120', - localWebSocketUrl: `${localWebSocket.url}/ws`, operatorToken: () => 'local-operator-token', ticketProvider: async () => issued, fetchImpl, @@ -175,7 +177,7 @@ describe('machine relay attach real path', () => { }); connector.start(); - await waitFor(() => responseFrame !== null); + await waitFor(() => responses.size === 5); expect(relay.connections).toHaveLength(1); expect(relay.connections[0]).toMatchObject({ @@ -191,17 +193,22 @@ describe('machine relay attach real path', () => { aud: 'o8-relay', }); - expect(fetchCalls).toHaveLength(1); - expect(fetchCalls[0]?.url).toBe('http://127.0.0.1:47120/api/panel/repos'); - const headers = new Headers(fetchCalls[0]?.init?.headers); - expect(headers.get('authorization')).toBe('Bearer local-operator-token'); - expect(headers.get('x-o8-client-addr')).toBe('o8-relay-forward'); - expect(headers.get('x-o8-relay-forward')).toBe('1'); - expect(responseFrame).toMatchObject({ - t: 'http-res', - rid: 'request-1', - status: 200, - }); + expect(fetchCalls.map((call) => call.url)).toEqual([ + 'http://127.0.0.1:47120/mobile', + 'http://127.0.0.1:47120/_next/static/chunks/app.js', + ]); + for (const call of fetchCalls) { + const headers = new Headers(call.init?.headers); + expect(headers.get('authorization')).toBeNull(); + expect(headers.get('x-o8-client-addr')).toBe('o8-relay-forward'); + expect(headers.get('x-o8-relay-forward')).toBe('1'); + expect(headers.get('x-o8-relay-surface')).toBe('web-machine'); + } + expect(responses.get('page')).toMatchObject({ t: 'http-res', status: 200 }); + expect(responses.get('asset')).toMatchObject({ t: 'http-res', status: 200 }); + for (const rid of ['api', 'write', 'escape']) { + expect(responses.get(rid)).toMatchObject({ t: 'http-res', status: 403, error: 'web_machine_route_forbidden' }); + } connector.stop('test-complete'); }); @@ -340,42 +347,37 @@ describe('machine relay attach real path', () => { connector.stop('test-complete'); }); - it('bridges each web-machine stream to the local realtime socket and tears it down', async () => { - let localReceived = ''; - let relayedReply = ''; - let localClosed = false; - const localWebSocket = await startRelay((socket) => { - socket.on('message', (raw) => { - localReceived = raw.toString(); - socket.send(JSON.stringify({ channel: 'pong', seq: 7 })); - }); - socket.on('close', () => { - localClosed = true; - }); - }); + it('opens no local realtime socket for a web-machine stream and drops its realtime frames', async () => { + const localWebSocket = await startRelay(); + let ready = false; + let relayed = 0; const relay = await startRelay((socket) => { socket.send(JSON.stringify({ t: 'mux-open', sid: 'web-realtime' })); socket.on('message', (raw) => { const outer = parseFrame(raw); if (outer.t === 'mux-ready') { + ready = true; socket.send(JSON.stringify({ t: 'mux', sid: 'web-realtime', seq: 1, payload: Buffer.from(JSON.stringify({ type: 'ping' }), 'utf8').toString('base64'), })); + // An ordered stream open after the frame proves it was processed. + socket.send(JSON.stringify({ t: 'mux-open', sid: 'barrier' })); return; } - if (outer.t === 'mux' && typeof outer.payload === 'string') { - relayedReply = Buffer.from(outer.payload, 'base64').toString('utf8'); - socket.send(JSON.stringify({ t: 'mux-close', sid: 'web-realtime' })); - } + if (outer.t === 'mux') relayed++; }); }); + let barrier = false; + relay.server.on('connection', (socket) => socket.on('message', (raw) => { + const outer = parseFrame(raw); + if (outer.t === 'mux-ready' && outer.sid === 'barrier') barrier = true; + })); const connector = new MachineRelayConnector({ machineId: 'machine_realtime', relayUrl: relay.url, - localWebSocketUrl: `${localWebSocket.url}/ws`, operatorToken: () => 'local-operator-token', ticketProvider: async () => ticket('machine_realtime'), reconnectBaseMs: 20, @@ -383,26 +385,15 @@ describe('machine relay attach real path', () => { }); connector.start(); - await waitFor(() => localReceived.length > 0 && relayedReply.length > 0 && localClosed); + await waitFor(() => ready && barrier); - expect(localWebSocket.connections).toEqual([{ - path: '/ws?token=local-operator-token', - authorization: undefined, - machineId: undefined, - }]); - expect(localReceived).toBe(JSON.stringify({ type: 'ping' })); - expect(relayedReply).toBe(JSON.stringify({ channel: 'pong', seq: 7 })); + expect(localWebSocket.connections).toEqual([]); + expect(relayed).toBe(0); connector.stop('test-complete'); }); it('rotates the relay ticket before expiry without waiting for a socket drop', async () => { - let localBridgeCloses = 0; - const localWebSocket = await startRelay((socket) => { - socket.on('close', () => { - localBridgeCloses++; - }); - }); const relay = await startRelay((socket) => { socket.send(JSON.stringify({ t: 'devices', count: 0 })); socket.send(JSON.stringify({ t: 'mux-open', sid: 'refresh-stream' })); @@ -411,7 +402,6 @@ describe('machine relay attach real path', () => { const connector = new MachineRelayConnector({ machineId: 'machine_refresh', relayUrl: relay.url, - localWebSocketUrl: `${localWebSocket.url}/ws`, operatorToken: () => 'local-operator-token', ticketProvider: async () => ticket('machine_refresh', ++issued), refreshIntervalMs: 40, @@ -425,8 +415,6 @@ describe('machine relay attach real path', () => { expect(issued).toBeGreaterThanOrEqual(2); expect(relay.connections[0]?.authorization).not.toBe(relay.connections[1]?.authorization); - expect(localWebSocket.connections).toHaveLength(1); - expect(localBridgeCloses).toBe(0); connector.stop('test-complete'); }); @@ -435,7 +423,6 @@ describe('machine relay attach real path', () => { const authenticatedSockets: WebSocket[] = []; let rotationRejected = false; let muxReady = false; - const localWebSocket = await startRelay(); const relay = await startRelay((socket, index) => { if (index === 0) { authenticatedSockets.push(socket); @@ -452,7 +439,6 @@ describe('machine relay attach real path', () => { const connector = new MachineRelayConnector({ machineId: 'machine_rotation_failure', relayUrl: relay.url, - localWebSocketUrl: `${localWebSocket.url}/ws`, operatorToken: () => 'local-operator-token', ticketProvider: async () => ticket('machine_rotation_failure', ++issued), refreshIntervalMs: 40, @@ -470,7 +456,6 @@ describe('machine relay attach real path', () => { expect(relay.connections).toHaveLength(2); expect(activeSocket?.readyState).toBe(WebSocket.OPEN); - expect(localWebSocket.connections).toHaveLength(1); connector.stop('test-complete'); }); diff --git a/src/lib/connect/machine-attach.ts b/src/lib/connect/machine-attach.ts index a824f51a32..5c7cf63650 100644 --- a/src/lib/connect/machine-attach.ts +++ b/src/lib/connect/machine-attach.ts @@ -16,7 +16,7 @@ import { resolvePortInfo } from '@/lib/panel/api-port'; import { getOrCreateWsToken } from '@/lib/ws-auth'; import type { MachineRelayTicket } from './machine-registry'; -import { parsePluginRelayGrant, pluginReplayAuthorization, type PluginRelayGrant } from './plugin-relay'; +import { O8_WEB_MACHINE_SURFACE, webMachineRouteAllowed } from './web-machine-surface'; const P = '[connect]'; const DEFAULT_HTTP_TIMEOUT_MS = 55_000; @@ -32,11 +32,7 @@ type ConnectReason = 'attach' | 'reconnect' | 'ticket-refresh'; interface MachineStreamState { sid: string; - bridge: WebSocket | null; - pendingFrames: string[]; - pendingBytes: number; closing: boolean; - pluginGrant?: PluginRelayGrant; } export interface MachineRelayConnectorConfig { @@ -44,7 +40,7 @@ export interface MachineRelayConnectorConfig { ticketProvider: () => Promise; relayUrl?: string; apiBase?: string; - localWebSocketUrl?: string; + /** Only to block responses that would carry it; never sent on a replay. */ operatorToken?: () => string; fetchImpl?: typeof fetch; maxTunnelBytes?: number; @@ -319,13 +315,18 @@ export class MachineRelayConnector { ); if (!frame) return; if (frame.t === 'mux-open' && typeof frame.sid === 'string') { - if (frame.surface === 'plugin') { - const grant = parsePluginRelayGrant(frame.grant); - if (!grant) return; - this.openStream(frame.sid, grant); - } else if (frame.surface === undefined) { + if (frame.surface === undefined) { this.openStream(frame.sid); + return; } + // A plugin grant arrives as plain claims the Mac cannot verify, so a + // plugin stream is refused until the account service signs its grants. + this.sendControl({ + t: 'mux-close', + sid: frame.sid, + code: 4403, + reason: frame.surface === 'plugin' ? 'plugin_grant_unverifiable' : 'surface_not_supported', + }); return; } if (frame.t === 'mux-close' && typeof frame.sid === 'string') { @@ -353,48 +354,28 @@ export class MachineRelayConnector { if (rid) this.httpRequests.cancel(sid, rid); return; } - if (message.t === 'http-req') { - const apiBase = this.config.apiBase ?? localApiBase(); - const authorization = state.pluginGrant - ? pluginReplayAuthorization(this.config.machineId, state.pluginGrant, message as HttpReqFrame) - : `Bearer ${this.localOperatorToken()}`; - if (!authorization) { - this.sendMux(sid, { t: 'http-res', rid: message.rid, status: 403, error: 'plugin_route_forbidden', last: true }); - return; - } - void replayRelayHttpRequest({ - sid, - request: message as HttpReqFrame, - apiBase, - requestRegistry: this.httpRequests, - timeoutMs: this.httpRequestTimeoutMs, - maxTunnelBytes: state.pluginGrant ? 65_536 : this.maxTunnelBytes, - isStreamActive: () => this.streams.get(sid) === state, - send: (response) => this.sendMux(sid, response), - authorizationOverride: authorization, - relaySurface: state.pluginGrant ? undefined : 'web-machine', - blockedResponseValues: [authorization.slice(7), this.localOperatorToken()], - fetchImpl: this.config.fetchImpl, - }); - return; - } - - if (state.pluginGrant) return; - - if (state.bridge?.readyState === WebSocket.OPEN) { - try { - state.bridge.send(plaintext); - } catch { - // The bridge close handler owns cleanup. - } + // Only HTTP reads of the notice pages and their static files are replayed. + // Realtime frames are dropped: no local operator socket is opened for a + // relayed stream. + if (message.t !== 'http-req') return; + if (!webMachineRouteAllowed(message.method, message.path)) { + this.sendMux(sid, { t: 'http-res', rid: message.rid, status: 403, error: 'web_machine_route_forbidden', bodyB64: '', last: true }); return; } - if (state.pendingFrames.length >= 128 || state.pendingBytes + plaintext.length > 1024 * 1024) { - this.closeStream(sid, 1009, 'websocket_backlog_exceeded'); - return; - } - state.pendingFrames.push(plaintext); - state.pendingBytes += plaintext.length; + const operatorToken = this.localOperatorToken(); + void replayRelayHttpRequest({ + sid, + request: withoutAuthorization(message as HttpReqFrame), + apiBase: this.config.apiBase ?? localApiBase(), + requestRegistry: this.httpRequests, + timeoutMs: this.httpRequestTimeoutMs, + maxTunnelBytes: this.maxTunnelBytes, + isStreamActive: () => this.streams.get(sid) === state, + send: (response) => this.sendMux(sid, response), + relaySurface: O8_WEB_MACHINE_SURFACE, + blockedResponseValues: operatorToken ? [operatorToken] : [], + fetchImpl: this.config.fetchImpl, + }); } private sendMux(sid: string, frame: Record): void { @@ -420,114 +401,26 @@ export class MachineRelayConnector { } } - private openStream(sid: string, pluginGrant?: PluginRelayGrant): void { - const existing = this.streams.get(sid); - if (existing) { - if (existing.bridge?.readyState === WebSocket.OPEN) { - this.sendControl({ t: 'mux-ready', sid }); - } - return; - } - - const state: MachineStreamState = { - sid, - bridge: null, - pendingFrames: [], - pendingBytes: 0, - closing: false, - pluginGrant, - }; - if (pluginGrant) { - this.streams.set(sid, state); - this.sendControl({ t: 'mux-ready', sid }); - return; - } - this.streams.set(sid, state); - - let bridge: WebSocket; - try { - bridge = new WebSocket(this.localWebSocketUrl()); - } catch (error) { - console.warn(`${P} local websocket dial failed sid=${shortId(sid)}: ${errorMessage(error)}`); - this.closeStream(sid, 1011, 'local_websocket_unavailable'); - return; - } - state.bridge = bridge; - bridge.on('open', () => { - if (this.streams.get(sid) !== state || state.closing) { - closeSocket(bridge, 'stale web-machine stream'); - return; - } - this.sendControl({ t: 'mux-ready', sid }); - for (const frame of state.pendingFrames.splice(0)) { - try { - bridge.send(frame); - } catch { - break; - } - } - state.pendingBytes = 0; - }); - bridge.on('message', (raw) => { - if (this.streams.get(sid) !== state || state.closing) return; - const plaintext = typeof raw === 'string' - ? raw - : (raw as Buffer).toString('utf8'); - const operatorToken = this.localOperatorToken(); - if (operatorToken && plaintext.includes(operatorToken)) { - console.warn( - `${P} blocked local credential on realtime stream sid=${shortId(sid)}`, - ); - this.closeStream(sid, 4403, 'local_credential_exposure_blocked'); - return; - } - this.sendMuxPayload(sid, plaintext); - }); - bridge.on('close', (code, rawReason) => { - if (state.closing || this.streams.get(sid) !== state) return; - this.closeStream( - sid, - code === 1000 || code === 1001 ? code : 1011, - rawReason.toString('utf8') || 'local_websocket_closed', - ); - }); - bridge.on('error', (error) => { - console.warn(`${P} local websocket error sid=${shortId(sid)}: ${errorMessage(error)}`); - }); - } - - private localWebSocketUrl(): string { - const base = this.config.localWebSocketUrl ?? localWsBase(); - const url = new URL(base); - url.searchParams.set('token', this.localOperatorToken()); - return url.toString(); + private openStream(sid: string): void { + if (!this.streams.has(sid)) this.streams.set(sid, { sid, closing: false }); + this.sendControl({ t: 'mux-ready', sid }); } private localOperatorToken(): string { return (this.config.operatorToken ?? getOrCreateWsToken)().trim(); } - private closeStream(sid: string, code: number, reason: string): void { - if (!this.streams.has(sid)) return; - this.sendControl({ t: 'mux-close', sid, code, reason }); - this.teardownStream(sid); - } - private teardownStream(sid: string): void { const state = this.streams.get(sid); if (!state) return; state.closing = true; this.httpRequests.abortStream(sid); this.streams.delete(sid); - closeSocket(state.bridge, 'web-machine stream closed'); } private teardownStreams(reason: 'connector-stop' | 'stream-teardown'): void { this.httpRequests.abortAll(reason); - for (const state of this.streams.values()) { - state.closing = true; - closeSocket(state.bridge, 'web-machine streams closed'); - } + for (const state of this.streams.values()) state.closing = true; this.streams.clear(); } @@ -624,9 +517,15 @@ function localApiBase(): string { return `http://127.0.0.1:${apiPort}`; } -function localWsBase(): string { - const { wsPort } = resolvePortInfo(); - return `ws://127.0.0.1:${wsPort}/ws`; +/** The relay's frame never chooses the local credential: replays carry none. */ +function withoutAuthorization(request: HttpReqFrame): HttpReqFrame { + const headers: Record = {}; + if (request.headers && typeof request.headers === 'object') { + for (const [name, value] of Object.entries(request.headers as Record)) { + if (name.toLowerCase() !== 'authorization') headers[name] = value; + } + } + return { ...request, authorization: undefined, headers }; } function nonNegativeInteger(value: number | undefined, fallback: number): number { diff --git a/src/lib/connect/machine-full-surface.test.ts b/src/lib/connect/machine-full-surface.test.ts index bb2440d7d8..f622b34c16 100644 --- a/src/lib/connect/machine-full-surface.test.ts +++ b/src/lib/connect/machine-full-surface.test.ts @@ -340,7 +340,6 @@ describe('web-machine full-surface real path', () => { machineId: MACHINE_ID, relayUrl: relayServer.url.replace(/^http/, 'ws'), apiBase: local.url, - localWebSocketUrl: local.wsUrl, operatorToken: () => LOCAL_OPERATOR_TOKEN, ticketProvider: async () => fixtureTicket(), reconnectBaseMs: 20, @@ -412,21 +411,24 @@ describe('web-machine full-surface real path', () => { expect(range.headers.get('content-range')).toMatch(/^bytes 0-1023\//); expect((await range.arrayBuffer()).byteLength).toBe(1024); + // API routes are outside the web-machine allowlist and never reach the Mac. const credentialExport = await surfaceApp.request( `/web/${MACHINE_ID}/surface/api/panel/ws-info`, { headers: { cookie } }, ); - expect(credentialExport.status).toBe(502); + expect(credentialExport.status).toBe(403); expect( Buffer.from(await credentialExport.arrayBuffer()) .includes(Buffer.from(LOCAL_OPERATOR_TOKEN)), ).toBe(false); + expect(local.requests.map((request) => request.path)).not.toContain('/api/panel/ws-info'); + // The browser socket attaches, but no local realtime socket is opened. const browser = await openBrowserSurfaceClient(relayServer.url, cookie); - await waitFor(() => local.socketPaths.length >= 5); browser.socket.send(JSON.stringify({ type: 'ping', source: 'browser-bridge' })); - await waitFor(() => records(browser.messages).some((frame) => frame.channel === 'pong')); - expect(browser.messages.join('')).not.toContain(LOCAL_OPERATOR_TOKEN); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(records(browser.messages).some((frame) => frame.channel === 'pong')).toBe(false); + expect(local.socketPaths).toEqual([]); connector.stop('fixture-machine-drop'); expect(await browser.closed).toEqual({ @@ -443,7 +445,6 @@ describe('web-machine full-surface real path', () => { machineId: MACHINE_ID, relayUrl: relayServer.url.replace(/^http/, 'ws'), apiBase: local.url, - localWebSocketUrl: local.wsUrl, operatorToken: () => LOCAL_OPERATOR_TOKEN, ticketProvider: async () => fixtureTicket(), reconnectBaseMs: 20, @@ -454,7 +455,6 @@ describe('web-machine full-surface real path', () => { await waitFor(() => relay.stats().machines === 1); const web = await openWebClient(relayServer.url); - await waitFor(() => local.socketPaths.length === 1); const page = await requestThroughWeb(web, '/mobile', 'page'); const asset = await requestThroughWeb( @@ -468,7 +468,6 @@ describe('web-machine full-surface real path', () => { 'credential-export', ); sendWeb(web, { type: 'ping', source: 'browser' }); - await waitFor(() => records(web.messages).some((frame) => frame.channel === 'pong')); expect(page.status).toBe(200); expect(page.headers['content-type']).toBe('text/html; charset=utf-8'); @@ -481,48 +480,26 @@ describe('web-machine full-surface real path', () => { expect(asset.body.byteLength).toBeGreaterThan(300 * 1024); expect(asset.body.includes(Buffer.from(LOCAL_OPERATOR_TOKEN))).toBe(false); expect(credentialExport).toMatchObject({ - status: 502, - error: 'local_credential_exposure_blocked', + status: 403, + error: 'web_machine_route_forbidden', body: Buffer.alloc(0), }); expect(web.sent.join('')).not.toContain(LOCAL_OPERATOR_TOKEN); expect(web.messages.join('')).not.toContain(LOCAL_OPERATOR_TOKEN); + // Pages and assets are replayed with no local credential; nothing else is. expect(local.requests).toEqual([ - { - path: '/mobile', - authorization: `Bearer ${LOCAL_OPERATOR_TOKEN}`, - webMachine: true, - }, - { - path: '/_next/static/chunks/mobile.js', - authorization: `Bearer ${LOCAL_OPERATOR_TOKEN}`, - webMachine: true, - }, - { - path: '/api/panel/ws-info', - authorization: `Bearer ${LOCAL_OPERATOR_TOKEN}`, - webMachine: true, - }, + { path: '/mobile', authorization: '', webMachine: true }, + { path: '/_next/static/chunks/mobile.js', authorization: '', webMachine: true }, ]); - expect(local.socketPaths).toEqual([`/ws?token=${LOCAL_OPERATOR_TOKEN}`]); - - sendWeb(web, { type: 'request-credential-leak' }); - const credentialLeakClose = await web.closed; - expect(credentialLeakClose).toEqual({ - code: 4403, - reason: 'local_credential_exposure_blocked', - }); - await waitFor(() => local.bridgeCloses === 1); - expect(web.messages.join('')).not.toContain(LOCAL_OPERATOR_TOKEN); + expect(records(web.messages).some((frame) => frame.channel === 'pong')).toBe(false); + expect(local.socketPaths).toEqual([]); - const secondWeb = await openWebClient(relayServer.url); - await waitFor(() => local.socketPaths.length === 2); connector.stop('fixture-machine-drop'); - const machineDrop = await secondWeb.closed; - await waitFor(() => local.bridgeCloses === 2); + const machineDrop = await web.closed; + expect(local.bridgeCloses).toBe(0); expect(machineDrop).toEqual({ code: 1012, reason: 'machine_disconnected' }); expect( - records(secondWeb.messages).some((frame) => ( + records(web.messages).some((frame) => ( frame.t === 'presence' && frame.machine === 'down' )), ).toBe(true); diff --git a/src/lib/connect/plugin-relay.ts b/src/lib/connect/plugin-relay.ts deleted file mode 100644 index 1506c7a38f..0000000000 --- a/src/lib/connect/plugin-relay.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { mintPluginToken, PLUGIN_FOLLOW_UP_SCOPE, PLUGIN_READ_SCOPE, PLUGIN_PREPARE_TASK_SCOPE, PLUGIN_LAUNCH_TASK_SCOPE } from '@/lib/auth/plugin-token'; -import type { HttpReqFrame } from '@/lib/mobile/relay-connector-protocol'; - -export interface PluginRelayGrant { - clientId: string; - scopes: string[]; - expiresAt: number; - accountId?: string; -} - -export function parsePluginRelayGrant(value: unknown): PluginRelayGrant | null { - if (!value || typeof value !== 'object' || Array.isArray(value)) return null; - const grant = value as PluginRelayGrant; - return typeof grant.clientId === 'string' && grant.clientId.length > 0 && grant.clientId.length <= 256 - && Array.isArray(grant.scopes) && grant.scopes.length <= 4 - && grant.scopes.every((scope) => scope === PLUGIN_READ_SCOPE || scope === PLUGIN_FOLLOW_UP_SCOPE || scope === PLUGIN_PREPARE_TASK_SCOPE || scope === PLUGIN_LAUNCH_TASK_SCOPE) - && (grant.accountId === undefined || (typeof grant.accountId === 'string' && /^user_[A-Za-z0-9_-]{1,240}$/.test(grant.accountId))) - && (!grant.scopes.some((scope) => scope === PLUGIN_PREPARE_TASK_SCOPE || scope === PLUGIN_LAUNCH_TASK_SCOPE) || Boolean(grant.accountId)) - && Number.isFinite(grant.expiresAt) && grant.expiresAt > Date.now() - ? grant : null; -} - -/** A plugin stream has one fixed destination and never acquires an operator bearer. */ -export function pluginReplayAuthorization( - machineId: string, - grant: PluginRelayGrant, - request: HttpReqFrame, -): string | null { - if (request.path !== '/api/plugins/mcp' || request.method !== 'POST' || grant.expiresAt <= Date.now()) return null; - try { - return `Bearer ${mintPluginToken({ machineId, clientId: grant.clientId, scopes: grant.scopes, accountId: grant.accountId }, { expiresAt: grant.expiresAt })}`; - } catch { - return null; - } -} diff --git a/src/lib/connect/web-machine-surface.ts b/src/lib/connect/web-machine-surface.ts index 5740367e17..268ec047b0 100644 --- a/src/lib/connect/web-machine-surface.ts +++ b/src/lib/connect/web-machine-surface.ts @@ -19,6 +19,24 @@ export function headersIndicateWebMachineRelay( && get(O8_RELAY_SURFACE_HEADER) === O8_WEB_MACHINE_SURFACE; } +/** + * The only requests a relayed web-machine stream may replay: reads of the + * desktop-app notice pages and the static files they load. The browser console + * is gone, so no API route, write or realtime traffic is reachable this way. + */ +const WEB_MACHINE_PAGES = new Set(['/', '/mobile', '/dashboard', '/icon.png', '/favicon.ico']); + +export function webMachineRouteAllowed(method: unknown, path: unknown): boolean { + // Same default as the replay itself: a frame without a method is a GET. + const verb = typeof method === 'string' ? method.toUpperCase() : method === undefined ? 'GET' : ''; + if (verb !== 'GET' && verb !== 'HEAD') return false; + if (typeof path !== 'string' || !path.startsWith('/') || path.startsWith('//')) return false; + if (path.includes('\\') || path.includes('..') || /%2e|%2f|%5c/i.test(path)) return false; + const pathname = path.split(/[?#]/, 1)[0]!; + const page = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname; + return WEB_MACHINE_PAGES.has(page) || pathname.startsWith('/_next/static/'); +} + export interface WebMachineBrowserTransport { fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise; openWebSocket: (path: '/ws') => WebSocket; diff --git a/src/lib/mobile/relay-http-replay.ts b/src/lib/mobile/relay-http-replay.ts index 52504ee052..6a4a01281b 100644 --- a/src/lib/mobile/relay-http-replay.ts +++ b/src/lib/mobile/relay-http-replay.ts @@ -19,12 +19,6 @@ export interface RelayHttpReplayOptions { maxTunnelBytes: number; isStreamActive: () => boolean; send: (frame: Record) => void; - /** - * Machine web sessions are authenticated by the relay ticket and ownership - * check, then replayed locally as the desktop operator. Supplying this value - * replaces any authorization sent by the remote web client. - */ - authorizationOverride?: string; relaySurface?: typeof O8_WEB_MACHINE_SURFACE; blockedResponseValues?: readonly string[]; fetchImpl?: typeof fetch; @@ -47,10 +41,6 @@ export async function replayRelayHttpRequest(options: RelayHttpReplayOptions): P options.send({ t: 'http-res', rid, status: plan.status, error: plan.error, bodyB64: '' }); return; } - if (options.authorizationOverride) { - plan.headers.authorization = options.authorizationOverride; - } - const controller = options.requestRegistry.begin(options.sid, rid); const timeout = setTimeout(() => { options.requestRegistry.timeout(options.sid, rid, controller); diff --git a/tests/plugin-front-door-real-path.test.ts b/tests/plugin-front-door-real-path.test.ts index f35bd17467..10c5ea29f6 100644 --- a/tests/plugin-front-door-real-path.test.ts +++ b/tests/plugin-front-door-real-path.test.ts @@ -2,7 +2,6 @@ import { createServer, type Server } from 'node:http'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { handleNativeHttp } from '@/lib/ws-server/native-http-routes'; import { forwardToNext, registeredFrontDoorRoute } from '@/lib/ws-server/api-front-door'; -import { pluginReplayAuthorization, type PluginRelayGrant } from '@/lib/connect/plugin-relay'; import { replayRelayHttpRequest } from '@/lib/mobile/relay-http-replay'; import { RelayHttpRequestRegistry, type HttpReqFrame } from '@/lib/mobile/relay-connector-protocol'; import { mintPluginToken } from '@/lib/auth/plugin-token'; @@ -22,18 +21,19 @@ let server: Server; let origin: string; let received: Array<{ principal: ReturnType; marker: string | undefined }>; const selected = { machineId: 'machine-plugin', missionId: 'mission-plugin', packetId: 'packet-plugin' }; -const grant = (scopes = ['o8:read']): PluginRelayGrant => ({ clientId: 'client-plugin', scopes, expiresAt: Date.now() + 60_000 }); +type PluginGrant = { clientId: string; scopes: string[]; expiresAt: number }; +const grant = (scopes = ['o8:read']): PluginGrant => ({ clientId: 'client-plugin', scopes, expiresAt: Date.now() + 60_000 }); function frame(name = 'o8_attention', args: Record = { machineId: selected.machineId }): HttpReqFrame { return { rid: 'fixture-call', path: '/api/plugins/mcp', method: 'POST', headers: { 'content-type': 'application/json' }, authorization: 'Bearer remote-caller-must-not-win', bodyB64: Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } })).toString('base64') }; } async function relay(request = frame(), permission = grant()) { - const authorization = pluginReplayAuthorization(selected.machineId, permission, request); - if (!authorization) throw new Error('Fixture grant refused before replay'); + // A local plugin capability, as the Mac mints it for a verified grant. + const authorization = `Bearer ${mintPluginToken({ machineId: selected.machineId, clientId: permission.clientId, scopes: permission.scopes }, { expiresAt: permission.expiresAt })}`; const replies: Record[] = []; - await replayRelayHttpRequest({ sid: 'plugin-stream', request, apiBase: origin, - authorizationOverride: authorization, requestRegistry: new RelayHttpRequestRegistry(), + await replayRelayHttpRequest({ sid: 'plugin-stream', request: { ...request, authorization }, apiBase: origin, + requestRegistry: new RelayHttpRequestRegistry(), timeoutMs: 5000, maxTunnelBytes: 1024 * 1024, isStreamActive: () => true, send: reply => { replies.push(reply); } }); return { status: replies[0].status, body: JSON.parse(Buffer.from(String(replies[0].bodyB64), 'base64').toString()) }; @@ -87,8 +87,6 @@ it('refuses the wrong scope, wrong machine and expired grants without worker del const follow = frame('o8_follow_up', { ...selected, message: 'Fixture follow-up', idempotencyKey: 'refused' }); expect((await relay(follow)).status).toBe(403); expect((await relay(frame('o8_attention', { machineId: 'other-machine' }))).status).toBe(403); - expect(pluginReplayAuthorization(selected.machineId, { ...grant(), expiresAt: Date.now() - 1 }, frame())).toBeNull(); - expect(pluginReplayAuthorization(selected.machineId, grant(), { ...frame(), path: '/api/panel/approvals' })).toBeNull(); const expired = mintPluginToken({ ...selected, clientId: 'client-plugin', scopes: ['o8:read'] }, { now: Date.now() - 120_000 }); const response = await fetch(origin + '/api/plugins/mcp', { method: 'POST', headers: { authorization: `Bearer ${expired}`, 'content-type': 'application/json' }, body: '{}' }); expect(response.status).toBe(401); diff --git a/tests/plugin-relay-real-path.test.ts b/tests/plugin-relay-real-path.test.ts index b0980eccbc..f17d6b3a7f 100644 --- a/tests/plugin-relay-real-path.test.ts +++ b/tests/plugin-relay-real-path.test.ts @@ -1,60 +1,29 @@ import { createServer } from 'node:http'; -import { generateKeyPairSync, sign } from 'node:crypto'; -import { rmSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { NextRequest } from 'next/server'; -import { describe, expect, it, vi } from 'vitest'; +import { describe, expect, it } from 'vitest'; import { WebSocket, WebSocketServer } from 'ws'; -const steer = vi.hoisted(() => vi.fn(async () => ({ packetId: 'packet-relay', laneId: 'lane-relay', note: 'accepted' }))); -vi.mock('@/lib/orchestrator/operator-mission-service', () => ({ steerPacket: steer })); - -import { POST } from '@/app/api/plugins/mcp/route'; -import { resolveRequestPrincipal, resolveRequestPrincipalContext } from '@/lib/auth/principal'; import { MachineRelayConnector } from '@/lib/connect/machine-attach'; -import { getDataDir } from '@/lib/data-dir-migration'; -import { bumpSignInEpoch, readSignInEpoch, writeActiveIdentity } from '@/lib/github-broker/managed'; -import { allowAccountRefresh, publishReadyAccountState, withAccountStateLease } from '@/lib/auth/account-state'; -import { readPluginAudit } from '@/lib/mcp/plugin-audit'; -import { panelGateMiddleware } from '@/middleware'; -describe('machine connector plugin stream through the gated HTTP entry point', () => { - it('uses a plugin credential, rejects operator destinations, and never opens an operator realtime bridge', async () => { - const principals: string[] = []; - const contexts: Array> = []; - const originalPublicKey = process.env.O8_LICENSE_PUBKEY; +// A relay-supplied plugin grant is plain claims the Mac cannot verify, so the +// connector refuses the stream before any local request or credential. +describe('machine connector plugin stream', () => { + it('refuses a plugin stream with an unverifiable grant and replays nothing for it', async () => { let httpRequests = 0; - const http = createServer(async (incoming, outgoing) => { - const body: Buffer[] = []; - for await (const chunk of incoming) body.push(Buffer.from(chunk)); - const request = new NextRequest(`http://localhost${incoming.url}`, { - method: incoming.method, - headers: new Headers(Object.entries(incoming.headers).flatMap(([key, value]) => - value === undefined ? [] : [[key, Array.isArray(value) ? value.join(',') : value] as [string, string]])), - body: Buffer.concat(body), - }); - httpRequests++; - principals.push(resolveRequestPrincipal(request)); - contexts.push(resolveRequestPrincipalContext(request)); - const gate = panelGateMiddleware(request); - const response = gate.status === 200 ? await POST(request) : gate; - outgoing.writeHead(response.status, { 'content-type': 'application/json' }); - outgoing.end(await response.text()); - }); + const http = createServer((_incoming, outgoing) => { httpRequests++; outgoing.end('{}'); }); await new Promise((resolve) => http.listen(0, '127.0.0.1', resolve)); const address = http.address(); if (!address || typeof address === 'string') throw new Error('HTTP fixture failed'); const relay = new WebSocketServer({ host: '127.0.0.1', port: 0 }); - const realtime = new WebSocketServer({ host: '127.0.0.1', port: 0 }); - await Promise.all([relay, realtime].map((server) => new Promise((resolve) => server.once('listening', resolve)))); + await new Promise((resolve) => relay.once('listening', resolve)); const relayAddress = relay.address(); - const realtimeAddress = realtime.address(); - if (!relayAddress || typeof relayAddress === 'string' || !realtimeAddress || typeof realtimeAddress === 'string') throw new Error('WebSocket fixture failed'); - let realtimeConnections = 0; - realtime.on('connection', () => { realtimeConnections++; }); + if (!relayAddress || typeof relayAddress === 'string') throw new Error('WebSocket fixture failed'); + const frames: Array> = []; let peer: WebSocket | undefined; - let capability: string | undefined; - const receipts = new Map>(); + relay.on('connection', (socket) => { + peer = socket; + socket.on('message', (raw) => frames.push(JSON.parse(raw.toString()))); + socket.send(JSON.stringify({ t: 'mux-open', sid: 'plugin-stream', surface: 'plugin', grant: { clientId: 'client-relay', scopes: ['o8:read'], expiresAt: Date.now() + 60_000 } })); + }); const waitFor = async (test: () => boolean) => { const end = Date.now() + 5000; while (!test()) { @@ -62,118 +31,31 @@ describe('machine connector plugin stream through the gated HTTP entry point', ( await new Promise((resolve) => setTimeout(resolve, 10)); } }; - relay.on('connection', (socket, request) => { - peer = socket; - capability = request.headers['x-o8-plugin-protocol'] as string | undefined; - socket.send(JSON.stringify({ t: 'mux-open', sid: 'plugin-stream', surface: 'plugin', grant: { clientId: 'client-relay', scopes: ['o8:read'], expiresAt: Date.now() + 60_000 } })); - socket.on('message', (raw) => { - const frame = JSON.parse(raw.toString()); - if (frame.t === 'mux') { - const receipt = JSON.parse(Buffer.from(frame.payload, 'base64').toString('utf8')); - receipts.set(receipt.rid, receipt); - } - }); - }); const connector = new MachineRelayConnector({ machineId: 'machine-relay', relayUrl: `ws://127.0.0.1:${relayAddress.port}`, - apiBase: `http://127.0.0.1:${address.port}`, localWebSocketUrl: `ws://127.0.0.1:${realtimeAddress.port}/ws`, + apiBase: `http://127.0.0.1:${address.port}`, operatorToken: () => 'fixture-operator-secret', ticketProvider: async () => ({ ticket: 'fixture-machine-ticket', expiresAt: new Date(Date.now() + 600_000).toISOString() }), }); - const send = (rid: string, path: string, sid = 'plugin-stream', name = 'o8_attention', extra = {}) => peer!.send(JSON.stringify({ t: 'mux', sid, seq: 0, - payload: Buffer.from(JSON.stringify({ t: 'http-req', rid, path, method: 'POST', headers: { 'content-type': 'application/json' }, - bodyB64: Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: { machineId: 'machine-relay', ...extra } } })).toString('base64'), - authorization: 'Bearer fixture-operator-secret', - })).toString('base64'), - })); try { connector.start(); - await waitFor(() => Boolean(peer)); - send('status-call', '/api/plugins/mcp'); - await waitFor(() => receipts.has('status-call')); - expect(capability).toBe('1'); - expect(principals).toEqual(['plugin']); - expect(receipts.get('status-call')?.status).toBe(200); - expect(JSON.stringify(receipts.get('status-call'))).not.toContain('fixture-operator-secret'); - send('forbidden-call', '/api/panel/approvals'); - await waitFor(() => receipts.has('forbidden-call')); - expect(receipts.get('forbidden-call')?.status).toBe(403); - expect(httpRequests).toBe(1); - expect(realtimeConnections).toBe(0); - expect(readPluginAudit().at(-1)).toMatchObject({ actor: 'plugin', surface: 'chatgpt', clientId: 'client-relay' }); - // New account-bound preparation grant traverses the actual WebSocket - // connector and HTTP gate, without ever receiving an operator bearer. - const keys = generateKeyPairSync('ed25519'); - process.env.O8_LICENSE_PUBKEY = keys.publicKey.export({ type: 'spki', format: 'pem' }).toString(); - const accountId = 'user_relay_draft_fixture'; - const header = Buffer.from(JSON.stringify({ alg: 'EdDSA' })).toString('base64url'); - const payload = Buffer.from(JSON.stringify({ sub: accountId, plan: 'free', exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url'); - const unsigned = `${header}.${payload}`; - const licenseKey = `${unsigned}.${sign(null, Buffer.from(unsigned), keys.privateKey).toString('base64url')}`; - await withAccountStateLease(() => { - writeActiveIdentity(accountId); - bumpSignInEpoch(); - writeFileSync(join(getDataDir(), 'entitlement.json'), JSON.stringify({ plan: 'free', licenseKey })); - rmSync(join(getDataDir(), 'auth-signed-out-at'), { force: true }); - allowAccountRefresh(); - publishReadyAccountState(accountId, readSignInEpoch()!, licenseKey); - }); - const expiry = Date.now() + 4000; - const open = (sid: string, subject?: string, scopes = ['o8:prepare-task']) => peer!.send(JSON.stringify({ - t: 'mux-open', sid, surface: 'plugin', grant: { - accountId: subject, clientId: 'client-relay', scopes, expiresAt: expiry, - }, - })); - send('old-grant-draft', '/api/plugins/mcp', 'plugin-stream', 'o8_task_options'); - await waitFor(() => receipts.has('old-grant-draft')); - expect(receipts.get('old-grant-draft')?.status).toBe(403); - open('draft-valid', accountId); - send('draft-options', '/api/plugins/mcp', 'draft-valid', 'o8_task_options'); - await waitFor(() => receipts.has('draft-options')); - expect(receipts.get('draft-options')?.status).toBe(200); - expect(contexts.at(-1)).toMatchObject({ role: 'plugin', accountId, scopes: ['o8:prepare-task'], expiresAt: expiry }); - const taskId = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'; - open('result-read', accountId, ['o8:read']); - send('bound-result', '/api/plugins/mcp', 'result-read', 'o8_task_result', { taskId }); - await waitFor(() => receipts.has('bound-result')); - expect(receipts.get('bound-result')?.status).toBe(404); // Authenticated, but no such own task. - expect(contexts.at(-1)).toMatchObject({ role: 'plugin', accountId, scopes: ['o8:read'], expiresAt: expiry }); - send('result-no-account', '/api/plugins/mcp', 'plugin-stream', 'o8_task_result', { taskId }); - await waitFor(() => receipts.has('result-no-account')); - expect(receipts.get('result-no-account')?.status).toBe(403); - open('result-foreign', 'user_foreign_relay_fixture', ['o8:read']); - send('result-other-account', '/api/plugins/mcp', 'result-foreign', 'o8_task_result', { taskId }); - await waitFor(() => receipts.has('result-other-account')); - expect(receipts.get('result-other-account')?.status).toBe(403); - open('draft-foreign', 'user_foreign_relay_fixture'); - send('foreign-options', '/api/plugins/mcp', 'draft-foreign', 'o8_task_options'); - await waitFor(() => receipts.has('foreign-options')); - expect(receipts.get('foreign-options')?.status).toBe(403); - const beforeInvalid = httpRequests; - open('draft-missing-account'); - send('missing-options', '/api/plugins/mcp', 'draft-missing-account', 'o8_task_options'); - // An ordered request on a known stream proves the invalid open was - // processed. It cannot create a stream or reach the local HTTP server. - send('invalid-open-barrier', '/api/plugins/mcp'); - await waitFor(() => receipts.has('invalid-open-barrier')); - expect(httpRequests).toBe(beforeInvalid + 1); - expect(receipts.has('missing-options')).toBe(false); - await waitFor(() => Date.now() > expiry); - const beforeExpired = httpRequests; - send('expired-options', '/api/plugins/mcp', 'draft-valid', 'o8_task_options'); - await waitFor(() => receipts.has('expired-options')); - expect(receipts.get('expired-options')?.status).toBe(403); - expect(httpRequests).toBe(beforeExpired); - expect(realtimeConnections).toBe(0); - expect(steer).not.toHaveBeenCalled(); + await waitFor(() => frames.some((frame) => frame.t === 'mux-close')); + expect(frames.find((frame) => frame.t === 'mux-close')).toEqual({ t: 'mux-close', sid: 'plugin-stream', code: 4403, reason: 'plugin_grant_unverifiable' }); + expect(frames.some((frame) => frame.t === 'mux-ready')).toBe(false); + + // A request on the refused stream reaches nothing; an ordinary stream opened + // after it proves the connector processed the request first. + peer!.send(JSON.stringify({ t: 'mux', sid: 'plugin-stream', seq: 0, payload: Buffer.from(JSON.stringify({ + t: 'http-req', rid: 'plugin-call', method: 'POST', path: '/api/plugins/mcp', headers: { 'content-type': 'application/json' }, bodyB64: '', + })).toString('base64') })); + peer!.send(JSON.stringify({ t: 'mux-open', sid: 'barrier' })); + await waitFor(() => frames.some((frame) => frame.t === 'mux-ready' && frame.sid === 'barrier')); + expect(httpRequests).toBe(0); + expect(frames.some((frame) => frame.t === 'mux' && frame.sid === 'plugin-stream')).toBe(false); } finally { - if (originalPublicKey === undefined) delete process.env.O8_LICENSE_PUBKEY; - else process.env.O8_LICENSE_PUBKEY = originalPublicKey; connector.stop('test-complete'); - for (const server of [relay, realtime]) { - for (const socket of server.clients) socket.terminate(); - await new Promise((resolve) => server.close(() => resolve())); - } + for (const socket of relay.clients) socket.terminate(); + await new Promise((resolve) => relay.close(() => resolve())); await new Promise((resolve) => http.close(() => resolve())); } }); diff --git a/tests/plugin-task-draft-real-path.test.ts b/tests/plugin-task-draft-real-path.test.ts index 6c6d494e09..d2bdaca0fe 100644 --- a/tests/plugin-task-draft-real-path.test.ts +++ b/tests/plugin-task-draft-real-path.test.ts @@ -16,7 +16,6 @@ vi.mock('@/lib/runtime/actions', () => ({ launchRuntimeSurface: launches })); import { POST } from '@/app/api/plugins/mcp/route'; import { GET as inspectDrafts } from '@/app/api/plugins/task-drafts/route'; import { mintPluginToken, PLUGIN_PREPARE_TASK_SCOPE, resolvePluginToken } from '@/lib/auth/plugin-token'; -import { parsePluginRelayGrant, pluginReplayAuthorization } from '@/lib/connect/plugin-relay'; import { publishReadyAccountState, withAccountStateLease } from '@/lib/auth/account-state'; import { getDataDir } from '@/lib/data-dir-migration'; import { bumpSignInEpoch, readSignInEpoch, writeActiveIdentity } from '@/lib/github-broker/managed'; @@ -475,12 +474,10 @@ describe('plugin task drafts through the actual authenticated route and persiste expect(launches).not.toHaveBeenCalled(); }); - it('requires relay account binding for draft grants and caps local credentials to OAuth expiry', () => { - expect(parsePluginRelayGrant({ clientId: 'draft-client', scopes: [PLUGIN_PREPARE_TASK_SCOPE], expiresAt: Date.now() + 60000 })).toBeNull(); + it('requires account binding for draft credentials and caps local credentials to the grant expiry', () => { const expiry = Date.now() + 1000; - const grant = parsePluginRelayGrant({ accountId, clientId: 'draft-client', scopes: [PLUGIN_PREPARE_TASK_SCOPE], expiresAt: expiry })!; - const auth = pluginReplayAuthorization('draft-machine', grant, { rid: 'test', path: '/api/plugins/mcp', method: 'POST' }); - expect(resolvePluginToken(auth!.slice(7))).toMatchObject({ accountId, expiresAt: expiry }); + const auth = mintPluginToken({ machineId: 'draft-machine', accountId, clientId: 'draft-client', scopes: [PLUGIN_PREPARE_TASK_SCOPE] }, { expiresAt: expiry }); + expect(resolvePluginToken(auth)).toMatchObject({ accountId, expiresAt: expiry }); expect(() => mintPluginToken({ machineId: 'm', clientId: 'c', scopes: [PLUGIN_PREPARE_TASK_SCOPE] })).toThrow(); }); });