Skip to content

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.

fix(relay): hosted mint fix round — challenge 429/2xx, team status, hosted-join fake

review8052943e2117
diff --git a/src/core/relay/host-token.test.ts b/src/core/relay/host-token.test.ts
index f2e391cc0..5fd4e1276 100644
--- a/src/core/relay/host-token.test.ts
+++ b/src/core/relay/host-token.test.ts
@@ -159,18 +159,60 @@ describe('host token proof of possession', () => {
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 pop_required answer to an UNPROVEN mint after a 405 challenge is transient too', async () => {
+ const { f, calls } = api(undefined, { challenge: () => res(405, {}), 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('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') }]) {
+ for (const challenge of [() => res(403, { error: 'pop_invalid' }), () => res(502, {}), () => { 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 rate-limited challenge (429) is rate-limited, so the scheduler waits its 60 s floor, and sends nothing', async () => {
+ // Several hosts behind one NAT share /challenge's per-IP limit.
+ const { f, calls } = api(undefined, { challenge: () => res(429, {}) })
+ const r = await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: f })
+ expect(r).toEqual({ ok: false, kind: 'rate-limited', status: 429 })
+ expect(calls).toHaveLength(1)
+ })
+ it('a 2xx challenge the host cannot use is bad-response, not network, and sends nothing', async () => {
+ for (const body of [{ challenge: 1, serverPublicKeyB64: 'x' }, { pairingToken: 'T' }, null]) {
+ const { f, calls } = api(undefined, { challenge: () => res(200, body) })
+ 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)
+ }
+ const broken = { ...res(200, null), json: async () => { throw new SyntaxError('Unexpected token <') } } as Response
+ const t = api(undefined, { challenge: () => broken })
+ expect(await mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: PUB, hostSecretKey: keys.secretKey, fetch: t.f }))
+ .toEqual({ ok: false, kind: 'bad-response' })
+ })
+ it('a challenge body that stalls until the 8 s timeout is network (a timeout), not bad-response', async () => {
+ vi.useFakeTimers()
+ const f = (async (u: string, init: RequestInit) => {
+ if (!u.endsWith('/v1/relay/challenge')) throw new Error('no mint may follow')
+ return {
+ ...res(200, null),
+ json: () => new Promise((_resolve, reject) => {
+ init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))
+ })
+ } as Response
+ }) 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(8_000)
+ expect(settled).toEqual({ ok: false, kind: 'network' })
+ })
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 })
diff --git a/src/core/relay/host-token.ts b/src/core/relay/host-token.ts
index c53d39fb7..ea53edb76 100644
--- a/src/core/relay/host-token.ts
+++ b/src/core/relay/host-token.ts
@@ -10,7 +10,7 @@
// 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. One 403 is deliberately NOT terminal: a
-// `pop_required` answer to a mint sent WITHOUT a proof because the challenge said 404. A reverse
+// `pop_required` answer to a mint sent WITHOUT a proof because the challenge said 404/405. 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
@@ -66,6 +66,9 @@ export async function mintHostToken(deps: {
const timer = setTimeout(() => ctrl.abort(), MINT_TIMEOUT_MS)
try {
let proof: { popChallenge: string; popProof: string } | null = null
+ // True only when a challenge was asked for and answered 404/405: the one case this mint goes out
+ // unproven although we hold the key (see the header on what a 403 then means).
+ let sentUnproven = false
if (deps.hostSecretKey) {
const ch = await fetchPopChallenge({
apiBase: deps.apiBase,
@@ -76,7 +79,18 @@ export async function mintHostToken(deps: {
})
// 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 && !ch.unsupported) {
+ // /challenge has its own per-IP limit, which several hosts behind one NAT share: take the
+ // scheduler's 60 s floor rather than the short network backoff.
+ if (ch.status === 429) return { ok: false, kind: 'rate-limited', status: 429 }
+ // A 2xx that is not a usable challenge is the server's fault, unless the body read was cut
+ // short by our own timeout.
+ if (ch.status !== undefined && ch.status >= 200 && ch.status < 300) {
+ return ctrl.signal.aborted ? { ok: false, kind: 'network' } : { ok: false, kind: 'bad-response' }
+ }
+ return { ok: false, kind: 'network', ...(ch.status ? { status: ch.status } : {}) }
+ }
+ if (!ch.ok && ch.unsupported) sentUnproven = true
if (ch.ok) {
try {
proof = {
@@ -118,7 +132,7 @@ export async function mintHostToken(deps: {
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 }
+ if (reason === 'pop_required' && sentUnproven) 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 }
diff --git a/src/core/relay/hosted-scheduler.test.ts b/src/core/relay/hosted-scheduler.test.ts
index 1b46e3ebb..0d119357c 100644
--- a/src/core/relay/hosted-scheduler.test.ts
+++ b/src/core/relay/hosted-scheduler.test.ts
@@ -451,4 +451,22 @@ describe('hosted scheduler', () => {
'/v1/relay/challenge', '/v1/relay/host-token', '/v1/relay/challenge', '/v1/relay/host-token'
])
})
+
+ it('a rate-limited challenge (429, shared per-IP limit) waits the 60 s floor before the next mint', async () => {
+ const keys = nacl.box.keyPair()
+ const pub = Buffer.from(keys.publicKey).toString('base64')
+ let challenges = 0
+ const f = (async (u: string) => {
+ if (u.endsWith('/v1/relay/challenge')) { challenges++; return new Response('{}', { status: 429 }) }
+ throw new Error('no mint may follow a refused challenge')
+ }) 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: 'rate-limited (429)' })
+ await h.advance(59_999)
+ expect(challenges).toBe(1)
+ await h.advance(1)
+ expect(challenges).toBe(2)
+ })
})
diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.ts
index 0b447285e..cef89fb95 100644
--- a/src/main/remote/hosted-join.test.ts
+++ b/src/main/remote/hosted-join.test.ts
@@ -675,7 +675,13 @@ function hostedWorld() {
const svc = createHostedService({
dataDir: dir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'host-dev', hostLabel: 'box',
attach, projectsOfNode: () => ['P'], nodeOfSession: () => undefined, projectCwd: () => '/srv/app',
- fetch: (async () => new Response(JSON.stringify({ pairingToken: 'T', hostId: 'H', exp: 0 }), { status: 200 })) as typeof fetch,
+ // Routed by URL: the hosted mint asks for a key-proof challenge first (relay-pop.ts). A 404 is a
+ // pre-proof backend, so the legacy mint follows; answering it with a token body would read as a
+ // malformed challenge and no listener would ever open.
+ fetch: (async (u: string | URL | Request) =>
+ String(u).endsWith('/v1/relay/challenge')
+ ? new Response('{}', { status: 404 })
+ : 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 }
})
live.push({ svc, dir })
diff --git a/src/server/team-cli.test.ts b/src/server/team-cli.test.ts
index 4b97bb5e9..e7f2e90d0 100644
--- a/src/server/team-cli.test.ts
+++ b/src/server/team-cli.test.ts
@@ -6,6 +6,7 @@ import { parseTeamArgv, runTeamCli, describeStatus, teamArgv } from './team-cli'
import { startTeamAdmin, adminSocketPath, type AdminStatusResult } from '../core/relay/team-admin'
import { genKeyPair, publicKeyToB64 } from '../core/relay/e2ee'
import type { HostedService, HostedStatus } from '../core/relay/hosted-service'
+import { POP_REFUSED_MESSAGE } from '../core/relay/relay-pop'
const KEY = publicKeyToB64(genKeyPair().publicKey)
@@ -113,6 +114,16 @@ describe('describeStatus', () => {
expect(text).toMatch(/restart/)
})
+ it('a refused key proof prints its advice on its own line, and says how hosting comes back', () => {
+ const lines = describeStatus(idleStatus({ state: 'backend-refused', idle: 0, lastError: POP_REFUSED_MESSAGE }))
+ expect(lines[0]).toBe('Hosting: STOPPED — the nodeterm API refused to issue relay tokens.')
+ expect(lines[1]).toBe(` ${POP_REFUSED_MESSAGE}`)
+ expect(lines[2]).toBe(' Hosting stays off until nodeterm is updated or the key is rotated.')
+ const text = lines.join('\n')
+ expect(text).not.toMatch(/\.\)\./) // no "…replaced.)." double punctuation
+ expect(text).not.toMatch(/until the service restarts/) // `team rotate-key` restarts hosting in place
+ })
+
it('off states say why, and still list the members', () => {
const peers = [{ label: 'Enes', role: 'owner' as const, connected: false }, { label: '', role: 'viewer' as const, connected: false }]
const unreadable = describeStatus({
diff --git a/src/server/team-cli.ts b/src/server/team-cli.ts
index 4b5679d6b..cba8864ce 100644
--- a/src/server/team-cli.ts
+++ b/src/server/team-cli.ts
@@ -17,6 +17,7 @@ import {
type AdminRotateResult,
type AdminStatusResult
} from '../core/relay/team-admin'
+import { POP_REFUSED_MESSAGE } from '../core/relay/relay-pop'
// One rule for what never reaches the admin's terminal: the same characters a label may not
// contain (C0/C1 controls, DEL, and the text-direction controls). Server-supplied strings can carry
@@ -222,6 +223,14 @@ export function describeStatus(result: AdminStatusResult): string[] {
? OFF_TEXT[reason]
: 'hosting is not running.'
lines.push(`Hosting: OFF — ${text}`)
+ } else if (sched.state === 'backend-refused' && lastError === POP_REFUSED_MESSAGE) {
+ // The advice is a sentence of its own, and it is how hosting comes back: `team rotate-key`
+ // restarts it in place, so "until the service restarts" would be wrong here.
+ lines.push(
+ 'Hosting: STOPPED — the nodeterm API refused to issue relay tokens.',
+ ` ${POP_REFUSED_MESSAGE}`,
+ ' Hosting stays off until nodeterm is updated or the key is rotated.'
+ )
} else if (sched.state === 'backend-refused') {
lines.push(
`Hosting: STOPPED — the nodeterm API refused to issue relay tokens${lastError ? ` (${lastError})` : ''}. ` +