The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: enable cross-machine communication by adding relay support to localWsServer and implementing E2EE relay infrastructure
0xken15b77364f8a47a
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsnew file mode 100644index 000000000..ef7d738f2--- /dev/null+++ b/cli/src/authCommand.spec.ts@@ -0,0 +1,205 @@+import { spawn, spawnSync } from 'child_process'+import { createServer, type Server } from 'http'+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { fileURLToPath } from 'url'+import { afterEach, describe, expect, it } from 'vitest'++const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))+const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')+const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')+const dirs: string[] = []+const servers: Server[] = []++afterEach(async () => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ for (const server of servers.splice(0)) {+ // http.Server#close() only stops NEW connections — it waits forever for any keep-alive socket the+ // CLI's own `fetch` left open (undici pools connections for reuse) unless those are force-closed too.+ server.closeAllConnections?.()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+})++function tempRoot(): string {+ const root = mkdtempSync(join(tmpdir(), 'harness-cli-auth-'))+ dirs.push(root)+ return root+}++function seedSession(root: string): void {+ const authDir = join(root, 'auth')+ mkdirSync(authDir, { recursive: true })+ writeFileSync(join(authDir, 'session.json'), JSON.stringify({+ version: 1,+ accessToken: 'tok_seeded',+ refreshToken: 'refresh_seeded',+ expiresAt: Date.now() + 60 * 60_000, // an hour out — accessToken() must not attempt a refresh+ autonomousEnv: 'prod',+ computerId: 'a'.repeat(32),+ machineId: 'm_seeded',+ updatedAt: Date.now(),+ }))+}++function envFor(root: string, backendUrl?: string): NodeJS.ProcessEnv {+ return {+ ...process.env,+ HOME: root,+ HARNESS_AUTH_DIR: join(root, 'auth'),+ ADAPTER_DATA_DIR: join(root, 'data'),+ ADAPTER_CLI_DIR: join(root, 'cli'),+ ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),+ ADAPTER_UPDATE_DISABLE: 'true',+ ...(backendUrl ? { BACKEND_WS_URL: backendUrl } : {}),+ }+}++function runSync(root: string, args: string[], backendUrl?: string) {+ return spawnSync(process.execPath, [TSX, CLI_SOURCE, ...args], {+ cwd: CLI_ROOT,+ encoding: 'utf8',+ env: envFor(root, backendUrl),+ })+}++/** Async spawn — REQUIRED (not spawnSync) whenever the child talks back to a fake backend hosted in+ * this same test process: spawnSync blocks this process's entire event loop until the child exits,+ * so a fake server living here could never answer the child's request and the pair would deadlock. */+function runAsync(root: string, args: string[], backendUrl?: string): Promise<{ status: number | null; stdout: string; stderr: string }> {+ return new Promise((resolve) => {+ const child = spawn(process.execPath, [TSX, CLI_SOURCE, ...args], { cwd: CLI_ROOT, env: envFor(root, backendUrl) })+ let stdout = ''+ let stderr = ''+ child.stdout.on('data', (c: Buffer) => { stdout += c.toString() })+ child.stderr.on('data', (c: Buffer) => { stderr += c.toString() })+ child.once('exit', (status) => resolve({ status, stdout, stderr }))+ })+}++/** A minimal fake backend for the two `/api/auth/*` + resolve-computer calls `harness login`/+ * `auth status` make — real network shape, canned answers, so the CLI's own code runs unmodified. */+function fakeBackend(handlers: {+ authorizeNative?: (body: any) => any+ exchange?: (body: any) => any+ resolveComputer?: (body: any) => any+}): Promise<{ server: Server; base: string }> {+ return new Promise((resolve) => {+ const server = createServer((req, res) => {+ let raw = ''+ req.on('data', (c) => { raw += c })+ req.on('end', () => {+ const body = raw ? JSON.parse(raw) : {}+ const send = (data: unknown): void => {+ res.writeHead(200, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ success: true, data }))+ }+ if (req.url === '/api/auth/authorize-native' && handlers.authorizeNative) { send(handlers.authorizeNative(body)); return }+ if (req.url === '/api/auth/exchange' && handlers.exchange) { send(handlers.exchange(body)); return }+ if (req.url === '/api/machines/resolve-computer' && handlers.resolveComputer) { send(handlers.resolveComputer(body)); return }+ res.writeHead(404, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ success: false, error: { message: 'not stubbed' } }))+ })+ })+ servers.push(server)+ server.listen(0, '127.0.0.1', () => {+ const address = server.address()+ const port = typeof address === 'object' && address ? address.port : 0+ resolve({ server, base: `http://127.0.0.1:${port}` })+ })+ })+}++describe('harness auth status --json', () => {+ it('reports loggedIn:false with no saved session, and never touches the network', () => {+ const root = tempRoot()+ const result = runSync(root, ['auth', 'status', '--json'], 'http://127.0.0.1:1') // port 1: would fail fast if ever called+ expect(result.status).toBe(0)+ expect(JSON.parse(result.stdout.trim())).toEqual({ loggedIn: false })+ })++ it('falls back to human text without --json', () => {+ const root = tempRoot()+ const result = runSync(root, ['auth', 'status'])+ expect(result.status).toBe(0)+ expect(result.stdout).toContain('Not signed in')+ })++ it('reports loggedIn:true from a saved, non-expiring session without a network round trip', () => {+ const root = tempRoot()+ seedSession(root)+ const result = runSync(root, ['auth', 'status', '--json'], 'http://127.0.0.1:1')+ expect(result.status).toBe(0)+ expect(JSON.parse(result.stdout.trim())).toEqual({+ loggedIn: true,+ computerId: 'a'.repeat(32),+ machineId: 'm_seeded',+ autonomousEnv: 'prod',+ expiresAt: expect.any(Number),+ })+ })+})++describe('harness login --json', () => {+ it('already-signed-in short-circuit emits a single success result line', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await fakeBackend({+ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }),+ })+ const result = await runAsync(root, ['login', '--json'], base)+ expect(result.status).toBe(0)+ const lines = result.stdout.trim().split('\n').map((l) => JSON.parse(l))+ expect(lines).toEqual([{ type: 'result', status: 'success', alreadySignedIn: true }])+ })++ it('emits a BACKEND_ERROR result line (not a stack trace) when authorize-native is unreachable', async () => {+ const root = tempRoot()+ const result = await runAsync(root, ['login', '--json'], 'http://127.0.0.1:1')+ expect(result.status).toBe(1)+ const lines = result.stdout.trim().split('\n').filter(Boolean).map((l) => JSON.parse(l))+ expect(lines).toEqual([{ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: expect.any(String) }])+ })++ it('drives the full loopback flow: emits authorize_url, then a success result once the callback lands', async () => {+ const root = tempRoot()+ let capturedRedirectUri = ''+ const { base } = await fakeBackend({+ authorizeNative: (body) => { capturedRedirectUri = body.redirectUri; return { authorizeUrl: 'https://sso.example.test/authorize?tx=abc', tx: 'tx_abc' } },+ exchange: () => ({ token: 'tok_new', refreshToken: 'refresh_new', expiresIn: 3600, autonomousEnv: 'prod' }),+ resolveComputer: () => ({ machine: { machineId: 'm_new' } }),+ })++ const child = spawn(process.execPath, [TSX, CLI_SOURCE, 'login', '--json'], {+ cwd: CLI_ROOT,+ env: envFor(root, base),+ })+ let stdout = ''+ const lines: Record<string, unknown>[] = []+ const gotUrl = new Promise<void>((resolve) => {+ child.stdout.on('data', (chunk: Buffer) => {+ stdout += chunk.toString()+ while (stdout.includes('\n')) {+ const idx = stdout.indexOf('\n')+ const line = stdout.slice(0, idx).trim()+ stdout = stdout.slice(idx + 1)+ if (line) { lines.push(JSON.parse(line)); resolve() }+ }+ })+ })++ await gotUrl+ expect(lines[0]).toEqual({ type: 'authorize_url', url: 'https://sso.example.test/authorize?tx=abc' })+ expect(capturedRedirectUri).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/callback$/)++ // Simulate the browser completing SSO: hit this CLI's own loopback callback server.+ await fetch(`${capturedRedirectUri}?code=code_123&state=state_456`)++ const exitCode = await new Promise<number | null>((resolve) => child.once('exit', resolve))+ expect(exitCode).toBe(0)+ // Drain any trailing buffered line after exit.+ if (stdout.trim()) lines.push(JSON.parse(stdout.trim()))+ expect(lines[1]).toEqual({ type: 'result', status: 'success' })+ }, 15_000)+})diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex f79d285cc..482a58745 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -33,7 +33,7 @@ import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCuimport { PID_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'import { flashCommand } from './lib/flash.js'import { readOrMintComputerId } from './lib/computerIdentity.js'-import { AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'+import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'import { buildEngineLaunchArgv } from './lib/engineLaunch.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'@@ -60,6 +60,7 @@ import { Watcher, type LineEvent } from './watcher/watcher.js'import { chooseHookAgent, startHookServer } from './hookServer.js'import { BackendSocket } from './backendSocket.js'import { attachLocalWsServer, LOCAL_WS_PATH, LOCAL_WS_PROTOCOL_VERSION } from './localWsServer.js'+import { RemoteRelayPool } from './lib/remoteRelay.js'import { TERMINAL_BINARY_VERSION } from './lib/terminalBinary.js'import { foldTranscript, lastTurnTextFromRawLines, lineToEvents, newTurnState, type LiveEvent, type TurnState } from './lib/normalize.js'import { AnalyticsCollector } from './lib/analytics/collector.js'@@ -75,6 +76,9 @@ import {import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from './lib/voiceRouter.js'import { tailFile } from './lib/sessions.js'import { E2eeStore } from './lib/e2ee/store.js'+import { b64e, verifySetupToken } from './lib/e2ee/core.js'+import { MachinePeerStore } from './lib/e2ee/machinePeers.js'+import { claimSetupToken } from './lib/e2ee/relayClient.js'import {startSelfUpdater, restore as restoreUpdate, confirm as confirmUpdate,fetchManifest, downloadVerified, canary, stage, semverGt,@@ -186,6 +190,8 @@ A launcher that hands the pane to one of these works the same — "ori claude" iMachine:harness login sign in with SSO and save this computer's sessionharness login --force stop the daemon and sign in with a different SSO account+ harness login --json emit machine-readable NDJSON instead of opening a browser (for GUI clients)+ harness auth status --json print {loggedIn,...} for this computer's saved sessionharness start start the adapter using the saved SSO sessionharness start -f run the adapter in the FOREGROUND (for a supervisor; logs to stdout)harness logout stop the adapter and clear this computer's SSO session@@ -204,6 +210,13 @@ Browser end-to-end encryption:harness unpair <#|fp> unpair one browser (by list number or fingerprint)harness unpair --all unpair every browser+Machine-to-machine linking (lets this machine's relay reach ANOTHER of your machines with the CLI,+not the app, terminating E2EE):+ harness link create print a token for another machine's \`harness link import\`+ harness link import <token> claim a token printed by another machine's \`harness link create\`+ harness link list list machines this one has linked+ harness link unlink <id> remove a linked machine's trust+harness --helpThis computer's id lives at ${tildify(env.ADAPTER_COMPUTER_ID_FILE)} and is created once. Nothing here@@ -291,11 +304,43 @@ async function resolveComputerMachine(): Promise<AuthSession> {return next}-async function loginCommand(foreground: boolean, force: boolean): Promise<void> {+/** `harness auth status --json` — one JSON line, always exit 0; logged-out is a valid answer, not a+ * process failure. Reuses AuthSessionManager.accessToken() (not a raw file read) so a session that's+ * on-disk-but-about-to-expire gets refreshed here rather than reporting loggedIn:true and 401ing on+ * the caller's very next request. */+async function authStatusCommand(json: boolean): Promise<void> {+ const session = readAuthSession()+ if (!session) {+ if (json) console.log(JSON.stringify({ loggedIn: false }))+ else console.log('\n ✗ Not signed in. Run: harness login\n')+ return+ }+ const auth = new AuthSessionManager(backendHttpBase())+ let loggedIn = true+ try {+ await auth.accessToken()+ } catch (err) {+ loggedIn = !(err instanceof AuthSessionError)+ }+ const latest = readAuthSession()+ const payload = {+ loggedIn: loggedIn && latest !== null,+ computerId: latest?.computerId,+ machineId: latest?.machineId,+ autonomousEnv: latest?.autonomousEnv,+ expiresAt: latest?.expiresAt,+ }+ if (json) console.log(JSON.stringify(payload))+ else console.log(`\n ${payload.loggedIn ? '✓ Signed in' : '✗ Not signed in'}${payload.machineId ? ` (machine ${payload.machineId})` : ''}\n`)+}++async function loginCommand(foreground: boolean, force: boolean, json: boolean): Promise<void> {if (foreground) throw new Error('`harness login` does not run the adapter. Use `harness start -f`.')+ const emit = (line: Record<string, unknown>): void => { if (json) console.log(JSON.stringify(line)) }if (readAuthSession() && !force) {await resolveComputerMachine()- console.log('\n ✓ Already signed in. Run `harness start` to connect this computer.\n')+ if (json) emit({ type: 'result', status: 'success', alreadySignedIn: true })+ else console.log('\n ✓ Already signed in. Run `harness start` to connect this computer.\n')return}// A forced login may intentionally switch SSO accounts. The old daemon must not keep streaming@@ -310,35 +355,58 @@ async function loginCommand(foreground: boolean, force: boolean): Promise<void>if (!address || typeof address === 'string') throw new Error('Could not start the SSO callback server')const redirectUri = `http://127.0.0.1:${address.port}/callback`try {- const start = await postJson<{ authorizeUrl?: string; tx?: string }>('/api/auth/authorize-native', {- redirectUri,- autonomousEnv: env.AUTONOMOUS_ENV,- })- if (!start.authorizeUrl || !start.tx) throw new Error('Backend did not return an SSO authorize URL')- console.log('\n Sign in to Harness in your browser:\n')- console.log(` ${start.authorizeUrl}\n`)- openInBrowser(start.authorizeUrl)- const callbackResult = await new Promise<{ code: string; state: string }>((resolve, reject) => {- const timeout = setTimeout(() => reject(new Error('SSO login timed out')), 5 * 60_000)- callback.on('request', (req, res) => {- const url = new URL(req.url ?? '/', redirectUri)- const code = url.searchParams.get('code')- const state = url.searchParams.get('state')- const error = url.searchParams.get('error')- res.writeHead(error || !code || !state ? 400 : 200, { 'content-type': 'text/html; charset=utf-8' })- res.end(error || !code || !state- ? '<h1>Harness login failed</h1><p>You can close this window.</p>'- : '<h1>Harness login complete</h1><p>You can close this window and return to the terminal.</p>')- clearTimeout(timeout)- if (error) reject(new Error(`SSO login failed: ${error}`))- else if (code && state) resolve({ code, state })+ let start: { authorizeUrl?: string; tx?: string }+ try {+ start = await postJson<{ authorizeUrl?: string; tx?: string }>('/api/auth/authorize-native', {+ redirectUri,+ autonomousEnv: env.AUTONOMOUS_ENV,})- })- const exchanged = await postJson<{ token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag' }>('/api/auth/exchange', {- ...callbackResult,- tx: start.tx,- })- if (!exchanged.token) throw new Error('SSO exchange returned no access token')+ if (!start.authorizeUrl || !start.tx) throw new Error('Backend did not return an SSO authorize URL')+ } catch (err) {+ if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return }+ throw err+ }+ if (json) {+ emit({ type: 'authorize_url', url: start.authorizeUrl })+ } else {+ console.log('\n Sign in to Harness in your browser:\n')+ console.log(` ${start.authorizeUrl}\n`)+ openInBrowser(start.authorizeUrl)+ }+ let callbackResult: { code: string; state: string }+ try {+ callbackResult = await new Promise<{ code: string; state: string }>((resolve, reject) => {+ const timeout = setTimeout(() => reject(new Error('SSO login timed out')), 5 * 60_000)+ callback.on('request', (req, res) => {+ const url = new URL(req.url ?? '/', redirectUri)+ const code = url.searchParams.get('code')+ const state = url.searchParams.get('state')+ const error = url.searchParams.get('error')+ res.writeHead(error || !code || !state ? 400 : 200, { 'content-type': 'text/html; charset=utf-8' })+ res.end(error || !code || !state+ ? '<h1>Harness login failed</h1><p>You can close this window.</p>'+ : '<h1>Harness login complete</h1><p>You can close this window and return to the terminal.</p>')+ clearTimeout(timeout)+ if (error) reject(new Error(`SSO login failed: ${error}`))+ else if (code && state) resolve({ code, state })+ })+ })+ } catch (err) {+ const timedOut = (err as Error).message === 'SSO login timed out'+ if (json) { emit({ type: 'result', status: 'error', code: timedOut ? 'TIMEOUT' : 'CALLBACK_ERROR', message: (err as Error).message }); process.exitCode = 1; return }+ throw err+ }+ let exchanged: { token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag' }+ try {+ exchanged = await postJson<{ token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag' }>('/api/auth/exchange', {+ ...callbackResult,+ tx: start.tx,+ })+ if (!exchanged.token) throw new Error('SSO exchange returned no access token')+ } catch (err) {+ if (json) { emit({ type: 'result', status: 'error', code: 'EXCHANGE_FAILED', message: (err as Error).message }); process.exitCode = 1; return }+ throw err+ }const id = computerId()const session: AuthSession = {version: 1,@@ -350,8 +418,14 @@ async function loginCommand(foreground: boolean, force: boolean): Promise<void>updatedAt: Date.now(),}writeAuthSession(session)- await resolveComputerMachine()- console.log('\n ✓ Signed in. Run `harness start` to connect this computer.\n')+ try {+ await resolveComputerMachine()+ } catch (err) {+ if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return }+ throw err+ }+ if (json) emit({ type: 'result', status: 'success' })+ else console.log('\n ✓ Signed in. Run `harness start` to connect this computer.\n')} finally {await new Promise<void>((resolve) => callback.close(() => resolve()))}@@ -1817,6 +1891,26 @@ async function runForeground(session: AuthSession): Promise<void> {void agentReconciler.trigger()}+ /** Proxy a control-plane call to backend using THIS daemon's own SSO session — the local caller+ * (e.g. the desktop app) never needs a bearer token of its own, loopback trust does the+ * authenticating. Forwards backend's response status/body verbatim, success or error alike, so a+ * local client's model layer needs zero special-casing versus talking to backend directly. */+ async function proxyBackend(method: string, path: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> }> {+ const accessToken = await auth.accessToken()+ const latest = readAuthSession()+ const res = await fetch(`${backendHttpBase()}${path}`, {+ method,+ headers: {+ authorization: `Bearer ${accessToken}`,+ 'x-autonomous-env': latest?.autonomousEnv ?? session.autonomousEnv,+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),+ },+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),+ })+ const json = await res.json().catch(() => ({})) as Record<string, unknown>+ return { status: res.status, body: json }+ }+const { server: hookServer, port: hookPort } = await startHookServer(env.PORT, {resolveHookAgent: async ({ engine, runtimeHints, callerPid }) => {if (!callerPid) return null@@ -2152,10 +2246,25 @@ async function runForeground(session: AuthSession): Promise<void> {try { return readFileSync(LOG_FILE, 'utf-8').split('\n').slice(-120).join('\n') } catch { return '' }},onStop: () => { setTimeout(() => process.kill(process.pid, 'SIGTERM'), 50) }, // let the 200 flush first+ onMachinesList: () => proxyBackend('GET', '/api/machines'),+ onMachineRename: (machineId, name) => proxyBackend('PATCH', `/api/machines/${encodeURIComponent(machineId)}`, { name }),+ onAuthMe: () => proxyBackend('GET', '/api/auth/me'),})+ // Same on-disk identity `harness link create`/`import` use (E2eeStore.init() is idempotent per file,+ // so a separate in-memory instance here just reads the one this machine already has).+ const relayIdentityStore = new E2eeStore()+ relayIdentityStore.init()+ const relayPool = new RemoteRelayPool(+ auth,+ env.BACKEND_WS_URL.replace(/\/$/, ''),+ relayIdentityStore.getIdentity(),+ new MachinePeerStore(),+ )const localWsServer = attachLocalWsServer(hookServer, {machineId: backend.machineId,backend,+ relayPool,+ autonomousEnv: readAuthSession()?.autonomousEnv ?? session.autonomousEnv,})// Install both CLI hooks with the port the local server actually bound.if (!env.DISABLE_HOOK_INSTALL) {@@ -3124,6 +3233,90 @@ async function unpairCommand(id: string | undefined, all: boolean): Promise<voidprocess.exit(1)}+/** `harness link create` — print a reusable setup token this machine's own identity signs, for+ * ANOTHER MACHINE's `harness link import` to consume — the machine-to-machine counterpart of+ * `browser-link` (same token mechanism, different consumer). Kept a distinct verb on purpose: `pair`/+ * `browser-link` stay reserved for the browser↔this-machine relation (see the file header comment). */+async function linkCreateCommand(): Promise<void> {+ const session = readAuthSession()+ if (!session?.machineId) { console.error('\n ✗ This computer is not signed in. Run: harness login\n'); process.exit(1) }+ const setup = createSetupToken(session.machineId)+ console.log('\n Machine-link token (valid for 7 days):\n')+ console.log(` ${setup.token}\n`)+ console.log(' Run on the OTHER machine:\n')+ console.log(` harness link import ${setup.token}\n`)+ console.log(` fingerprint ${setup.fingerprint} — verify it matches on the other machine\n`)+ process.exit(0)+}++/** `harness link import <token>` — claim another machine's link token, proving THIS machine's own+ * identity to it. Needs only this computer's own SSO session and network — no running daemon+ * required. On success this machine can relay through to that machine's data plane with the CLI (not+ * the app) terminating E2EE — see lib/remoteRelay.ts. */+async function linkImportCommand(token: string | undefined): Promise<void> {+ if (!token) { console.error('Usage: harness link import <token> (from `harness link create` on the other machine)'); process.exit(1) }+ const session = readAuthSession()+ if (!session) { console.error('\n ✗ Not signed in. Run: harness login\n'); process.exit(1) }+ const verified = verifySetupToken(token)+ if (!verified || !verified.payload.machineId) {+ console.error('\n ✗ That token is invalid, expired, or missing a machine id.\n')+ process.exit(1)+ }+ const targetMachineId = verified.payload.machineId+ const auth = new AuthSessionManager(backendHttpBase())+ let accessToken: string+ try {+ accessToken = await auth.accessToken()+ } catch (err) {+ console.error(`\n ✗ Could not refresh this computer's SSO session: ${err instanceof Error ? err.message : err}\n`)+ process.exit(1)+ return+ }+ const store = new E2eeStore()+ store.init()+ const result = await claimSetupToken({+ token,+ targetMachineId,+ selfIdentity: store.getIdentity(),+ accessToken,+ backendWsBase: env.BACKEND_WS_URL.replace(/\/$/, ''),+ autonomousEnv: session.autonomousEnv,+ })+ if (!result.ok) {+ console.error(`\n ✗ Link failed: ${result.error}\n`)+ process.exit(1)+ return+ }+ new MachinePeerStore().pin(targetMachineId, b64e(result.peerPub), 'harness link', Date.now())+ console.log(`\n ✓ Linked machine ${targetMachineId}`)+ console.log(` fingerprint ${result.fingerprint} — verify it matches \`harness link create\`'s output on the other machine\n`)+ process.exit(0)+}++/** `harness link list` — machines this one has linked (CLI-to-CLI/machine-node trust, not browsers). */+async function linkListCommand(): Promise<void> {+ const peers = new MachinePeerStore().list()+ if (!peers.length) {+ console.log('\n No machines linked yet.\n Run `harness link create` on another machine and `harness link import <token>` here.\n')+ process.exit(0)+ }+ console.log('\n Linked machines:\n')+ peers.forEach((p, i) => {+ const when = new Date(p.linkedAt).toISOString().slice(0, 16).replace('T', ' ')+ console.log(` ${String(i + 1).padStart(2)}. ${p.machineId} ${p.fingerprint} (linked ${when})`)+ })+ process.exit(0)+}++/** `harness link unlink <machineId>` — remove a linked machine's trust pin. */+async function linkUnlinkCommand(machineId: string | undefined): Promise<void> {+ if (!machineId) { console.error('Usage: harness link unlink <machineId> (see: harness link list)'); process.exit(1) }+ const removed = new MachinePeerStore().unlink(machineId)+ if (!removed) { console.error(`\n ✗ No linked machine matches "${machineId}". Run: harness link list\n`); process.exit(1); return }+ console.log(`\n ✓ Unlinked ${machineId}\n`)+ process.exit(0)+}+/** `harness status` — print the info block with the current running state. */async function status(): Promise<void> {const pid = readPid()@@ -3158,7 +3351,11 @@ const onError = (err: unknown): never => {switch (cmd) {case 'login':- loginCommand(foreground, flags.includes('--force')).catch(onError)+ loginCommand(foreground, flags.includes('--force'), flags.includes('--json')).catch(onError)+ break+ case 'auth':+ if (args[0] !== 'status') { console.error('Unknown command: auth ' + (args[0] ?? '')); usage(1) }+ else authStatusCommand(flags.includes('--json')).catch(onError)breakcase 'logout':logout().catch(onError)@@ -3188,6 +3385,13 @@ switch (cmd) {case 'pairings':pairingsCommand().catch(onError)break+ case 'link':+ if (args[0] === 'create') linkCreateCommand().catch(onError)+ else if (args[0] === 'import') linkImportCommand(args[1]).catch(onError)+ else if (args[0] === 'list') linkListCommand().catch(onError)+ else if (args[0] === 'unlink') linkUnlinkCommand(args[1]).catch(onError)+ else { console.error(`Unknown command: link ${args[0] ?? ''}`); usage(1) }+ breakcase 'unpair':unpairCommand(args[0], flags.includes('--all') || flags.includes('-a')).catch(onError)breakdiff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 5ec7c6eb5..91fe988b9 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -89,6 +89,13 @@ export interface HookServerHandlers {onLogs?: () => string/** Stop the adapter from the local dashboard (POST /api/stop). */onStop?: () => void+ /** GET /api/machines — proxy the user's full machine list from backend using this daemon's own+ * saved SSO session, so a local GUI client never needs a token of its own. */+ onMachinesList?: () => Promise<PairOutcome>+ /** PATCH /api/machines/:machineId — proxy a rename to backend the same way. */+ onMachineRename?: (machineId: string, name: string) => Promise<PairOutcome>+ /** GET /api/auth/me — proxy the signed-in user's profile from backend. */+ onAuthMe?: () => Promise<PairOutcome>}const MAX_HOOK_BODY_BYTES = 256 * 1024@@ -509,6 +516,29 @@ export function startHookServer(const out = handlers.onSetupLink(); json(out.status, out.body); return}+ // Local GUI clients (e.g. the desktop app): read the full machine list / rename one / read the+ // signed-in profile through this daemon's own SSO session, so the local caller never holds a+ // bearer token itself — loopback trust does the authenticating. Reads are ungated (same tier as+ // /api/status); the rename mutation is CSRF-guarded like every other local write.+ if (req.method === 'GET' && url === '/api/machines') {+ if (!handlers.onMachinesList) { json(503, { error: 'UNAVAILABLE' }); return }+ const out = await handlers.onMachinesList(); json(out.status, out.body); return+ }+ if (req.method === 'GET' && url === '/api/auth/me') {+ if (!handlers.onAuthMe) { json(503, { error: 'UNAVAILABLE' }); return }+ const out = await handlers.onAuthMe(); json(out.status, out.body); return+ }+ if (req.method === 'PATCH' && url.startsWith('/api/machines/')) {+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }+ if (!handlers.onMachineRename) { json(503, { error: 'UNAVAILABLE' }); return }+ const machineId = decodeURIComponent(url.slice('/api/machines/'.length))+ if (!machineId) { json(400, { error: 'MISSING_MACHINE_ID' }); return }+ let body: { name?: string }+ try { body = JSON.parse(await readBody(req)) as { name?: string } } catch { json(400, { error: 'bad json' }); return }+ if (!body.name) { json(400, { error: 'MISSING_NAME' }); return }+ const out = await handlers.onMachineRename(machineId, body.name); json(out.status, out.body); return+ }+// `harness pairings` — list paired browsers.if (req.method === 'GET' && url === '/api/pairs') {if (!handlers.onListPairs) { json(503, { error: 'UNAVAILABLE' }); return }diff --git a/cli/src/lib/e2ee/machinePeers.ts b/cli/src/lib/e2ee/machinePeers.tsnew file mode 100644index 000000000..748e9e5de--- /dev/null+++ b/cli/src/lib/e2ee/machinePeers.ts@@ -0,0 +1,67 @@+/**+ * Persistence for the "this machine trusts machine X" relation — a third E2EE trust relation distinct+ * from browser↔this-machine (`E2eeStore`/`paired.json`). Established via `harness link create` (on the+ * peer) + `harness link import <token>` (here), never via the live 6-digit CPace code — see+ * relayClient.ts for the session this pin then bootstraps. Same file-permission conventions as+ * `E2eeStore`: ${ADAPTER_DATA_DIR}/e2e/, 0700 dir / 0600 file.+ *+ * Deliberately NOT cached in memory: `harness link import` runs as its own short-lived process,+ * independent of the daemon — the daemon's `RemoteRelayPool` must see a link the moment `link import`+ * writes it, not only after a restart. The file is tiny and read rarely (once per fresh relay dial),+ * so reading fresh every time costs nothing.+ */+import { mkdirSync, readFileSync, writeFileSync } from 'fs'+import { join } from 'path'+import { env } from '../../config/env.js'+import { b64d, fingerprint } from './core.js'++const DIR = join(env.ADAPTER_DATA_DIR, 'e2e')+const FILE = join(DIR, 'machinePeers.json')++export interface MachinePeer {+ machineId: string+ pub: string // base64 Ed25519 pubkey of the peer machine's own identity+ label: string+ linkedAt: number+}++function readAll(): Map<string, MachinePeer> {+ const peers = new Map<string, MachinePeer>()+ try {+ const arr = JSON.parse(readFileSync(FILE, 'utf-8')) as MachinePeer[]+ for (const p of arr) {+ if (p?.machineId && p?.pub) peers.set(p.machineId, p)+ }+ } catch { /* none yet */ }+ return peers+}++function writeAll(peers: Map<string, MachinePeer>): void {+ mkdirSync(DIR, { recursive: true, mode: 0o700 })+ writeFileSync(FILE, JSON.stringify([...peers.values()], null, 2), { mode: 0o600 })+}++export class MachinePeerStore {+ get(machineId: string): MachinePeer | null {+ return readAll().get(machineId) ?? null+ }++ pin(machineId: string, pub: string, label: string, at = Date.now()): void {+ const peers = readAll()+ peers.set(machineId, { machineId, pub, label, linkedAt: at })+ writeAll(peers)+ }++ unlink(machineId: string): boolean {+ const peers = readAll()+ if (!peers.delete(machineId)) return false+ writeAll(peers)+ return true+ }++ list(): Array<MachinePeer & { fingerprint: string }> {+ return [...readAll().values()]+ .map((p) => ({ ...p, fingerprint: fingerprint(b64d(p.pub)) }))+ .sort((a, b) => b.linkedAt - a.linkedAt)+ }+}diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.tsnew file mode 100644index 000000000..9a3afa00e--- /dev/null+++ b/cli/src/lib/e2ee/relayClient.ts@@ -0,0 +1,225 @@+/**+ * The "client" (formerly-browser) role of the E2EE session protocol, run by THIS daemon on behalf of a+ * local app relaying through it to a REMOTE machine it has link-imported a setup token for (see+ * machinePeers.ts). Establishes a session via e2e_hello/e2e_welcome, then encrypts outgoing frames /+ * decrypts incoming ones for the lifetime of the relay connection.+ *+ * This is bookkeeping only — every actual crypto primitive comes from core.ts (identical to the one+ * that used to run this same role inside the Flutter desktop app and still runs it in the web app), so+ * there is no new cryptography here, only a new caller of it.+ */+import { WebSocket } from 'ws'+import * as C from './core.js'+import { deriveTerminalBinaryKey, openTerminalBinary, sealTerminalBinary, type TerminalBinaryClear } from '../terminalBinary.js'++type Frame = Record<string, unknown>++export interface RelayCryptoDeps {+ machineId: string+ selfIdentity: C.Identity+ peerPub: Uint8Array+}++export class RelaySessionCrypto {+ private readonly eph = C.newEphemeral()+ private c2s: Uint8Array | null = null+ private s2c: Uint8Array | null = null+ private terminalC2s: Uint8Array | null = null+ private terminalS2c: Uint8Array | null = null+ private c2sCounter = 0+ private s2cRecv = -1+ private terminalC2sCounter = 0+ private terminalS2cRecv = -1+ private groupKey: Uint8Array | null = null+ private epoch = ''+ private groupRecv = new Map<string, number>() // epoch -> highest counter seen++ constructor(private readonly deps: RelayCryptoDeps) {}++ get ready(): boolean { return this.c2s !== null && this.s2c !== null }++ helloFrame(): Frame {+ return {+ type: 'e2e_hello',+ payload: {+ identityPub: C.b64e(this.deps.selfIdentity.pub),+ ephPub: C.b64e(this.eph.pub),+ sig: C.b64e(C.helloSig(this.deps.selfIdentity.priv, this.deps.machineId, this.eph.pub)),+ },+ }+ }++ /** Process an `e2e_welcome` reply to our hello. Returns true once the session is usable. */+ handleWelcome(payload: Record<string, unknown>): boolean {+ const adapterEphPubB64 = typeof payload.ephPub === 'string' ? payload.ephPub : ''+ const sigB64 = typeof payload.sig === 'string' ? payload.sig : ''+ const encB64 = typeof payload.enc === 'string' ? payload.enc : ''+ if (!adapterEphPubB64 || !sigB64 || !encB64) return false+ let adapterEphPub: Uint8Array+ let keys: { c2s: Uint8Array; s2c: Uint8Array }+ try {+ adapterEphPub = C.b64d(adapterEphPubB64)+ if (!C.welcomeVerify(this.deps.peerPub, this.deps.machineId, this.eph.pub, adapterEphPub, C.b64d(sigB64))) return false+ keys = C.sessionKeys(this.eph.priv, adapterEphPub, this.deps.machineId, this.eph.pub, adapterEphPub)+ } catch { return false }+ const opened = C.aeadOpen(keys.s2c, 0, C.utf8('e2e-welcome'), C.b64d(encB64))+ if (!opened) return false+ let initial: { groupKey?: string; epoch?: string }+ try { initial = JSON.parse(new TextDecoder().decode(opened)) as { groupKey?: string; epoch?: string } } catch { return false }+ if (!initial.groupKey || !initial.epoch) return false+ this.c2s = keys.c2s+ this.s2c = keys.s2c+ this.terminalC2s = deriveTerminalBinaryKey(keys.c2s)+ this.terminalS2c = deriveTerminalBinaryKey(keys.s2c)+ this.groupKey = C.b64d(initial.groupKey)+ this.epoch = initial.epoch+ return true+ }++ /** Process an `e2e_rekey` (group key rotation) frame. */+ handleRekey(payload: Record<string, unknown>): boolean {+ if (!this.s2c) return false+ const n = typeof payload.n === 'number' ? payload.n : NaN+ const encB64 = typeof payload.enc === 'string' ? payload.enc : ''+ if (!Number.isFinite(n) || !encB64) return false+ const opened = C.aeadOpen(this.s2c, n, C.utf8('e2e-rekey'), C.b64d(encB64))+ if (!opened) return false+ let next: { groupKey?: string; epoch?: string }+ try { next = JSON.parse(new TextDecoder().decode(opened)) as { groupKey?: string; epoch?: string } } catch { return false }+ if (!next.groupKey || !next.epoch) return false+ this.groupKey = C.b64d(next.groupKey)+ this.epoch = next.epoch+ return true+ }++ /** Encrypt an outgoing (local app → remote machine) frame if its type requires it. */+ wrapOutgoing(frame: Frame): Frame {+ const type = frame.type as string | undefined+ if (!type || !this.c2s || !C.isEncryptedDownType(type)) return frame+ const payload = C.wrapPayload(this.c2s, 'p', this.c2sCounter++, type, undefined, frame.payload)+ return { ...frame, payload }+ }++ /** Decrypt an incoming (remote machine → local app) frame. Null = authenticated-stale or+ * undecryptable and must be dropped, never forwarded. A never-wrapped (plaintext control) frame+ * passes through unchanged. */+ unwrapIncoming(frame: Frame): Frame | null {+ const payload = frame.payload as Record<string, unknown> | undefined+ if (!payload || !C.isWrapped(payload)) return frame+ const env = (payload as C.WrappedPayload).__e2e+ if (!env || typeof env.n !== 'number' || typeof env.ct !== 'string') return null+ const type = frame.type as string+ if (env.k === 'g') {+ if (!this.groupKey || env.epoch !== this.epoch) return null+ const seen = this.groupRecv.get(env.epoch) ?? -1+ if (env.n <= seen) return null+ const plain = C.unwrapPayload(this.groupKey, env, type, frame.dbSessionId as string | undefined)+ if (plain === null) return null+ this.groupRecv.set(env.epoch, env.n)+ return { ...frame, payload: plain }+ }+ if (!this.s2c) return null+ if (env.n <= this.s2cRecv) return null+ const plain = C.unwrapPayload(this.s2c, env, type, frame.dbSessionId as string | undefined)+ if (plain === null) return null+ this.s2cRecv = env.n+ return { ...frame, payload: plain }+ }++ /** Encrypt an outgoing binary terminal frame (already decoded from the local plaintext wire format). */+ encryptTerminal(clear: TerminalBinaryClear): Uint8Array | null {+ if (!this.terminalC2s) return null+ const sealed = sealTerminalBinary(this.terminalC2s, this.terminalC2sCounter, clear)+ if (sealed) this.terminalC2sCounter+++ return sealed+ }++ /** Decrypt an incoming HTRM binary terminal frame into its clear form (to be re-encoded as the local+ * plaintext wire format before reaching the app). Null = drop (stale/undecryptable). */+ decryptTerminal(raw: Uint8Array): TerminalBinaryClear | null {+ if (!this.terminalS2c) return null+ const opened = openTerminalBinary(this.terminalS2c, raw)+ if (!opened || (this.terminalS2cRecv !== -1 && opened.counter <= this.terminalS2cRecv)) return null+ this.terminalS2cRecv = opened.counter+ return opened.frame+ }+}++export type ClaimResult =+ | { ok: true; peerPub: Uint8Array; fingerprint: string }+ | { ok: false; error: string }++/** `harness link import <token>`: verify the token offline, open a short-lived authenticated+ * `/api/web-ws` connection to the target machine (same endpoint RemoteRelayPool dials for the real+ * relay), and claim it — proving possession of THIS machine's own long-term identity, bound to the+ * token. On success the caller pins the returned peerPub via MachinePeerStore; no session/relay state+ * is established here, just the one-time trust pin. */+export async function claimSetupToken(opts: {+ token: string+ targetMachineId: string+ selfIdentity: C.Identity+ accessToken: string+ backendWsBase: string+ autonomousEnv: string+ timeoutMs?: number+}): Promise<ClaimResult> {+ const verified = C.verifySetupToken(opts.token, Date.now(), opts.targetMachineId)+ if (!verified) return { ok: false, error: 'BAD_TOKEN' }+ const url = `${opts.backendWsBase}/api/web-ws?autonomousEnv=${encodeURIComponent(opts.autonomousEnv)}`+ const ws = new WebSocket(url, [opts.accessToken])+ const requestId = C.b64e(C.newPairId())+ return new Promise<ClaimResult>((resolve) => {+ let settled = false+ const finish = (result: ClaimResult): void => {+ if (settled) return+ settled = true+ clearTimeout(timeout)+ try { ws.close() } catch { /* ignore */ }+ resolve(result)+ }+ const timeout = setTimeout(() => finish({ ok: false, error: 'TIMEOUT' }), opts.timeoutMs ?? 15_000)+ let selected = false+ ws.once('open', () => {+ try { ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId: opts.targetMachineId } })) }+ catch { finish({ ok: false, error: 'SEND_FAILED' }) }+ })+ ws.on('message', (raw, isBinary) => {+ if (isBinary) return+ let frame: Record<string, unknown>+ try { frame = JSON.parse(raw.toString()) as Record<string, unknown> } catch { return }+ const payload = (frame.payload ?? {}) as Record<string, unknown>+ if (!selected) {+ if (frame.type === 'connected' && payload.machineId === opts.targetMachineId) {+ selected = true+ const sig = C.setupClaimSig(opts.selfIdentity.priv, opts.targetMachineId, opts.token, opts.selfIdentity.pub)+ ws.send(JSON.stringify({+ type: 'e2e_setup_claim',+ payload: {+ requestId,+ token: opts.token,+ identityPub: C.b64e(opts.selfIdentity.pub),+ sig: C.b64e(sig),+ label: 'harness link',+ },+ }))+ } else if (frame.type === 'machine_select_error' && payload.machineId === opts.targetMachineId) {+ finish({ ok: false, error: typeof payload.error === 'string' ? payload.error : 'SELECT_FAILED' })+ }+ return+ }+ if (frame.type === 'e2e_setup_claim_result' && payload.requestId === requestId) {+ if (payload.ok === true) {+ finish({+ ok: true,+ peerPub: verified.adapterPub,+ fingerprint: typeof payload.fingerprint === 'string' ? payload.fingerprint : C.fingerprint(verified.adapterPub),+ })+ } else {+ finish({ ok: false, error: typeof payload.error === 'string' ? payload.error : 'CLAIM_FAILED' })+ }+ }+ })+ ws.once('close', (code) => finish({ ok: false, error: `CONNECTION_CLOSED:${code}` }))+ ws.once('error', () => finish({ ok: false, error: 'CONNECTION_ERROR' }))+ })+}diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.tsnew file mode 100644index 000000000..d682876a7--- /dev/null+++ b/cli/src/lib/e2ee/relayLink.spec.ts@@ -0,0 +1,158 @@+import { describe, it, expect, beforeAll, beforeEach } from 'vitest'+import { mkdtempSync, rmSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { WebSocketServer } from 'ws'+import type { AddressInfo } from 'net'++// Same reason as manager.test.ts: ADAPTER_DATA_DIR must be set before any transitive import of+// config/env.js, so every module under test is dynamically imported after the temp dir is set.+type Frame = Record<string, unknown>+let C: typeof import('./core.js')+let E2eeManagerCtor: typeof import('./manager.js')['E2eeManager']+let RelaySessionCrypto: typeof import('./relayClient.js')['RelaySessionCrypto']+let claimSetupToken: typeof import('./relayClient.js')['claimSetupToken']+let MachinePeerStore: typeof import('./machinePeers.js')['MachinePeerStore']++const MACHINE_ID = 'f2e0383771b734e4fc00f0bc8ccf060f'++beforeAll(async () => {+ process.env.ADAPTER_DATA_DIR = mkdtempSync(join(tmpdir(), 'e2ee-link-'))+ C = await import('./core.js')+ E2eeManagerCtor = (await import('./manager.js')).E2eeManager+ const relayClient = await import('./relayClient.js')+ RelaySessionCrypto = relayClient.RelaySessionCrypto+ claimSetupToken = relayClient.claimSetupToken+ MachinePeerStore = (await import('./machinePeers.js')).MachinePeerStore+})++beforeEach(() => {+ try { rmSync(join(process.env.ADAPTER_DATA_DIR as string, 'e2e'), { recursive: true, force: true }) } catch { /* none */ }+})++describe('MachinePeerStore', () => {+ it('pins, lists, and unlinks — surviving a fresh instance (no in-memory cache)', () => {+ const a = new MachinePeerStore()+ const identity = C.newIdentity()+ a.pin(MACHINE_ID, C.b64e(identity.pub), 'test peer')+ // A second instance must see the write immediately — RemoteRelayPool and `harness link import`+ // run as separate processes/instances and must never rely on a stale in-memory cache.+ const b = new MachinePeerStore()+ expect(b.get(MACHINE_ID)?.pub).toBe(C.b64e(identity.pub))+ expect(b.list()).toHaveLength(1)+ expect(b.list()[0].fingerprint).toBe(C.fingerprint(identity.pub))+ expect(b.unlink(MACHINE_ID)).toBe(true)+ expect(b.get(MACHINE_ID)).toBeNull()+ expect(b.unlink(MACHINE_ID)).toBe(false)+ })+})++describe('link create/import + relay session crypto (interop with the real E2eeManager)', () => {+ it('claimSetupToken pins the correct adapter pubkey, then hello/welcome + frame/terminal round-trip succeed', async () => {+ const inbox: Frame[] = []+ // Fakes just enough of backend's `/api/web-ws` (machine_select -> connected, then generic e2e_*+ // frame relay) to drive a REAL E2eeManager on the "adapter" side against real client-role code —+ // no backend involved, but the exact same frame shapes cross the exact same transport primitive+ // (a WebSocket) that production uses.+ const wss = new WebSocketServer({ port: 0 })+ const manager = new E2eeManagerCtor({+ machineId: MACHINE_ID,+ sendTo: (_connId, frame) => {+ inbox.push(frame)+ for (const client of wss.clients) client.send(JSON.stringify(frame))+ },+ isConnected: () => true,+ })+ wss.on('connection', (ws) => {+ let selected = false+ ws.on('message', (raw) => {+ let frame: Frame+ try { frame = JSON.parse(raw.toString()) as Frame } catch { return }+ if (!selected) {+ if (frame.type === 'machine_select') {+ selected = true+ ws.send(JSON.stringify({ type: 'connected', payload: { machineId: MACHINE_ID } }))+ }+ return+ }+ const type = frame.type as string+ if (type.startsWith('e2e_')) manager.handleFrame('fake-conn', frame)+ })+ })++ try {+ const port = (wss.address() as AddressInfo).port+ const wsBase = `ws://127.0.0.1:${port}`+ const clientIdentity = C.newIdentity()+ const token = manager.createSetupToken(MACHINE_ID).token++ const result = await claimSetupToken({+ token,+ targetMachineId: MACHINE_ID,+ selfIdentity: clientIdentity,+ accessToken: 'unused-in-this-fake',+ backendWsBase: wsBase,+ autonomousEnv: 'prod',+ timeoutMs: 2_000,+ })++ expect(result.ok).toBe(true)+ if (!result.ok) return+ expect(result.fingerprint).toBe(manager.fingerprint())++ const peers = new MachinePeerStore()+ peers.pin(MACHINE_ID, C.b64e(result.peerPub), 'test')++ // Session establishment (hello/welcome) + frame/terminal crypto round-trip, driven in-process+ // against the same manager instance the claim above already pinned into.+ const crypto = new RelaySessionCrypto({ machineId: MACHINE_ID, selfIdentity: clientIdentity, peerPub: result.peerPub })+ const hello = crypto.helloFrame()+ expect(manager.handleFrame('session-conn', hello)).toBe(true)+ const welcome = inbox[inbox.length - 1]+ expect(welcome.type).toBe('e2e_welcome')+ expect(crypto.handleWelcome(welcome.payload as Record<string, unknown>)).toBe(true)+ expect(crypto.ready).toBe(true)++ // Outgoing: client encrypts a down-type frame; manager decrypts it via unwrapDown.+ const outgoing = crypto.wrapOutgoing({ type: 'terminal_input', payload: { requestId: 'r1', foo: 'bar' } })+ expect((outgoing.payload as Record<string, unknown>).__e2e).toBeDefined()+ const decrypted = manager.unwrapDown('session-conn', outgoing)+ expect(decrypted).not.toBeNull()+ expect((decrypted!.payload as Record<string, unknown>).foo).toBe('bar')++ // Incoming: manager broadcasts a group-encrypted up event; client decrypts it.+ const wrappedUp = manager.wrapUp({ type: 'user_message', payload: { text: 'hi' } })+ const plainUp = crypto.unwrapIncoming(wrappedUp)+ expect(plainUp).not.toBeNull()+ expect((plainUp!.payload as Record<string, unknown>).text).toBe('hi')++ // Terminal binary round-trip, both directions.+ const clear = { kind: 1 as const, streamId: '00112233-4455-6677-8899-aabbccddeeff', seq: 1, bytes: new Uint8Array([1, 2, 3]), compressed: false }+ const sealedOut = crypto.encryptTerminal(clear)+ expect(sealedOut).not.toBeNull()+ const openedByAdapter = manager.unwrapTerminalBinary('session-conn', sealedOut!)+ expect(openedByAdapter?.bytes).toEqual(clear.bytes)++ const sealedIn = manager.wrapTerminalBinary('session-conn', { ...clear, kind: 2 })+ expect(sealedIn).not.toBeNull()+ const openedByClient = crypto.decryptTerminal(sealedIn!)+ expect(openedByClient?.bytes).toEqual(clear.bytes)+ } finally {+ await new Promise<void>((resolve) => wss.close(() => resolve()))+ }+ })++ it('rejects a token signed for a different machine id', async () => {+ const manager = new E2eeManagerCtor({ machineId: MACHINE_ID, sendTo: () => {}, isConnected: () => true })+ const token = manager.createSetupToken(MACHINE_ID).token+ const result = await claimSetupToken({+ token,+ targetMachineId: 'a-completely-different-machine-id',+ selfIdentity: C.newIdentity(),+ accessToken: 'unused',+ backendWsBase: 'ws://127.0.0.1:1', // never reached — rejected before any connection is opened+ autonomousEnv: 'prod',+ })+ expect(result).toEqual({ ok: false, error: 'BAD_TOKEN' })+ })+})diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.tsnew file mode 100644index 000000000..6adfee5fb--- /dev/null+++ b/cli/src/lib/remoteRelay.ts@@ -0,0 +1,225 @@+/**+ * Relay from the local WS API (`/api/local-ws`) to backend's `/api/web-ws` for a machine this daemon+ * does NOT itself own — e.g. a cloud machine, or a different paired computer, that the same signed-in+ * user also has. One pooled upstream connection per foreign machineId, reused across quick local+ * reconnects (a short linger window before actually tearing it down).+ *+ * This daemon now TERMINATES E2EE on the relay itself (see lib/e2ee/relayClient.ts), playing the+ * "client" role a browser (or the old Flutter app) used to play, toward whichever remote machine+ * `lib/e2ee/machinePeers.ts` has a pinned trust for (established out of band via `harness link+ * create`/`harness link import`). The local app therefore only ever sees plaintext — the exact same+ * shape it already gets for this daemon's own machine — for every machine, relayed or not. A machine+ * with no pinned peer fails the relay with `NO_PEER_LINK` instead of ever reaching pipe mode.+ */+import { WebSocket, type RawData } from 'ws'+import type { Frame, LocalClientSink } from '../backendSocket.js'+import type { AuthSessionManager } from './authSession.js'+import { b64d, type Identity } from './e2ee/core.js'+import type { MachinePeerStore } from './e2ee/machinePeers.js'+import { RelaySessionCrypto } from './e2ee/relayClient.js'+import { encodeTerminalLocal, type TerminalBinaryClear } from './terminalBinary.js'++const CONNECT_TIMEOUT_MS = 15_000+const LINGER_MS = 30_000++export class RelayConnectError extends Error {+ constructor(message: string, readonly closeCode?: number) {+ super(message)+ this.name = 'RelayConnectError'+ }+}++function binaryBytes(raw: RawData): Uint8Array {+ if (Buffer.isBuffer(raw)) return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength)+ if (raw instanceof ArrayBuffer) return new Uint8Array(raw)+ if (Array.isArray(raw)) return new Uint8Array(Buffer.concat(raw))+ return new Uint8Array()+}++interface Entry {+ ws: WebSocket+ crypto: RelaySessionCrypto+ sink: LocalClientSink | null+ onClosed: ((code: number, reason: string) => void) | null+ lingerTimer: ReturnType<typeof setTimeout> | null+}++export interface RelaySession {+ send: (frame: Frame) => void+ sendBinary: (clear: TerminalBinaryClear) => void+ detach: () => void+}++export class RemoteRelayPool {+ private entries = new Map<string, Entry>()+ private pending = new Map<string, Promise<Entry>>()++ constructor(+ private readonly auth: AuthSessionManager,+ private readonly backendWsBase: string,+ private readonly selfIdentity: Identity,+ private readonly peers: MachinePeerStore,+ ) {}++ /** Attach `sink` to the (possibly newly-created, possibly reused) upstream connection for+ * `machineId`. `selectFrame` is the local client's own `machine_select` frame, forwarded upstream+ * verbatim on a fresh connect — backend only reads its `.machineId`, so the local protocol's extra+ * `localProtocolVersion` field is harmless. */+ async acquire(+ machineId: string,+ autonomousEnv: string,+ selectFrame: Frame,+ sink: LocalClientSink,+ onClosed: (code: number, reason: string) => void,+ ): Promise<RelaySession> {+ const existing = this.entries.get(machineId)+ if (existing) {+ if (existing.lingerTimer) { clearTimeout(existing.lingerTimer); existing.lingerTimer = null }+ existing.sink = sink+ existing.onClosed = onClosed+ sink.sendFrame({ type: 'connected', payload: { machineId, e2ee: false } })+ return this.sessionFor(machineId, existing)+ }+ const inFlight = this.pending.get(machineId)+ const entry = await (inFlight ?? this.connect(machineId, autonomousEnv, selectFrame))+ entry.sink = sink+ // The real backend `connected{machineId}` ack that resolved the connect above was consumed+ // internally by dial()'s handshake logic, not forwarded — this local client (whether it triggered+ // the dial or joined one already in flight) still needs its own ack to know the select succeeded.+ sink.sendFrame({ type: 'connected', payload: { machineId, e2ee: false } })+ entry.onClosed = onClosed+ return this.sessionFor(machineId, entry)+ }++ private connect(machineId: string, autonomousEnv: string, selectFrame: Frame): Promise<Entry> {+ const attempt = (forceRefresh: boolean): Promise<Entry> => this.dial(machineId, autonomousEnv, selectFrame, forceRefresh)+ // A stale access token is the single most likely reason the very first select fails (4401 on the+ // upgrade) — one retry with a freshly-refreshed token is cheap next to surfacing that as a hard+ // error to the user. Any other failure (env mismatch, not-your-machine, timeout) is not helped by+ // a token refresh, so it is not retried.+ const promise = attempt(false).catch((err) => {+ if (err instanceof RelayConnectError && err.closeCode === 4401) return attempt(true)+ throw err+ })+ this.pending.set(machineId, promise)+ void promise.finally(() => { if (this.pending.get(machineId) === promise) this.pending.delete(machineId) })+ return promise+ }++ private async dial(machineId: string, autonomousEnv: string, selectFrame: Frame, forceRefresh: boolean): Promise<Entry> {+ const peer = this.peers.get(machineId)+ if (!peer) throw new RelayConnectError('NO_PEER_LINK')+ const token = await this.auth.accessToken({ force: forceRefresh })+ const url = `${this.backendWsBase}/api/web-ws?autonomousEnv=${encodeURIComponent(autonomousEnv)}`+ const ws = new WebSocket(url, [token])+ const crypto = new RelaySessionCrypto({ machineId, selfIdentity: this.selfIdentity, peerPub: b64d(peer.pub) })+ const entry: Entry = { ws, crypto, sink: null, onClosed: null, lingerTimer: null }+ // Two phases before this connection is usable: (1) machine_select ack, (2) this daemon's own+ // e2e_hello/e2e_welcome as the "client" role — see lib/e2ee/relayClient.ts. Only once BOTH are done+ // does the app's onOutgoing/sink start receiving anything, so it never sees a half-encrypted stream.+ let selected = false+ await new Promise<void>((resolve, reject) => {+ let settled = false+ const timeout = setTimeout(() => {+ if (!settled) { settled = true; reject(new RelayConnectError('relay connect timed out')) }+ }, CONNECT_TIMEOUT_MS)+ ws.once('open', () => {+ try { ws.send(JSON.stringify(selectFrame)) } catch { /* the close handler below rejects */ }+ })+ ws.on('message', (raw, isBinary) => {+ if (!crypto.ready) {+ if (isBinary) return+ let frame: Frame+ try { frame = JSON.parse(raw.toString()) as Frame } catch { return }+ const payload = frame.payload as { machineId?: unknown; error?: unknown } | undefined+ if (!selected) {+ // The socket's very first frame, before any select, is {type:'connected',payload:{userId}} —+ // pure backend bookkeeping with no machineId. Swallow it; it answers nothing this relay asked.+ if (frame.type === 'connected' && payload?.machineId === undefined) return+ if (frame.type === 'connected' && payload?.machineId === machineId) {+ selected = true+ try { ws.send(JSON.stringify(crypto.helloFrame())) } catch { /* the close handler below rejects */ }+ return+ }+ if (frame.type === 'machine_select_error' && payload?.machineId === machineId) {+ if (!settled) {+ settled = true; clearTimeout(timeout)+ reject(new RelayConnectError(typeof payload.error === 'string' ? payload.error : 'machine_select_error'))+ }+ return+ }+ return // anything else before the select ack is unexpected — drop it+ }+ if (frame.type === 'e2e_welcome') {+ const ok = crypto.handleWelcome((frame.payload ?? {}) as Record<string, unknown>)+ if (!ok) { if (!settled) { settled = true; clearTimeout(timeout); reject(new RelayConnectError('E2EE_WELCOME_INVALID')) } ; return }+ if (!settled) { settled = true; clearTimeout(timeout); resolve() }+ return+ }+ if (frame.type === 'e2e_denied') {+ if (!settled) {+ settled = true; clearTimeout(timeout)+ const reason = (frame.payload as { reason?: unknown } | undefined)?.reason+ reject(new RelayConnectError(typeof reason === 'string' ? `E2EE_DENIED:${reason}` : 'E2EE_DENIED'))+ }+ return+ }+ return // anything else before the E2EE session is up is unexpected — drop it+ }+ // Session established — decrypt-then-forward / encrypt-then-send from here on.+ if (isBinary) {+ const clear = crypto.decryptTerminal(binaryBytes(raw))+ if (!clear) return // undecryptable/stale — drop, never forward ciphertext or garbage to the app+ const local = encodeTerminalLocal(clear)+ if (local) entry.sink?.sendBinary(local)+ return+ }+ let frame: Frame+ try { frame = JSON.parse(raw.toString()) as Frame } catch { return }+ if (frame.type === 'e2e_rekey') { crypto.handleRekey((frame.payload ?? {}) as Record<string, unknown>); return }+ const plain = crypto.unwrapIncoming(frame)+ if (plain) entry.sink?.sendFrame(plain)+ })+ ws.once('close', (code, reasonBuf) => {+ if (!settled) {+ settled = true; clearTimeout(timeout)+ reject(new RelayConnectError(`relay closed before session ready: ${reasonBuf?.toString() ?? ''}`, code))+ }+ })+ ws.once('error', (err) => {+ if (!settled) { settled = true; clearTimeout(timeout); reject(err instanceof Error ? err : new Error(String(err))) }+ })+ })+ // Handshake done — from here on, a close is the entry's real end-of-life, not a handshake failure.+ ws.on('close', (code, reasonBuf) => {+ this.entries.delete(machineId)+ entry.onClosed?.(code, reasonBuf?.toString() ?? '')+ })+ this.entries.set(machineId, entry)+ return entry+ }++ private sessionFor(machineId: string, entry: Entry): RelaySession {+ return {+ send: (frame) => {+ try { entry.ws.send(JSON.stringify(entry.crypto.wrapOutgoing(frame))) } catch { /* closed — onClosed will fire */ }+ },+ sendBinary: (clear) => {+ const sealed = entry.crypto.encryptTerminal(clear)+ if (!sealed) return+ try { entry.ws.send(sealed, { binary: true }) } catch { /* closed — onClosed will fire */ }+ },+ detach: () => {+ entry.sink = null+ entry.onClosed = null+ entry.lingerTimer = setTimeout(() => {+ if (!entry.sink) {+ try { entry.ws.close(1000, 'idle') } catch { /* ignore */ }+ this.entries.delete(machineId)+ }+ }, LINGER_MS)+ entry.lingerTimer.unref?.()+ },+ }+ }+}diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex 11b7f1097..b269831cc 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -4,6 +4,7 @@ import type { Socket } from 'node:net'import { WebSocket, WebSocketServer, type RawData } from 'ws'import type { Frame, LocalClientSink } from './backendSocket.js'import { decodeTerminalLocal, TERMINAL_BINARY_VERSION, type TerminalBinaryClear } from './lib/terminalBinary.js'+import { RelayConnectError, type RelaySession, type RemoteRelayPool } from './lib/remoteRelay.js'export const LOCAL_WS_PATH = '/api/local-ws'export const LOCAL_WS_PROTOCOL_VERSION = 1@@ -21,6 +22,10 @@ export interface LocalWsBackend {export interface LocalWsServerOptions {machineId: stringbackend: LocalWsBackend+ /** Serves a `machine_select` for any OTHER machine this signed-in user owns, by relaying to+ * backend's `/api/web-ws` — see lib/remoteRelay.ts. Omit to keep today's own-machine-only behavior. */+ relayPool?: RemoteRelayPool+ autonomousEnv?: string}export interface LocalWsServer {@@ -99,6 +104,7 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOwss.on('connection', (ws) => {const connId = `local:${randomUUID()}`let selected = false+ let relay: RelaySession | null = nulllet alive = truelet chain = Promise.resolve()@@ -124,27 +130,61 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOif (isBinary) { close(4400, 'machine_select required'); return }const frame = jsonFrame(raw)const payload = frame?.payload as Record<string, unknown> | undefined+ const requestedMachineId = payload?.machineIdif (frame?.type !== 'machine_select'- || payload?.machineId !== options.machineId+ || typeof requestedMachineId !== 'string'|| payload?.localProtocolVersion !== LOCAL_WS_PROTOCOL_VERSION) {close(4403, 'machine mismatch')return}- if (!options.backend.registerLocalClient(connId, sink)) {- close(1011, 'local registration failed')+ if (requestedMachineId === options.machineId) {+ if (!options.backend.registerLocalClient(connId, sink)) {+ close(1011, 'local registration failed')+ return+ }+ selected = true+ sink.sendFrame({+ type: 'connected',+ payload: {+ machineId: options.machineId,+ transport: 'local',+ localProtocolVersion: LOCAL_WS_PROTOCOL_VERSION,+ terminalProtocolVersion: TERMINAL_BINARY_VERSION,+ e2ee: false,+ },+ })return}- selected = true- sink.sendFrame({- type: 'connected',- payload: {- machineId: options.machineId,- transport: 'local',- localProtocolVersion: LOCAL_WS_PROTOCOL_VERSION,- terminalProtocolVersion: TERMINAL_BINARY_VERSION,- e2ee: false,- },- })+ // Not this daemon's own machine — relay to backend for the other machines this same+ // signed-in user owns, if the daemon was wired up to do that (see lib/remoteRelay.ts).+ if (!options.relayPool || !options.autonomousEnv) {+ close(4403, 'machine mismatch')+ return+ }+ try {+ relay = await options.relayPool.acquire(requestedMachineId, options.autonomousEnv, frame, sink, close)+ selected = true+ } catch (err) {+ const noPeerLink = err instanceof RelayConnectError && err.message === 'NO_PEER_LINK'+ const code = noPeerLink ? 4404 : err instanceof RelayConnectError && err.closeCode ? err.closeCode : 1011+ close(code, err instanceof Error ? err.message.slice(0, 120) : 'relay failed')+ }+ return+ }++ if (relay) {+ // The relay now terminates E2EE itself (lib/remoteRelay.ts) — every frame past this point is+ // already plaintext going in and out, so binary frames use the SAME local wire format as this+ // daemon's own machine.+ if (isBinary) {+ const clear = decodeTerminalLocal(binaryBytes(raw))+ if (!clear) { close(4400, 'invalid terminal frame'); return }+ relay.sendBinary(clear)+ return+ }+ const frame = jsonFrame(raw)+ if (!frame) { close(4400, 'invalid json frame'); return }+ relay.send(frame)return}@@ -169,7 +209,8 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOconst cleanup = (): void => {clearInterval(heartbeat)- if (selected) void options.backend.unregisterLocalClient(connId)+ if (relay) { relay.detach(); relay = null }+ else if (selected) void options.backend.unregisterLocalClient(connId)selected = false}ws.once('close', cleanup)