diff --git a/src/lib/mobile/lan-encrypted-http.test.ts b/src/lib/mobile/lan-encrypted-http.test.ts new file mode 100644 index 0000000000..9e60061859 --- /dev/null +++ b/src/lib/mobile/lan-encrypted-http.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { createLanEncryptedHttp } from './lan-encrypted-http'; + +function harness(client: { id: string; authKind: 'operator' | 'device'; deviceId?: string; e2ee?: { state: string } }) { + const sent: Array> = []; + const fetchImpl = vi.fn(async () => new Response('{}', { status: 200 })); + const http = createLanEncryptedHttp({ + apiBase: () => 'http://127.0.0.1:1', + send: (_c, frame) => { sent.push(frame as Record); }, + isOpen: () => true, + deviceIdForToken: (token) => (token === 'tok-a' ? 'dev-a' : null), + fetchImpl, + }); + return { http, sent, fetchImpl, client }; +} + +const request = { t: 'http-req', rid: 'r1', method: 'GET', path: '/api/mobile/inbox', headers: { authorization: 'Bearer tok-a' } }; + +describe('HTTP over a phone\'s local-network socket', () => { + it('refuses a socket that is not an encrypted device socket, without reaching the API', () => { + for (const client of [ + { id: 'c1', authKind: 'operator' as const, e2ee: { state: 'encrypted' } }, + { id: 'c2', authKind: 'device' as const, deviceId: 'dev-a', e2ee: { state: 'awaiting-init' } }, + { id: 'c3', authKind: 'device' as const, deviceId: 'dev-a' }, + ]) { + const { http, sent, fetchImpl } = harness(client); + expect(http.handle(client as never, request)).toBe(true); + expect(sent).toEqual([expect.objectContaining({ t: 'http-res', rid: 'r1', status: 403, error: 'encrypted_device_socket_required' })]); + expect(fetchImpl).not.toHaveBeenCalled(); + } + }); + + it('leaves other messages to the caller', () => { + const { http } = harness({ id: 'c1', authKind: 'device', deviceId: 'dev-a', e2ee: { state: 'encrypted' } }); + expect(http.handle({ id: 'c1' } as never, { type: 'subscribe' })).toBe(false); + }); +}); diff --git a/src/lib/mobile/lan-encrypted-http.ts b/src/lib/mobile/lan-encrypted-http.ts new file mode 100644 index 0000000000..e4b284002a --- /dev/null +++ b/src/lib/mobile/lan-encrypted-http.ts @@ -0,0 +1,92 @@ +import 'server-only'; + +import { + DEFAULT_MAX_TUNNEL_BYTES, + httpCancelRequestId, + RelayHttpRequestRegistry, + type HttpReqFrame, +} from './relay-connector-protocol'; +import { replayRelayHttpRequest } from './relay-http-replay'; + +/** Must beat the phone's 60 s tunnel deadline, as on the relay. */ +const LAN_HTTP_TIMEOUT_MS = 55_000; + +export interface LanHttpClient { + id: string; + authKind: 'operator' | 'device'; + deviceId?: string | null; + e2ee?: { state: 'awaiting-init' | 'encrypted' }; +} + +export interface LanEncryptedHttpDeps { + apiBase: () => string; + /** Sends a frame on the client's socket; the socket encrypts it. */ + send: (client: C, frame: Record) => void; + isOpen: (client: C) => boolean; + /** The active device a bearer belongs to, if any. */ + deviceIdForToken: (token: string) => string | null; + fetchImpl?: typeof fetch; +} + +function bearer(frame: HttpReqFrame): string | null { + const raw = typeof frame.authorization === 'string' ? frame.authorization + : frame.headers && typeof frame.headers === 'object' + ? (frame.headers as Record).authorization ?? (frame.headers as Record).Authorization + : null; + return typeof raw === 'string' && raw.startsWith('Bearer ') ? raw.slice(7).trim() : null; +} + +/** + * HTTP for a phone on the same network, carried over its end-to-end encrypted + * socket as the relay carries it, so its bearer never crosses the network in + * cleartext. Only an enrolled device's encrypted socket may use it, and only + * with that same device's bearer. Each request is replayed into the local + * gated API exactly as a relayed one. + */ +export function createLanEncryptedHttp(deps: LanEncryptedHttpDeps) { + const requests = new RelayHttpRequestRegistry(); + + function refuse(client: C, rid: unknown, error: string): void { + if (typeof rid === 'string' && rid) deps.send(client, { t: 'http-res', rid, status: 403, error, bodyB64: '', last: true }); + } + + return { + /** Handles an `http-req` or `http-cancel` frame; returns false for anything else. */ + handle(client: C, msg: Record): boolean { + if (msg.t === 'http-cancel') { + const rid = httpCancelRequestId(msg); + if (rid) requests.cancel(client.id, rid); + return true; + } + if (msg.t !== 'http-req') return false; + const frame = msg as HttpReqFrame; + if (client.authKind !== 'device' || !client.deviceId || client.e2ee?.state !== 'encrypted') { + refuse(client, frame.rid, 'encrypted_device_socket_required'); + return true; + } + const token = bearer(frame); + if (!token || deps.deviceIdForToken(token) !== client.deviceId) { + refuse(client, frame.rid, 'device_mismatch'); + return true; + } + void replayRelayHttpRequest({ + sid: client.id, + request: frame, + apiBase: deps.apiBase(), + requestRegistry: requests, + timeoutMs: LAN_HTTP_TIMEOUT_MS, + maxTunnelBytes: DEFAULT_MAX_TUNNEL_BYTES, + isStreamActive: () => deps.isOpen(client), + send: (out) => deps.send(client, out), + fetchImpl: deps.fetchImpl, + }).catch(() => { + /* A failed replay answers through its own error frame or the phone's deadline. */ + }); + return true; + }, + /** Aborts the client's requests when its socket closes. */ + close(clientId: string): void { + requests.abortStream(clientId); + }, + }; +} diff --git a/src/ws-server.ts b/src/ws-server.ts index e6e23da8b1..4dfd1e1799 100644 --- a/src/ws-server.ts +++ b/src/ws-server.ts @@ -2,6 +2,7 @@ import { apiFrontDoorEnabled } from './lib/ws-server/api-front-door-config'; import { initiateE2eeHandshake } from './lib/ws-server/device-e2ee-handshake'; import { handleTokenProjectionRequest } from './lib/mobile/token-projection-http'; import { handleRelayConnectorSyncRequest } from './lib/mobile/relay-connector-sync'; +import { createLanEncryptedHttp } from './lib/mobile/lan-encrypted-http'; import { isPathReachable } from '@/lib/fs/protected-folders'; import { recordInboxConversationEvent } from '@/lib/inbox/store'; import { mobileModelError } from './lib/mobile/model-catalog'; @@ -2188,7 +2189,8 @@ function handleE2eeInit(client: ClientState, msg: Record): void e2ee.handshake = undefined; e2ee.state = 'encrypted'; // First encrypted frame — the client decrypting it confirms key agreement. - send(client, { channel: 'system', event: 'e2ee-ready' }); + // `http: 1` tells the phone it may send HTTP over this socket instead of cleartext. + send(client, { channel: 'system', event: 'e2ee-ready', data: { http: 1 } }); sendInitialClientState(client); console.log(`[mobile-e2ee] ${client.id} channel encrypted`); } @@ -3652,6 +3654,14 @@ function startAttachedBrowserRefreshLoop() { const clients = new Map(); +// HTTP for a phone on the network rides its encrypted socket, as on the relay. +const lanEncryptedHttp = createLanEncryptedHttp({ + apiBase: () => `http://127.0.0.1:${resolvePortInfo().apiPort}`, + send: (client, frame) => send(client, frame), + isOpen: (client) => client.ws.readyState === WebSocket.OPEN && clients.has(client.id), + deviceIdForToken: (token) => resolveDeviceByToken(token)?.id ?? null, +}); + async function handleClientMessage(client: ClientState, raw: string) { let msg: Record; try { msg = JSON.parse(raw); } catch { return; } @@ -3675,6 +3685,8 @@ async function handleClientMessage(client: ClientState, raw: string) { try { msg = JSON.parse(plaintext); } catch { return; } } + if (lanEncryptedHttp.handle(client, msg)) return; + // #5 E2EE — the client's handshake response (plaintext, signed). if (msg.type === 'e2ee-init') { handleE2eeInit(client, msg); @@ -7765,6 +7777,7 @@ wss.on('connection', (ws, req) => { // Stop backpressure flush timer stopFlushTimer(client); if (client.e2ee?.helloTimer) clearTimeout(client.e2ee.helloTimer); + lanEncryptedHttp.close(client.id); client.backpressureQueue.length = 0; // Detach from all terminal sessions for (const sessionName of client.terminalSessions) { diff --git a/tests/mobile-lan-encrypted-http-real-path.test.ts b/tests/mobile-lan-encrypted-http-real-path.test.ts new file mode 100644 index 0000000000..a076036367 --- /dev/null +++ b/tests/mobile-lan-encrypted-http-real-path.test.ts @@ -0,0 +1,179 @@ +import { execFile, execFileSync, type ChildProcess } from 'node:child_process'; +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { networkInterfaces, tmpdir } from 'node:os'; +import { join } from 'node:path'; +import nacl from 'tweetnacl'; +import { WebSocket } from 'ws'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + b64decode, + b64encode, + decryptFrame, + encryptFrame, + deriveSessionKey, + initTranscript, + isEncryptedFrame, + signDetached, +} from '@/lib/mobile/e2ee-crypto'; + +const dataDir = mkdtempSync(join(tmpdir(), 'o8-mobile-lan-http-')); +const apiRequests: Array<{ path: string; authorization?: string; clientAddr?: string }> = []; +let apiServer: import('node:http').Server; +const sockets = new Set(); +let wsProcess: ChildProcess; +let wsPort = 0; +let deviceToken = ''; +let serverOutput = ''; +const deviceIdentity = nacl.sign.keyPair(); + +function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (!address || typeof address === 'string') return reject(new Error('missing test port')); + server.close((error) => error ? reject(error) : resolve(address.port)); + }); + }); +} + +function nonLoopbackAddress(): string { + for (const entries of Object.values(networkInterfaces())) { + for (const entry of entries ?? []) { + if (!entry.internal && entry.family === 'IPv4') return entry.address; + } + } + throw new Error('A non-loopback interface is required to exercise the remote-device WebSocket gate.'); +} + +async function waitForHealth(): Promise { + const deadline = Date.now() + 30_000; + while (Date.now() < deadline) { + try { + if ((await fetch(`http://127.0.0.1:${wsPort}/health`)).ok) return; + } catch {} + await new Promise((resolve) => setTimeout(resolve, 25)); + } + throw new Error(`Timed out waiting for ws-server health. ${serverOutput.slice(-2_000)}`); +} + +beforeAll(async () => { + wsPort = await freePort(); + // The local API the replay reaches: it records what arrives. + apiServer = createServer((req, res) => { + apiRequests.push({ path: req.url ?? '', authorization: req.headers.authorization, clientAddr: req.headers['x-o8-client-addr'] as string | undefined }); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ ok: true, path: req.url })); + }); + await new Promise((resolve) => apiServer.listen(0, '127.0.0.1', resolve)); + const apiAddress = apiServer.address(); + if (!apiAddress || typeof apiAddress === 'string') throw new Error('missing api port'); + const apiPort = apiAddress.port; + const publicKey = Buffer.from(deviceIdentity.publicKey).toString('base64'); + const seedScript = [ + "const loaded = await import('./src/lib/mobile/device-registry.ts');", + "const enrollDevice = loaded.enrollDevice ?? loaded.default?.enrollDevice;", + `const result = enrollDevice({ identityPublicKey: '${publicKey}', deviceLabel: 'E2EE gate test' });`, + "console.log(`DEVICE_TOKEN:${result.deviceToken}`);", + ].join('\n'); + const seedOutput = execFileSync(process.execPath, [ + '--import=./scripts/register-server-only-stub.mjs', + '--import=tsx', + '--input-type=module', + '--eval', + seedScript, + ], { + cwd: process.cwd(), + env: { ...process.env, CORTEX_IDE_DATA_DIR: dataDir }, + encoding: 'utf8', + }); + deviceToken = seedOutput.match(/DEVICE_TOKEN:([a-f0-9]+)/)?.[1] ?? ''; + expect(deviceToken).not.toBe(''); + + wsProcess = execFile(process.execPath, [ + '--import=./scripts/register-server-only-stub.mjs', + '--import=tsx', + 'src/ws-server.ts', + ], { + cwd: process.cwd(), + env: { + ...process.env, + CORTEX_IDE_DATA_DIR: dataDir, + O8_API_PORT: String(apiPort), + O8_WS_PORT: String(wsPort), + // The remote-device gate is exercised over a network address. + O8_LAN_ACCESS: '1', + NEXT_ORIGIN: `http://127.0.0.1:${await freePort()}`, + }, + }); + wsProcess.stdout?.on('data', (chunk) => { serverOutput += String(chunk); }); + wsProcess.stderr?.on('data', (chunk) => { serverOutput += String(chunk); }); + await waitForHealth(); +}, 40_000); + +afterAll(async () => { + for (const socket of sockets) socket.close(); + if (wsProcess && wsProcess.exitCode === null) { + wsProcess.kill('SIGTERM'); + await Promise.race([once(wsProcess, 'exit'), new Promise((resolve) => setTimeout(resolve, 5_000))]); + } + await new Promise((resolve) => apiServer.close(() => resolve())); + rmSync(dataDir, { recursive: true, force: true }); +}); + + +async function encryptedSocket() { + const socket = new WebSocket(`ws://${nonLoopbackAddress()}:${wsPort}/ws?token=${encodeURIComponent(deviceToken)}`); + sockets.add(socket); + const frames: unknown[] = []; + socket.on('message', (raw) => frames.push(JSON.parse(String(raw)))); + await once(socket, 'open'); + const deadline = Date.now() + 10_000; + let hello: { serverEphPub: string; serverNonce: string } | undefined; + while (!hello && Date.now() < deadline) { + hello = (frames.find((f) => (f as { event?: string }).event === 'e2ee-hello') as { data?: typeof hello } | undefined)?.data; + if (!hello) await new Promise((resolve) => setTimeout(resolve, 10)); + } + if (!hello) throw new Error('no e2ee-hello'); + const clientEph = nacl.box.keyPair(); + const clientEphPub = b64encode(clientEph.publicKey); + const clientNonce = b64encode(nacl.randomBytes(24)); + socket.send(JSON.stringify({ + type: 'e2ee-init', clientEphPub, clientNonce, + clientSig: signDetached(initTranscript(clientEphPub, clientNonce, hello.serverEphPub, hello.serverNonce), deviceIdentity.secretKey), + })); + const sessionKey = deriveSessionKey(clientEph.secretKey, b64decode(hello.serverEphPub), hello.serverEphPub, clientEphPub); + const decrypted = () => frames.filter(isEncryptedFrame).map((f) => JSON.parse(decryptFrame(f as Parameters[0], sessionKey) ?? '{}') as Record); + const next = async (match: (frame: Record) => boolean) => { + const until = Date.now() + 10_000; + while (Date.now() < until) { + const found = decrypted().find(match); + if (found) return found; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error('frame did not arrive'); + }; + const sendEncrypted = (obj: unknown) => socket.send(JSON.stringify(encryptFrame(JSON.stringify(obj), sessionKey))); + return { socket, next, sendEncrypted }; +} + +describe('HTTP over a phone\'s encrypted socket on the network', () => { + it('advertises it, replays a request with the socket device\'s own bearer, and refuses another bearer', async () => { + const { next, sendEncrypted } = await encryptedSocket(); + expect(await next((f) => f.event === 'e2ee-ready')).toMatchObject({ data: { http: 1 } }); + + sendEncrypted({ t: 'http-req', rid: 'r1', method: 'GET', path: '/api/mobile/inbox', headers: { authorization: `Bearer ${deviceToken}` } }); + const response = await next((f) => f.t === 'http-res' && f.rid === 'r1'); + expect(response).toMatchObject({ status: 200 }); + expect(JSON.parse(Buffer.from(String(response.bodyB64), 'base64').toString())).toEqual({ ok: true, path: '/api/mobile/inbox' }); + // It reached the local API as a remote device request, never as loopback. + expect(apiRequests).toEqual([{ path: '/api/mobile/inbox', authorization: `Bearer ${deviceToken}`, clientAddr: 'o8-relay-forward' }]); + + sendEncrypted({ t: 'http-req', rid: 'r2', method: 'GET', path: '/api/panel/settings', headers: { authorization: 'Bearer someone-elses-token' } }); + expect(await next((f) => f.t === 'http-res' && f.rid === 'r2')).toMatchObject({ status: 403, error: 'device_mismatch' }); + expect(apiRequests).toHaveLength(1); + }, 30_000); +}); diff --git a/tests/test-classification.json b/tests/test-classification.json index 9f011bb6d4..9ff3fd977c 100644 --- a/tests/test-classification.json +++ b/tests/test-classification.json @@ -4792,6 +4792,15 @@ "real-path" ] }, + { + "path": "tests/mobile-lan-encrypted-http-real-path.test.ts", + "reasons": [ + "child-process", + "network-listener", + "process-signal", + "real-path" + ] + }, { "path": "tests/mobile-media-image-serving-real-path.test.ts", "reasons": [