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.

feat(relay): host key proof-of-possession client module

reviewadb7ae001ccc
diff --git a/src/core/relay/relay-pop-vector.json b/src/core/relay/relay-pop-vector.json
new file mode 100644
index 000000000..b47675250
--- /dev/null
+++ b/src/core/relay/relay-pop-vector.json
@@ -0,0 +1,38 @@
+{
+ "popSecret": "test-pop-secret-0123456789abcdef0123456789",
+ "hostSecretKeyB64": "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA=",
+ "hostPublicKeyB64": "B6N8vBQgk8i3VdwbEOhstCY3StFqqFPtC9/AsrhtHHw=",
+ "hostId": "qqj_9wO1CyKX9PbhNQj3JC",
+ "nonce": "oKGio6SlpqeoqaqrrK2urw",
+ "cases": [
+ {
+ "purpose": "host-token",
+ "subject": "device-123",
+ "exp": 1790000000,
+ "challenge": "eyJ2IjoxLCJob3N0SWQiOiJxcWpfOXdPMUN5S1g5UGJoTlFqM0pDIiwicHVycG9zZSI6Imhvc3QtdG9rZW4iLCJub25jZSI6Im9LR2lvNlNscHFlb3FhcXJySzJ1cnciLCJleHAiOjE3OTAwMDAwMDB9.kdNHxQO-4E_okTEnGGBxvAJV0oZvzBRp5VWp19j1YQE",
+ "serverPublicKeyB64": "QLXQx6cW4EyIiSe3r+GlJd5CgIY4lvJnxnImo5WjKV4=",
+ "proof": "-bMvfUCdybg9xJEh5u5uVehucQgOkOxDf2kz6YAeeco"
+ },
+ {
+ "purpose": "host-token",
+ "subject": "",
+ "exp": 1790000000,
+ "challenge": "eyJ2IjoxLCJob3N0SWQiOiJxcWpfOXdPMUN5S1g5UGJoTlFqM0pDIiwicHVycG9zZSI6Imhvc3QtdG9rZW4iLCJub25jZSI6Im9LR2lvNlNscHFlb3FhcXJySzJ1cnciLCJleHAiOjE3OTAwMDAwMDB9.kdNHxQO-4E_okTEnGGBxvAJV0oZvzBRp5VWp19j1YQE",
+ "serverPublicKeyB64": "QLXQx6cW4EyIiSe3r+GlJd5CgIY4lvJnxnImo5WjKV4=",
+ "proof": "EgIK3YPJ2TcS6elaFqJiTQ-Dbsz-QNAqDRh6yDBo0UA"
+ },
+ {
+ "purpose": "push",
+ "subject": "desk-1",
+ "exp": 1790000000,
+ "challenge": "eyJ2IjoxLCJob3N0SWQiOiJxcWpfOXdPMUN5S1g5UGJoTlFqM0pDIiwicHVycG9zZSI6InB1c2giLCJub25jZSI6Im9LR2lvNlNscHFlb3FhcXJySzJ1cnciLCJleHAiOjE3OTAwMDAwMDB9.eqUI3oXLoyLAgPSkL4Jbo5OniyqIeE6dNnZylp5tUvE",
+ "serverPublicKeyB64": "QLXQx6cW4EyIiSe3r+GlJd5CgIY4lvJnxnImo5WjKV4=",
+ "proof": "TAQpPbO8V_4T4TRsFcjDAy_aSGSlmXCoP2dhN42BjQw"
+ }
+ ],
+ "hostAuth": {
+ "hostDeviceId": "desk-1",
+ "exp": 1790000900,
+ "token": "eyJ2IjoxLCJ0eXAiOiJob3N0LWF1dGgiLCJob3N0SWQiOiJxcWpfOXdPMUN5S1g5UGJoTlFqM0pDIiwiaG9zdERldmljZUlkIjoiZGVzay0xIiwiZXhwIjoxNzkwMDAwOTAwfQ.AIpU0Dmoo6FWcw7PiV9NTuICq0KzC0FZgl-xtjJQDY4"
+ }
+}
diff --git a/src/core/relay/relay-pop.test-server.ts b/src/core/relay/relay-pop.test-server.ts
new file mode 100644
index 000000000..109a9a0a3
--- /dev/null
+++ b/src/core/relay/relay-pop.test-server.ts
@@ -0,0 +1,101 @@
+// Test-only mirror of nodeterm-server's src/lib/relay-pop.ts (issue + verify). Pinned to the same bytes by relay-pop-vector.json; never import from product code.
+//
+// Tests and test fakes use it to answer `/v1/relay/challenge` and to check a proof the way the real
+// backend does (docs/hosted-team-relay.md), so a client that proves something the backend would
+// refuse goes red here instead of in production. The hostId hash is computed inline rather than via
+// ./relay-id: a mirror of the BACKEND must not silently follow a drift in the client's own derivation.
+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
+import nacl from 'tweetnacl'
+import type { PopPurpose } from './relay-pop'
+
+const CHALLENGE_LABEL = 'nodeterm/relay-pop/challenge/v1'
+const EPHEMERAL_LABEL = 'nodeterm/relay-pop/eph/v1'
+const PROOF_LABEL = 'nodeterm/relay-pop/v1'
+const PURPOSES: readonly PopPurpose[] = ['host-token', 'push']
+const CHALLENGE_TTL_S = 60
+const SKEW_S = 5
+const TOKEN_MAX = 2000
+
+const b64u = (b: Uint8Array): string => Buffer.from(b).toString('base64url')
+const hmac = (key: Buffer | Uint8Array | string, data: string): Buffer => createHmac('sha256', key).update(data).digest()
+
+function decodeHostKey(b64: unknown): Uint8Array | null {
+ if (typeof b64 !== 'string' || !/^[A-Za-z0-9+/]{43}=$/.test(b64)) return null
+ const raw = Buffer.from(b64, 'base64')
+ return raw.length === 32 ? new Uint8Array(raw) : null
+}
+
+const hostIdOf = (hostPub: Uint8Array): string => createHash('sha256').update(hostPub).digest('base64url').slice(0, 22)
+
+function isZero(b: Uint8Array): boolean {
+ let acc = 0
+ for (const x of b) acc |= x
+ return acc === 0
+}
+
+function safeEqual(a: string, b: string): boolean {
+ const x = Buffer.from(a)
+ const y = Buffer.from(b)
+ return x.length === y.length && timingSafeEqual(x, y)
+}
+
+export function createTestPopServer(
+ secret = 'test-pop-secret-'.padEnd(40, 'x'),
+ opts: { now?: () => number; nonce?: Buffer } = {}
+): {
+ issue(hostPublicKeyB64: string, purpose: PopPurpose): { challenge: string; serverPublicKeyB64: string; exp: number }
+ verify(i: { hostPublicKeyB64: string; purpose: PopPurpose; subject: string; popChallenge: unknown; popProof: unknown }): boolean
+} {
+ const now = opts.now ?? Date.now
+ const nowS = (): number => Math.floor(now() / 1000)
+ const used = new Set<string>()
+
+ const seal = (part: string): string => b64u(hmac(secret, `${CHALLENGE_LABEL}\n${part}`))
+ const serverSecretFor = (nonce: string): Uint8Array => new Uint8Array(hmac(secret, `${EPHEMERAL_LABEL}\n${nonce}`))
+
+ function open(token: unknown): Record<string, unknown> | null {
+ if (typeof token !== 'string' || token.length > TOKEN_MAX) return null
+ const dot = token.indexOf('.')
+ if (dot <= 0 || dot !== token.lastIndexOf('.')) return null
+ const part = token.slice(0, dot)
+ if (!safeEqual(token.slice(dot + 1), seal(part))) return null
+ try {
+ const v: unknown = JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
+ return v && typeof v === 'object' ? (v as Record<string, unknown>) : null
+ } catch {
+ return null
+ }
+ }
+
+ return {
+ issue(hostPublicKeyB64, purpose) {
+ const hostPub = decodeHostKey(hostPublicKeyB64)
+ // The backend answers null (→ 400) here; a test that sends a bad key should fail loudly.
+ if (!hostPub || !PURPOSES.includes(purpose)) throw new Error('relay-pop test server: bad host key or purpose')
+ const nonce = b64u(opts.nonce ?? randomBytes(16))
+ const exp = nowS() + CHALLENGE_TTL_S
+ const part = b64u(Buffer.from(JSON.stringify({ v: 1, hostId: hostIdOf(hostPub), purpose, nonce, exp }), 'utf8'))
+ return {
+ challenge: `${part}.${seal(part)}`,
+ serverPublicKeyB64: Buffer.from(nacl.scalarMult.base(serverSecretFor(nonce))).toString('base64'),
+ exp
+ }
+ },
+ verify({ hostPublicKeyB64, purpose, subject, popChallenge, popProof }) {
+ const hostPub = decodeHostKey(hostPublicKeyB64)
+ if (!hostPub || typeof popProof !== 'string' || typeof subject !== 'string') return false
+ const c = open(popChallenge)
+ if (!c || c.v !== 1 || c.purpose !== purpose || typeof c.nonce !== 'string' || typeof c.exp !== 'number') return false
+ if (c.hostId !== hostIdOf(hostPub)) return false
+ if (c.exp + SKEW_S < nowS()) return false
+ const shared = nacl.scalarMult(serverSecretFor(c.nonce), hostPub)
+ if (isZero(shared)) return false // a low-order "key" gives everyone the same secret
+ const key = hmac(Buffer.from(shared), PROOF_LABEL)
+ const expected = b64u(hmac(key, [popChallenge as string, purpose, subject, hostPublicKeyB64].join('\n')))
+ if (!safeEqual(popProof, expected)) return false
+ if (used.has(c.nonce)) return false // single-use
+ used.add(c.nonce)
+ return true
+ }
+ }
+}
diff --git a/src/core/relay/relay-pop.test.ts b/src/core/relay/relay-pop.test.ts
new file mode 100644
index 000000000..5a41b87d1
--- /dev/null
+++ b/src/core/relay/relay-pop.test.ts
@@ -0,0 +1,135 @@
+import { createHmac } from 'node:crypto'
+import nacl from 'tweetnacl'
+import { describe, expect, it } from 'vitest'
+import vector from './relay-pop-vector.json'
+import { computePopProof, fetchPopChallenge, popProverFor, popRefusalOf, type PopPurpose } from './relay-pop'
+import { createTestPopServer } from './relay-pop.test-server'
+
+const secretKey = new Uint8Array(Buffer.from(vector.hostSecretKeyB64, 'base64'))
+
+describe('relay-pop: the shared vector (byte contract with nodeterm-server)', () => {
+ for (const c of vector.cases) {
+ it(`computes the vector proof (${c.purpose}, "${c.subject}")`, () => {
+ expect(computePopProof({ hostSecretKey: secretKey, hostPublicKeyB64: vector.hostPublicKeyB64, challenge: c.challenge, serverPublicKeyB64: c.serverPublicKeyB64, purpose: c.purpose as PopPurpose, subject: c.subject })).toBe(c.proof)
+ })
+ }
+ it('the test server issues the vector challenge (so fakes mirror the backend)', () => {
+ const s = createTestPopServer(vector.popSecret, { now: () => (vector.cases[0].exp - 60) * 1000, nonce: Buffer.from(vector.nonce, 'base64url') })
+ expect(s.issue(vector.hostPublicKeyB64, 'host-token')).toEqual({ challenge: vector.cases[0].challenge, serverPublicKeyB64: vector.cases[0].serverPublicKeyB64, exp: vector.cases[0].exp })
+ })
+})
+
+describe('computePopProof', () => {
+ it('refuses a degenerate (all-zero) server key', () => {
+ expect(() => computePopProof({ hostSecretKey: secretKey, hostPublicKeyB64: vector.hostPublicKeyB64, challenge: 'c', serverPublicKeyB64: Buffer.alloc(32).toString('base64'), purpose: 'push', subject: '' })).toThrow(/degenerate/)
+ })
+ it('refuses a malformed server key', () => {
+ expect(() => computePopProof({ hostSecretKey: secretKey, hostPublicKeyB64: vector.hostPublicKeyB64, challenge: 'c', serverPublicKeyB64: 'AAAA', purpose: 'push', subject: '' })).toThrow()
+ })
+ it('popProverFor proves with its key pair, and the test server accepts it', () => {
+ const k = nacl.box.keyPair()
+ const pub = Buffer.from(k.publicKey).toString('base64')
+ const s = createTestPopServer()
+ const ch = s.issue(pub, 'host-token')
+ const proof = popProverFor(k)({ challenge: ch.challenge, serverPublicKeyB64: ch.serverPublicKeyB64, purpose: 'host-token', subject: 'd' })
+ expect(s.verify({ hostPublicKeyB64: pub, purpose: 'host-token', subject: 'd', popChallenge: ch.challenge, popProof: proof })).toBe(true)
+ })
+})
+
+// The fakes in later tests are only as strict as this mirror: each refusal below is one the backend
+// makes, and each would let a wrong client proof through if the mirror dropped it.
+describe('createTestPopServer refuses what the backend refuses', () => {
+ const keys = nacl.box.keyPair()
+ const pub = Buffer.from(keys.publicKey).toString('base64')
+ const T = 1_000_000
+ const at = (s: number) => () => s * 1000
+ const prove = (ch: { challenge: string; serverPublicKeyB64: string }, purpose: PopPurpose, subject: string, k = keys) =>
+ popProverFor(k)({ challenge: ch.challenge, serverPublicKeyB64: ch.serverPublicKeyB64, purpose, subject })
+
+ it('accepts once, refuses the same nonce again', () => {
+ const s = createTestPopServer(undefined, { now: at(T) })
+ const ch = s.issue(pub, 'push')
+ const input = { hostPublicKeyB64: pub, purpose: 'push' as const, subject: 'x', popChallenge: ch.challenge, popProof: prove(ch, 'push', 'x') }
+ expect(s.verify(input)).toBe(true)
+ expect(s.verify(input)).toBe(false)
+ })
+ it('refuses another subject, a tampered challenge, and a challenge sealed under another secret', () => {
+ const s = createTestPopServer(undefined, { now: at(T) })
+ const ch = s.issue(pub, 'host-token')
+ const base = { hostPublicKeyB64: pub, purpose: 'host-token' as const, subject: 'd', popChallenge: ch.challenge, popProof: prove(ch, 'host-token', 'd') }
+ expect(s.verify({ ...base, subject: 'e' })).toBe(false)
+ expect(s.verify({ ...base, popChallenge: ch.challenge.replace(/.$/, (x) => (x === 'A' ? 'B' : 'A')) })).toBe(false)
+ expect(createTestPopServer('t'.repeat(40), { now: at(T) }).verify(base)).toBe(false)
+ expect(s.verify(base)).toBe(true)
+ })
+ it('refuses a re-written challenge payload (extended exp), even with the key holder\'s proof over it', () => {
+ const ch = createTestPopServer(undefined, { now: at(T) }).issue(pub, 'push')
+ const [part, sig] = ch.challenge.split('.')
+ const body = JSON.parse(Buffer.from(part, 'base64url').toString('utf8')) as { exp: number }
+ const forged = `${Buffer.from(JSON.stringify({ ...body, exp: body.exp + 3600 }), 'utf8').toString('base64url')}.${sig}`
+ const late = createTestPopServer(undefined, { now: at(T + 600) })
+ expect(late.verify({ hostPublicKeyB64: pub, purpose: 'push', subject: 'x', popChallenge: forged, popProof: prove({ ...ch, challenge: forged }, 'push', 'x') })).toBe(false)
+ })
+ it('refuses a challenge issued for another purpose, even with a proof made over it', () => {
+ const s = createTestPopServer(undefined, { now: at(T) })
+ const ch = s.issue(pub, 'push')
+ expect(s.verify({ hostPublicKeyB64: pub, purpose: 'host-token', subject: 'd', popChallenge: ch.challenge, popProof: prove(ch, 'host-token', 'd') })).toBe(false)
+ })
+ it('refuses a challenge issued for another host key, even with that key\'s own valid proof', () => {
+ const s = createTestPopServer(undefined, { now: at(T) })
+ const other = nacl.box.keyPair()
+ const ch = s.issue(pub, 'push')
+ const otherPub = Buffer.from(other.publicKey).toString('base64')
+ expect(s.verify({ hostPublicKeyB64: otherPub, purpose: 'push', subject: 'x', popChallenge: ch.challenge, popProof: prove(ch, 'push', 'x', other) })).toBe(false)
+ })
+ it('accepts up to exp + 5 s, refuses after', () => {
+ const issued = createTestPopServer(undefined, { now: at(T) }).issue(pub, 'push')
+ const input = (subject: string) => ({ hostPublicKeyB64: pub, purpose: 'push' as const, subject, popChallenge: issued.challenge, popProof: prove(issued, 'push', subject) })
+ expect(createTestPopServer(undefined, { now: at(issued.exp + 6) }).verify(input('x'))).toBe(false)
+ expect(createTestPopServer(undefined, { now: at(issued.exp + 5) }).verify(input('x'))).toBe(true)
+ })
+ it('refuses a proof forged over the all-zero shared secret of a low-order host key', () => {
+ const zero = Buffer.alloc(32).toString('base64')
+ const s = createTestPopServer(undefined, { now: at(T) })
+ const ch = s.issue(zero, 'host-token')
+ const zeroKey = createHmac('sha256', Buffer.alloc(32)).update('nodeterm/relay-pop/v1').digest()
+ const forged = createHmac('sha256', zeroKey).update([ch.challenge, 'host-token', '', zero].join('\n')).digest('base64url')
+ expect(s.verify({ hostPublicKeyB64: zero, purpose: 'host-token', subject: '', popChallenge: ch.challenge, popProof: forged })).toBe(false)
+ })
+ it('refuses non-string evidence without throwing', () => {
+ expect(createTestPopServer().verify({ hostPublicKeyB64: pub, purpose: 'push', subject: '', popChallenge: 5, popProof: {} })).toBe(false)
+ })
+})
+
+describe('fetchPopChallenge', () => {
+ const res = (status: number, body: unknown) => new Response(JSON.stringify(body), { status })
+ it('404/405 ⇒ unsupported (old backend)', async () => {
+ for (const st of [404, 405]) {
+ expect(await fetchPopChallenge({ apiBase: 'https://api/', hostPublicKeyB64: 'K', purpose: 'push', fetch: (async () => res(st, {})) as typeof fetch })).toEqual({ ok: false, unsupported: true })
+ }
+ })
+ it('network error, 5xx, 429 and a malformed body are NOT unsupported', async () => {
+ const throwing = (async () => { throw new Error('down') }) as typeof fetch
+ expect(await fetchPopChallenge({ apiBase: 'https://api', hostPublicKeyB64: 'K', purpose: 'push', fetch: throwing })).toEqual({ ok: false, unsupported: false })
+ expect(await fetchPopChallenge({ apiBase: 'https://api', hostPublicKeyB64: 'K', purpose: 'push', fetch: (async () => res(503, {})) as typeof fetch })).toEqual({ ok: false, unsupported: false, status: 503 })
+ expect(await fetchPopChallenge({ apiBase: 'https://api', hostPublicKeyB64: 'K', purpose: 'push', fetch: (async () => res(429, {})) as typeof fetch })).toEqual({ ok: false, unsupported: false, status: 429 })
+ expect(await fetchPopChallenge({ apiBase: 'https://api', hostPublicKeyB64: 'K', purpose: 'push', fetch: (async () => res(200, { pairingToken: 'T' })) as typeof fetch })).toEqual({ ok: false, unsupported: false, status: 200 })
+ })
+ it('posts {hostPublicKeyB64, purpose} to /v1/relay/challenge and returns the challenge', async () => {
+ let url = ''; let sent: unknown
+ const r = await fetchPopChallenge({ apiBase: 'https://api//', hostPublicKeyB64: 'K', purpose: 'host-token', fetch: (async (u: string, init: RequestInit) => { url = u; sent = JSON.parse(String(init.body)); return res(200, { challenge: 'C', serverPublicKeyB64: 'S', exp: 1 }) }) as typeof fetch })
+ expect(url).toBe('https://api/v1/relay/challenge')
+ expect(sent).toEqual({ hostPublicKeyB64: 'K', purpose: 'host-token' })
+ expect(r).toEqual({ ok: true, challenge: 'C', serverPublicKeyB64: 'S' })
+ })
+})
+
+describe('popRefusalOf', () => {
+ it('reads only a 403 carrying a PoP error', () => {
+ expect(popRefusalOf(403, { error: 'pop_required' })).toBe('pop_required')
+ expect(popRefusalOf(403, { error: 'pop_invalid' })).toBe('pop_invalid')
+ expect(popRefusalOf(403, { error: 'forbidden' })).toBeNull()
+ expect(popRefusalOf(402, { error: 'pop_required' })).toBeNull()
+ expect(popRefusalOf(403, null)).toBeNull()
+ })
+})
diff --git a/src/core/relay/relay-pop.ts b/src/core/relay/relay-pop.ts
new file mode 100644
index 000000000..74ca17d46
--- /dev/null
+++ b/src/core/relay/relay-pop.ts
@@ -0,0 +1,85 @@
+// Proof that this process holds a relay host's X25519 secret key (hosted relay, R44 — see
+// docs/hosted-team-relay.md). The backend issues a challenge plus a one-off X25519 key; the proof is
+// an HMAC keyed by the shared secret. The ONLY place a proof is computed. Its bytes are pinned by
+// relay-pop-vector.json, which nodeterm-server carries too (test/fixtures/relay-pop-vector.json).
+import { createHmac } from 'node:crypto'
+import nacl from 'tweetnacl'
+
+export type PopPurpose = 'host-token' | 'push'
+export type PopRefusal = 'pop_required' | 'pop_invalid'
+export const POP_REFUSED_MESSAGE =
+ "The relay refused this host's key proof — update nodeterm, or run `team rotate-key` if the key was replaced."
+
+const PROOF_LABEL = 'nodeterm/relay-pop/v1'
+const hmac = (key: Buffer | Uint8Array, data: string): Buffer => createHmac('sha256', key).update(data).digest()
+
+function key32(b64: string): Uint8Array {
+ if (!/^[A-Za-z0-9+/]{43}=$/.test(b64)) throw new Error('relay-pop: bad key')
+ const raw = Buffer.from(b64, 'base64')
+ if (raw.length !== 32) throw new Error('relay-pop: bad key')
+ return new Uint8Array(raw)
+}
+
+export function computePopProof(i: {
+ hostSecretKey: Uint8Array
+ hostPublicKeyB64: string
+ challenge: string
+ serverPublicKeyB64: string
+ purpose: PopPurpose
+ subject: string
+}): string {
+ if (i.hostSecretKey.length !== 32) throw new Error('relay-pop: bad key')
+ const shared = nacl.scalarMult(i.hostSecretKey, key32(i.serverPublicKeyB64))
+ if (shared.every((b) => b === 0)) throw new Error('relay-pop: degenerate shared secret')
+ const key = hmac(Buffer.from(shared), PROOF_LABEL)
+ return hmac(key, [i.challenge, i.purpose, i.subject, i.hostPublicKeyB64].join('\n')).toString('base64url')
+}
+
+export type PopProver = (i: { challenge: string; serverPublicKeyB64: string; purpose: PopPurpose; subject: string }) => string
+
+/** A prover closed over a key pair, so callers that only need to PROVE never hold the secret. */
+export function popProverFor(keys: { publicKey: Uint8Array; secretKey: Uint8Array }): PopProver {
+ const hostPublicKeyB64 = Buffer.from(keys.publicKey).toString('base64')
+ return (i) => computePopProof({ ...i, hostSecretKey: keys.secretKey, hostPublicKeyB64 })
+}
+
+export type ChallengeResult =
+ | { ok: true; challenge: string; serverPublicKeyB64: string }
+ | { ok: false; unsupported: true }
+ | { ok: false; unsupported: false; status?: number }
+
+/** Only 404/405 means "this backend predates PoP" — the one case a caller may send an unproven
+ * request. Every other failure is transient and must go to the caller's backoff: an unproven
+ * request from a LATCHED host is refused (403) and would stop hosting. */
+export async function fetchPopChallenge(d: {
+ apiBase: string
+ hostPublicKeyB64: string
+ purpose: PopPurpose
+ fetch?: typeof fetch
+ signal?: AbortSignal
+}): Promise<ChallengeResult> {
+ const f = d.fetch ?? fetch
+ let res: Response
+ try {
+ res = await f(`${d.apiBase.replace(/\/+$/, '')}/v1/relay/challenge`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ hostPublicKeyB64: d.hostPublicKeyB64, purpose: d.purpose }),
+ signal: d.signal
+ })
+ } catch {
+ return { ok: false, unsupported: false }
+ }
+ if (res.status === 404 || res.status === 405) return { ok: false, unsupported: true }
+ if (!res.ok) return { ok: false, unsupported: false, status: res.status }
+ const json = (await res.json().catch(() => null)) as { challenge?: unknown; serverPublicKeyB64?: unknown } | null
+ if (!json || typeof json.challenge !== 'string' || typeof json.serverPublicKeyB64 !== 'string')
+ return { ok: false, unsupported: false, status: res.status }
+ return { ok: true, challenge: json.challenge, serverPublicKeyB64: json.serverPublicKeyB64 }
+}
+
+export function popRefusalOf(status: number, body: unknown): PopRefusal | null {
+ if (status !== 403 || !body || typeof body !== 'object') return null
+ const e = (body as { error?: unknown }).error
+ return e === 'pop_required' || e === 'pop_invalid' ? e : null
+}