Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(relay): the Server Edition proves its host key when minting relay tokens
review40ab4919acc2
diff --git a/src/core/relay/host-token.test.ts b/src/core/relay/host-token.test.tsindex 29cb6b366..f2e391cc0 100644--- a/src/core/relay/host-token.test.ts+++ b/src/core/relay/host-token.test.ts@@ -1,6 +1,8 @@// src/core/relay/host-token.test.tsimport { describe, it, expect, vi, afterEach } from 'vitest'+import nacl from 'tweetnacl'import { mintHostToken, tokenTtlMs } from './host-token'+import { createTestPopServer } from './relay-pop.test-server'const res = (status: number, body: unknown, headers: Record<string, string> = {}) =>({ ok: status >= 200 && status < 300, status, headers: new Headers(headers), json: async () => body, text: async () => JSON.stringify(body) }) as Response@@ -12,11 +14,14 @@ afterEach(() => {describe('host token', () => {it('sends deviceId + host key and measures TTL on the server clock', async () => {let sent: unknown+ const urls: string[] = []const r = await mintHostToken({apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: 'K',- fetch: (async (_u: string, init: RequestInit) => { sent = JSON.parse(String(init.body)); return res(200, { pairingToken: 'T', hostId: 'H', exp: 1_000_120 }, { date: new Date(1_000_000_000).toUTCString() }) }) as typeof fetch,+ fetch: (async (u: string, init: RequestInit) => { urls.push(u); sent = JSON.parse(String(init.body)); return res(200, { pairingToken: 'T', hostId: 'H', exp: 1_000_120 }, { date: new Date(1_000_000_000).toUTCString() }) }) as typeof fetch,now: () => 999_000_000 // local clock 1000 s behind: must not matter})+ // No hostSecretKey = the legacy mode: one call, never a challenge.+ expect(urls.some((u) => u.endsWith('/challenge'))).toBe(false)expect(sent).toEqual({ deviceId: 'd', hostPublicKeyB64: 'K' })expect(r).toEqual({ ok: true, pairingToken: 'T', hostId: 'H', ttlMs: 120_000 })})@@ -88,3 +93,109 @@ describe('host token', () => {expect(settled).toEqual({ ok: false, kind: 'network' })})})++// --- proof of possession (relay-pop.ts): a real key pair against a byte-exact mirror of the backend ---+const keys = nacl.box.keyPair()+const PUB = Buffer.from(keys.publicKey).toString('base64')++function api(s = createTestPopServer(), over: { challenge?: (() => Response) | null; mint?: (body: Record<string, unknown>) => Response } = {}) {+ const calls: Array<{ url: string; body: Record<string, unknown> }> = []+ const f = (async (u: string, init: RequestInit) => {+ const body = JSON.parse(String(init.body)) as Record<string, unknown>+ calls.push({ url: u, body })+ if (u.endsWith('/v1/relay/challenge')) {+ if (over.challenge === null) return res(404, {})+ if (over.challenge) return over.challenge()+ return res(200, s.issue(body.hostPublicKeyB64 as string, body.purpose as 'host-token'))+ }+ if (over.mint) return over.mint(body)+ const valid = s.verify({ hostPublicKeyB64: body.hostPublicKeyB64 as string, purpose: 'host-token', subject: String(body.deviceId ?? ''), popChallenge: body.popChallenge, popProof: body.popProof })+ return valid ? res(200, { pairingToken: 'T', hostId: 'H', exp: 0 }) : res(403, { error: 'pop_invalid' })+ }) as typeof fetch+ return { f, calls }+}++describe('host token proof of possession', () => {+ it('proves possession: challenge first, then a mint the backend verifies', async () => {+ const { f, calls } = api()+ const r = await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: f })+ expect(r.ok).toBe(true)+ expect(calls.map((c) => c.url)).toEqual(['https://api/v1/relay/challenge', 'https://api/v1/relay/host-token'])+ expect(Object.keys(calls[1].body).sort()).toEqual(['deviceId', 'hostPublicKeyB64', 'popChallenge', 'popProof'])+ })+ it('an old backend (challenge 404) gets the legacy two-field body', async () => {+ const { f, calls } = api(undefined, { challenge: null })+ await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: f })+ expect(calls[1].body).toEqual({ deviceId: 'd', hostPublicKeyB64: PUB })+ })+ it('a transient challenge failure sends NO unproven mint', async () => {+ const { f, calls } = api(undefined, { challenge: () => res(503, {}) })+ const r = await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: f })+ expect(r).toEqual({ ok: false, kind: 'network', status: 503 })+ expect(calls).toHaveLength(1)+ })+ it('a 403 PoP refusal carries its reason', async () => {+ const { f } = api(undefined, { mint: () => res(403, { error: 'pop_required' }) })+ const r = await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: f })+ expect(r).toEqual({ ok: false, kind: 'refused', status: 403, reason: 'pop_required' })+ })++ // --- beyond the brief ---++ it('a pop_required answer to an UNPROVEN mint (challenge 404) is transient, not a refusal', async () => {+ // A reverse proxy answers 404 while the backend redeploys; the legacy mint that follows can land on+ // the fresh backend, which requires a proof from a latched host. Stopping here would stop hosting+ // for good over a redeploy: back off, and the next attempt fetches a fresh challenge.+ const { f, calls } = api(undefined, { challenge: null, mint: () => res(403, { error: 'pop_required' }) })+ const r = await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: f })+ expect(r).toEqual({ ok: false, kind: 'network', status: 403 })+ expect(calls[1].body).toEqual({ deviceId: 'd', hostPublicKeyB64: PUB })+ })+ it('pop_invalid is terminal, proven or not', async () => {+ const proven = api(undefined, { mint: () => res(403, { error: 'pop_invalid' }) })+ expect(await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: proven.f }))+ .toEqual({ ok: false, kind: 'refused', status: 403, reason: 'pop_invalid' })+ const unproven = api(undefined, { challenge: null, mint: () => res(403, { error: 'pop_invalid' }) })+ expect(await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: unproven.f }))+ .toEqual({ ok: false, kind: 'refused', status: 403, reason: 'pop_invalid' })+ })+ it('a 405 challenge is an old backend too; any other challenge failure is transient and sends nothing', async () => {+ const old = api(undefined, { challenge: () => res(405, {}) })+ await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: old.f })+ expect(old.calls.map((c) => c.url)).toEqual(['https://api/v1/relay/challenge', 'https://api/v1/relay/host-token'])+ expect(old.calls[1].body).toEqual({ deviceId: 'd', hostPublicKeyB64: PUB })+ for (const challenge of [() => res(403, { error: 'pop_invalid' }), () => res(200, { challenge: 1 }), () => { throw new Error('ECONNRESET') }]) {+ const t = api(undefined, { challenge })+ const r = await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: t.f })+ expect(r).toMatchObject({ ok: false, kind: 'network' })+ expect(t.calls).toHaveLength(1)+ }+ })+ it('a proof that cannot be computed (a low-order server key) is bad-response and sends no mint', async () => {+ const { f, calls } = api(undefined, { challenge: () => res(200, { challenge: 'c.s', serverPublicKeyB64: Buffer.alloc(32).toString('base64') }) })+ const r = await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: f })+ expect(r).toEqual({ ok: false, kind: 'bad-response' })+ expect(calls).toHaveLength(1)+ })+ it('the proof binds the deviceId: the backend refuses it for another subject', async () => {+ const s = createTestPopServer()+ const { f, calls } = api(s, { mint: () => res(200, { pairingToken: 'T', hostId: 'H', exp: 0 }) })+ await mintHostToken({ apiBase: 'https://api', deviceId: 'dev-A', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: f })+ const b = calls[1].body+ expect(s.verify({ hostPublicKeyB64: PUB, purpose: 'host-token', subject: 'dev-B', popChallenge: b.popChallenge, popProof: b.popProof })).toBe(false)+ expect(s.verify({ hostPublicKeyB64: PUB, purpose: 'host-token', subject: 'dev-A', popChallenge: b.popChallenge, popProof: b.popProof })).toBe(true)+ })+ it('the 8 s timeout covers a challenge that never answers', async () => {+ vi.useFakeTimers()+ const f = ((_u: string, init: RequestInit) => new Promise<Response>((_resolve, reject) => {+ init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))+ })) as unknown as typeof fetch+ const p = mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: f })+ let settled: unknown = 'pending'+ void p.then((r) => { settled = r })+ await vi.advanceTimersByTimeAsync(7_999)+ expect(settled).toBe('pending')+ await vi.advanceTimersByTimeAsync(1)+ expect(settled).toEqual({ ok: false, kind: 'network' })+ })+})diff --git a/src/core/relay/host-token.ts b/src/core/relay/host-token.tsindex 1058b9ca7..c53d39fb7 100644--- a/src/core/relay/host-token.ts+++ b/src/core/relay/host-token.ts@@ -1,15 +1,32 @@// Standing-host token mint for the Server Edition's hosted team relay. Mirrors the desktop's// `mintHostToken` + `tokenTtlMs` in src/main/remote/standing-host.ts (see that file for the measured// incidents: clock skew → 238 mints/hour, refused mints re-minted in a tight loop), minus Electron.-// It sends deviceId only, never an entitlement: relay access is free (CLAUDE.md, "Remote access …-// free, not Pro"), and the backend is the gate.+// It sends its deviceId, never an entitlement: relay access is free (CLAUDE.md, "Remote access …+// free, not Pro"), and the backend is the gate. When the backend supports it, the mint also carries+// a proof that this process holds the host's secret key (relay-pop.ts), so a join code alone can no+// longer mint this host's tokens. Only a challenge answered 404/405 means "this backend predates the+// proof" and gets the legacy two-field mint; any other challenge failure is transient.//// Unlike the desktop copy, which collapses every failure to `null`, this one says WHICH failure it// was, because the scheduler reacts differently to each: a 429 waits at least a minute, a 402/403-// stops minting, anything else backs off and retries.+// stops minting, anything else backs off and retries. One 403 is deliberately NOT terminal: a+// `pop_required` answer to a mint sent WITHOUT a proof because the challenge said 404. A reverse+// proxy answers 404 while the backend redeploys, and the unproven mint that follows can land on the+// fresh backend, which requires a proof from a host it has seen prove before. Stopping there would+// stop hosting for good over a redeploy, so it backs off and the next attempt asks for a challenge+// again.+import { computePopProof, fetchPopChallenge, popRefusalOf, type PopRefusal } from './relay-pop'+export type MintResult =| { ok: true; pairingToken: string; hostId: string; ttlMs: number }- | { ok: false; kind: 'network' | 'rate-limited' | 'refused' | 'bad-response'; retryAfterMs?: number; status?: number }+ | {+ ok: false+ kind: 'network' | 'rate-limited' | 'refused' | 'bad-response'+ retryAfterMs?: number+ status?: number+ /** Set only on a terminal key-proof refusal (a `refused` 403). */+ reason?: PopRefusal+ }const DEFAULT_TTL_MS = 120_000const MINT_TIMEOUT_MS = 8000@@ -34,6 +51,11 @@ export async function mintHostToken(deps: {apiBase: stringdeviceId: stringhostPublicKeyB64: string+ /**+ * The host's X25519 secret key, used only to prove possession (relay-pop.ts); it never leaves+ * this process. Absent = the legacy unproven mint: only tests and pre-proof call sites omit it.+ */+ hostSecretKey?: Uint8Arrayfetch?: typeof fetchnow?: () => number}): Promise<MintResult> {@@ -43,13 +65,45 @@ export async function mintHostToken(deps: {// otherwise leave this mint pending forever, and the scheduler runs one mint at a time.const timer = setTimeout(() => ctrl.abort(), MINT_TIMEOUT_MS)try {+ let proof: { popChallenge: string; popProof: string } | null = null+ if (deps.hostSecretKey) {+ const ch = await fetchPopChallenge({+ apiBase: deps.apiBase,+ hostPublicKeyB64: deps.hostPublicKeyB64,+ purpose: 'host-token',+ fetch: f,+ signal: ctrl.signal+ })+ // Never an unproven mint after a transient failure: to a host the backend has seen prove+ // before, that mint is a 403 which would stop hosting. Back off and ask again.+ if (!ch.ok && !ch.unsupported) return { ok: false, kind: 'network', ...(ch.status ? { status: ch.status } : {}) }+ if (ch.ok) {+ try {+ proof = {+ popChallenge: ch.challenge,+ popProof: computePopProof({+ hostSecretKey: deps.hostSecretKey,+ hostPublicKeyB64: deps.hostPublicKeyB64,+ challenge: ch.challenge,+ serverPublicKeyB64: ch.serverPublicKeyB64,+ purpose: 'host-token',+ subject: deps.deviceId+ })+ }+ } catch {+ // A server key the proof cannot use (malformed, or low-order): the server's fault.+ return { ok: false, kind: 'bad-response' }+ }+ }+ }let res: Responsetry {res = await f(`${deps.apiBase.replace(/\/+$/, '')}/v1/relay/host-token`, {method: 'POST',headers: { 'content-type': 'application/json' },- // EXACTLY these two fields: the production endpoint was verified against this body.- body: JSON.stringify({ deviceId: deps.deviceId, hostPublicKeyB64: deps.hostPublicKeyB64 }),+ // deviceId + host key, plus the key proof when the backend issued a challenge (relay-pop.ts).+ // The two-field form is what a pre-PoP backend was verified against.+ body: JSON.stringify({ deviceId: deps.deviceId, hostPublicKeyB64: deps.hostPublicKeyB64, ...(proof ?? {}) }),signal: ctrl.signal})} catch {@@ -60,7 +114,13 @@ export async function mintHostToken(deps: {const ra = Number(res.headers.get('retry-after'))return { ok: false, kind: 'rate-limited', status: 429, ...(ra > 0 ? { retryAfterMs: ra * 1000 } : {}) }}- if (res.status === 402 || res.status === 403) return { ok: false, kind: 'refused', status: res.status }+ if (res.status === 402 || res.status === 403) {+ const reason = res.status === 403 ? popRefusalOf(403, await res.json().catch(() => null)) : null+ // The challenge said 404/405 and this mint went out unproven: a pop_required here is a backend+ // that came back mid-redeploy (see the header), so it is transient, not a refusal.+ if (reason === 'pop_required' && deps.hostSecretKey && !proof) return { ok: false, kind: 'network', status: 403 }+ return { ok: false, kind: 'refused', status: res.status, ...(reason ? { reason } : {}) }+ }if (!res.ok) return { ok: false, kind: 'network', status: res.status }let json: { pairingToken?: unknown; hostId?: unknown; exp?: unknown } | nulltry {diff --git a/src/core/relay/hosted-scheduler.test.ts b/src/core/relay/hosted-scheduler.test.tsindex 0a651c2b4..1b46e3ebb 100644--- a/src/core/relay/hosted-scheduler.test.ts+++ b/src/core/relay/hosted-scheduler.test.ts@@ -1,6 +1,10 @@// src/core/relay/hosted-scheduler.test.tsimport { describe, it, expect } from 'vitest'+import nacl from 'tweetnacl'import { createHostedScheduler, type MintResult, type SchedulerStatus } from './hosted-scheduler'+import { mintHostToken } from './host-token'+import { POP_REFUSED_MESSAGE } from './relay-pop'+import { createTestPopServer } from './relay-pop.test-server'// Flush with macrotask turns, not a fixed count of microtasks: how many awaits an async mint takes// is an implementation detail the tests must not pin.@@ -406,4 +410,45 @@ describe('hosted scheduler', () => {await h.advance(HOUR)expect(h.mintCalls() - before).toBeLessThanOrEqual(200)})++ // --- relay proof of possession (relay-pop.ts) ---++ it('a PoP refusal stops with backend-refused and the proof message', async () => {+ const h = harness([{ ok: false, kind: 'refused', status: 403, reason: 'pop_required' }])+ h.s.start(); await flush()+ expect(h.s.status()).toMatchObject({ state: 'backend-refused', lastError: POP_REFUSED_MESSAGE })+ expect(h.timers).toHaveLength(0)+ })++ it('a pop_required answer to an unproven mint (challenge 404 mid-redeploy) backs off and proves on the retry', async () => {+ // The real mint against a fake API: while the backend redeploys its proxy answers the challenge+ // 404, the unproven mint lands on the fresh backend and earns pop_required. That must be a retry,+ // never backend-refused — and the retry asks for a fresh challenge and proves.+ const keys = nacl.box.keyPair()+ const pub = Buffer.from(keys.publicKey).toString('base64')+ const pop = createTestPopServer()+ let redeploying = true+ const urls: string[] = []+ const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status })+ const f = (async (u: string, init: RequestInit) => {+ urls.push(u)+ const body = JSON.parse(String(init.body)) as Record<string, unknown>+ if (u.endsWith('/v1/relay/challenge')) return redeploying ? json(404, {}) : json(200, pop.issue(pub, 'host-token'))+ if (!pop.verify({ hostPublicKeyB64: pub, purpose: 'host-token', subject: String(body.deviceId ?? ''), popChallenge: body.popChallenge, popProof: body.popProof }))+ return json(403, { error: 'pop_required' })+ return json(200, { pairingToken: 'T', hostId: 'H', exp: 0 })+ }) as typeof fetch+ const mint = () => mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: pub, hostSecretKey: keys.secretKey, fetch: f })+ const h = harness([mint, mint])+ h.s.start(); await flush()+ expect(h.s.status()).toMatchObject({ state: 'running', lastError: 'network (403)' })+ expect(h.timers).toHaveLength(1) // the backoff owns the next mint+ expect(h.opened).toHaveLength(0)+ redeploying = false+ await h.advance(1000); await flush()+ expect(h.opened).toHaveLength(1)+ expect(urls.map((u) => u.replace('https://api', ''))).toEqual([+ '/v1/relay/challenge', '/v1/relay/host-token', '/v1/relay/challenge', '/v1/relay/host-token'+ ])+ })})diff --git a/src/core/relay/hosted-scheduler.ts b/src/core/relay/hosted-scheduler.tsindex 85519999e..a2d4c061c 100644--- a/src/core/relay/hosted-scheduler.ts+++ b/src/core/relay/hosted-scheduler.ts@@ -12,11 +12,14 @@// - at most MINT_BUDGET_PER_HOUR successful mints in any rolling hour, whatever asks for them. The// backend's free limit is 240/h, the 15 s backoff ceiling alone reaches exactly 240/h, and a peer// joining and leaving every 10 s asks for 360/h — so no per-path rule can hold the line on its own;-// - a 429 waits at least 60 s (longer if Retry-After says so); a 402/403 stops minting;+// - a 429 waits at least 60 s (longer if Retry-After says so); a 402/403 stops minting (a refused+// key proof names itself in `lastError`; a 403 host-token.ts judges transient arrives as+// `network` and backs off);// - while a backoff timer is armed it owns the next mint: nothing else may mint early.// Everything the injected deps can throw is caught: a scheduler that swallowed an exception would sit// in 'running' with no listener and no timer, i.e. hosting silently dead until a restart.import type { MintResult } from './host-token'+import { POP_REFUSED_MESSAGE } from './relay-pop'export type { MintResult } from './host-token'const REFRESH_LEAD_MS = 30_000@@ -182,7 +185,8 @@ export function createHostedScheduler(deps: SchedulerDeps, now: () => number) {if (r.ok) mints.push(now()) // counted even if we were stopped meanwhile: the backend counted itif (state !== 'running') returnif (!r.ok) {- lastError = threw ?? (r.kind + (r.status ? ` (${r.status})` : ''))+ // A key-proof refusal says what to do about it (update, or `team rotate-key`); `refused (403)` would not.+ lastError = threw ?? (r.reason ? POP_REFUSED_MESSAGE : r.kind + (r.status ? ` (${r.status})` : ''))if (r.kind === 'refused') {state = 'backend-refused'emit()diff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.tsindex 29656dcb8..8cce38e15 100644--- a/src/core/relay/hosted-service.test.ts+++ b/src/core/relay/hosted-service.test.ts@@ -84,6 +84,7 @@ function world(opts: WorldOpts = {}) {}const peersT: RelayTransport[] = []let mints = 0+ let challenges = 0const armed: Armed[] = []const timerDeps: Pick<HostedServiceDeps, 'setTimeout' | 'clearTimeout'> = opts.recordTimers? {@@ -101,7 +102,13 @@ function world(opts: WorldOpts = {}) {// Terminal sessions: 'sess-shared' runs n-shared (project P), 'sess-other' runs n-other (Q).nodeOfSession: opts.nodeOfSession ?? ((sid) => (sid === 'sess-shared' ? 'n-shared' : sid === 'sess-other' ? 'n-other' : undefined)),projectCwd: () => '/srv/app',- fetch: (async () => { mints++; return new Response(JSON.stringify({ pairingToken: 'T', hostId: 'H', exp: 0 }), { status: 200 }) }) as typeof fetch,+ // Routed by URL: the key-proof challenge answers 404 (a pre-proof backend, so the legacy mint+ // follows), and only host-token calls count as mints.+ fetch: (async (u: string | URL | Request) => {+ if (String(u).endsWith('/v1/relay/challenge')) { challenges++; return new Response('{}', { status: 404 }) }+ mints+++ return new Response(JSON.stringify({ pairingToken: 'T', hostId: 'H', exp: 0 }), { status: 200 })+ }) as typeof fetch,transport: () => { const { hostT, peerT } = transportPair(); peersT.push(peerT); return hostT },...(opts.now ? { now: opts.now } : {}),...(opts.monotonicNow ? { monotonicNow: opts.monotonicNow } : {}),@@ -155,7 +162,7 @@ function world(opts: WorldOpts = {}) {}const teamOnDisk = (): Array<{ pubkeyB64: string; role: string; addedBy: string; addedAt: string; label: string }> =>JSON.parse(fs.readFileSync(path.join(dataDir, 'relay', 'team.json'), 'utf-8')).peers- return { svc, join, rawPeer, sinks, dispatched, casts, dataDir, armed, teamOnDisk, mints: () => mints }+ return { svc, join, rawPeer, sinks, dispatched, casts, dataDir, armed, teamOnDisk, mints: () => mints, challenges: () => challenges }}async function ownerOnline(w: ReturnType<typeof world>, ownerKeys = genKeyPair()) {@@ -898,6 +905,15 @@ describe('hosted service — lifecycle', () => {expect(w.svc.status().scheduler?.idle).toBe(1)})+ it('the hosted mint holds the host key: it asks for a key-proof challenge before every mint', async () => {+ const w = world()+ await w.svc.init()+ expect(await w.svc.start()).toBe('started')+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))+ expect(w.challenges()).toBe(1)+ expect(w.mints()).toBe(1)+ })+it('stop cuts every session and pending request; start brings hosting back', async () => {const w = world()const owner = await ownerOnline(w)diff --git a/src/core/relay/hosted-service.ts b/src/core/relay/hosted-service.tsindex 4fcbf267c..ab624d490 100644--- a/src/core/relay/hosted-service.ts+++ b/src/core/relay/hosted-service.ts@@ -552,7 +552,15 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {const s = createHostedScheduler({mint: () =>- mintHostToken({ apiBase: deps.apiBase, deviceId: deps.deviceId, hostPublicKeyB64: addr.hostPublicKeyB64, fetch: deps.fetch, now: wallNow }),+ mintHostToken({+ apiBase: deps.apiBase,+ deviceId: deps.deviceId,+ hostPublicKeyB64: addr.hostPublicKeyB64,+ // Proves this process holds the host key (relay-pop.ts); the key never leaves it.+ hostSecretKey: hostKeys.secretKey,+ fetch: deps.fetch,+ now: wallNow+ }),open: (token, ev) => openListener(hostKeys, token, ev),setTimeout: (fn, ms) => setT(fn, ms),clearTimeout: (h) => clearT(h)diff --git a/src/server/hosted-e2e.test.ts b/src/server/hosted-e2e.test.tsindex ebdef1414..0b484b547 100644--- a/src/server/hosted-e2e.test.ts+++ b/src/server/hosted-e2e.test.ts@@ -50,6 +50,7 @@ import { transportPair } from '../core/relay/transport-pair'import { connectRelayClient, type RelayClientSession } from '../core/relay/relay-client'import { decodeJoinCode, type JoinCode } from '../core/relay/join-code'import { genKeyPair, publicKeyToB64, type KeyPair } from '../core/relay/e2ee'+import { createTestPopServer } from '../core/relay/relay-pop.test-server'import type { RelayTransport } from '../core/relay/relay-socket'import { IPC } from '../shared/ipc'import { mutationKey } from '../shared/canvas-order'@@ -385,14 +386,29 @@ describe.skipIf(process.platform === 'win32')('hosted team relay, end to end onlisteners.push(peerT)return hostT}- // The host-token API. A token good for an hour, so no listener refresh lands mid-test.- const mints: Array<{ url: string; body: { deviceId?: string; hostPublicKeyB64?: string } }> = []+ // The host-token API, proof of possession included: a byte-exact mirror of the backend issues+ // the challenge and refuses a mint whose proof does not verify, so a host that stopped proving it+ // holds its key (or proved the wrong thing) never gets a listener. A token good for an hour, so+ // no listener refresh lands mid-test.+ const popServer = createTestPopServer()+ const mints: Array<{ url: string; body: Record<string, unknown> }> = []const relayTestFetch = (async (url: string | URL | Request, init?: RequestInit) => {- mints.push({ url: String(url), body: JSON.parse(String(init?.body ?? '{}')) })- return new Response(- JSON.stringify({ pairingToken: 'relay-token', hostId: 'H', exp: Math.floor(Date.now() / 1000) + 3600 }),- { status: 200, headers: { date: new Date().toUTCString() } }- )+ const body = JSON.parse(String(init?.body ?? '{}')) as Record<string, unknown>+ const json = (status: number, payload: unknown) =>+ new Response(JSON.stringify(payload), { status, headers: { date: new Date().toUTCString() } })+ if (String(url).endsWith('/v1/relay/challenge')) {+ return json(200, popServer.issue(String(body.hostPublicKeyB64), body.purpose as 'host-token'))+ }+ mints.push({ url: String(url), body })+ const proven = popServer.verify({+ hostPublicKeyB64: String(body.hostPublicKeyB64),+ purpose: 'host-token',+ subject: typeof body.deviceId === 'string' ? body.deviceId : '',+ popChallenge: body.popChallenge,+ popProof: body.popProof+ })+ if (!proven) return json(403, { error: 'pop_invalid' })+ return json(200, { pairingToken: 'relay-token', hostId: 'H', exp: Math.floor(Date.now() / 1000) + 3600 })}) as typeof fetch// The mint's production twin of the relay trap above: if `relayTestFetch` stopped being plumbed// through, the mint would fall back to the global fetch — which refuses here instead of minting@@ -462,10 +478,15 @@ describe.skipIf(process.platform === 'win32')('hosted team relay, end to end onconst owner = teammate(code, await step('first listener', listeners.next()), ownerKeys, true)teardown.push(() => owner.c.close())await step('owner approved', owner.approved)- // The host minted that listener's token for THIS host key, through the seam.+ // The host minted that listener's token for THIS host key, through the seam, proving it holds it.expect(mints[0]).toMatchObject({url: expect.stringMatching(/\/v1\/relay\/host-token$/),- body: { hostPublicKeyB64: code.hostPublicKeyB64, deviceId: code.hostDeviceId }+ body: {+ hostPublicKeyB64: code.hostPublicKeyB64,+ deviceId: code.hostDeviceId,+ popChallenge: expect.any(String),+ popProof: expect.any(String)+ }})// Even the owner cannot save the host's workspace over the relay: shared content travels as