Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 41 additions & 44 deletions docs/internals/connect-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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:

Expand All @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions docs/operations/browser-console-removal.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
123 changes: 54 additions & 69 deletions src/lib/connect/machine-attach.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> | 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<string, Record<string, unknown>>();
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<string, unknown>;
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('<html>notice</html>', {
status: 200,
headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'text/html' },
});
}) as typeof fetch;
const machineId = 'machine_01HREALPATH';
Expand All @@ -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,
Expand All @@ -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({
Expand All @@ -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');
});
Expand Down Expand Up @@ -340,69 +347,53 @@ 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,
reconnectCapMs: 40,
});

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' }));
Expand All @@ -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,
Expand All @@ -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');
});
Expand All @@ -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);
Expand All @@ -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,
Expand All @@ -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');
});
Expand Down
Loading
Loading