@agimon-ai/po-remote 0.0.0-alpha.170
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +149 -0
- package/README.md +28 -0
- package/dist/apiContracts.cjs +17 -0
- package/dist/apiContracts.cjs.map +1 -0
- package/dist/apiContracts.d.mts +53 -0
- package/dist/apiContracts.d.mts.map +1 -0
- package/dist/apiContracts.mjs +13 -0
- package/dist/apiContracts.mjs.map +1 -0
- package/dist/extensions/server.cjs +30 -0
- package/dist/extensions/server.cjs.map +1 -0
- package/dist/extensions/server.d.mts +5 -0
- package/dist/extensions/server.d.mts.map +1 -0
- package/dist/extensions/server.mjs +25 -0
- package/dist/extensions/server.mjs.map +1 -0
- package/dist/extensions/web.mjs +1464 -0
- package/dist/extensions/web.mjs.map +1 -0
- package/dist/index.cjs +6190 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.mts +553 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +6159 -0
- package/dist/index.mjs.map +1 -0
- package/dist/po-runtime-identity.json +1 -0
- package/llms.txt +13 -0
- package/package.json +158 -0
- package/src/prompts/help-how-to-remote/SKILL.md +23 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["BAD_GATEWAY","BAD_REQUEST","FORBIDDEN","NOT_FOUND","CREATED","BAD_GATEWAY","LOOSE_MODE_MASK","isLooseMode","tightenMode","isLooseMode","MS_PER_MINUTE","isRecord","TOKEN_BYTES","fs","TOKEN_BYTES","ID_BYTES","isRecord","UNAUTHORIZED","fs"],"sources":["../src/services/devProxyPolicy/index.ts","../src/services/loopbackAddress/index.ts","../src/services/devProxyForward/index.ts","../src/services/devProxyRoutes/index.ts","../src/services/devProxySocket/index.ts","../src/services/devProxyStore/devProxyRecords.ts","../src/services/devProxyStore/sync.ts","../src/services/devProxyStore/index.ts","../src/constants/remote.ts","../src/services/deviceSessions/index.ts","../src/services/webauthnPolicy/index.ts","../src/services/deviceTrust/index.ts","../src/services/hubDeviceTrust/index.ts","../src/services/hubFederation/index.ts","../src/services/publicFileShares/index.ts","../src/services/deviceAuth/index.ts","../src/services/nativePushRegistration/index.ts","../src/services/pairingFlow/index.ts","../src/services/remoteAccessSettings/index.ts","../src/services/remoteAccessStore/remoteAccessRecords.ts","../src/services/remoteGuardPolicy/index.ts","../src/services/webauthn/index.ts","../src/services/remoteAccess/index.ts","../src/services/remoteAccessStore/sync.ts","../src/services/remoteAccessStore/index.ts","../src/services/remoteRoutes/index.ts","../src/services/tunnelOutput/index.ts","../src/services/tunnelProcess/index.ts","../src/services/remoteRuntime/index.ts","../src/services/remoteApi/index.ts"],"sourcesContent":["/**\n * What the dev proxy will forward, and where.\n *\n * Pure, with no I/O, so the whole decision surface of a feature that reaches\n * loopback services can be read in one sitting and tested without a server.\n *\n * The upstream host is not a parameter anywhere in this module, and a target\n * is a port and nothing else. Accepting a hostname would mean resolving one,\n * and a resolver turns a fixed destination into an attacker-chosen one through\n * DNS rebinding, decimal and octal address spellings, and IPv4-mapped IPv6\n * forms. Refusing the parameter forecloses that family rather than filtering\n * it. Which of the two loopback literals actually answers is settled in\n * the loopbackAddress service, from the port alone.\n */\n\nimport { DEV_PROXY_PREFIX } from '@agimon-ai/po-core/remoteContract';\n\nconst MAX_NAME_LENGTH = 32;\n/**\n * Lowercase, digits and dashes, opening on an alphanumeric.\n *\n * The name is a path segment and it is also what the developer types into\n * `base: '/devproxy/<name>/'`, so it stays in the character set that needs no\n * escaping in either place.\n */\nconst TARGET_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/u;\nconst MIN_PORT = 1;\nconst MAX_PORT = 65_535;\n\nexport type NameVerdict = { ok: true; name: string } | { ok: false; reason: string };\n\nexport type PortVerdict = { ok: true; port: number } | { ok: false; reason: string };\n\nexport type ProxyPathVerdict =\n | { kind: 'match'; name: string; /** The path unchanged, prefix included. */ upstreamPath: string }\n | { kind: 'redirect'; location: string }\n | { kind: 'reject'; reason: string };\n\nexport function validateTargetName(raw: unknown): NameVerdict {\n if (typeof raw !== 'string') return { ok: false, reason: 'A target name must be text.' };\n const name = raw.trim().toLowerCase();\n if (name === '') return { ok: false, reason: 'A target needs a name.' };\n if (name.length > MAX_NAME_LENGTH) {\n return { ok: false, reason: `A target name is at most ${String(MAX_NAME_LENGTH)} characters.` };\n }\n if (!TARGET_NAME.test(name)) {\n return {\n ok: false,\n reason: 'A target name uses lowercase letters, digits and dashes, starting with a letter or digit.',\n };\n }\n return { ok: true, name };\n}\n\n/**\n * Whether this port may be proxied.\n *\n * `reserved` is read fresh by the caller on every attempt rather than captured\n * once, because the cockpit's own ports are only known after it binds and the\n * tunnel port changes when remote access is toggled. A cached list would go\n * stale in exactly the direction that matters, letting the proxy point at the\n * cockpit itself.\n */\nexport function validateTargetPort(raw: unknown, reserved: readonly (number | undefined)[]): PortVerdict {\n const port = typeof raw === 'number' ? raw : Number(raw);\n if (!Number.isSafeInteger(port)) return { ok: false, reason: 'A port must be a whole number.' };\n if (port < MIN_PORT || port > MAX_PORT) {\n return { ok: false, reason: `A port is between ${String(MIN_PORT)} and ${String(MAX_PORT)}.` };\n }\n if (reserved.includes(port)) return { ok: false, reason: 'That port belongs to the cockpit itself.' };\n return { ok: true, port };\n}\n\n/**\n * Whether a path segment tries to climb out of the prefix.\n *\n * Checked before and after percent-decoding. A proxy that only checked the raw\n * form would forward `%2e%2e`, and an upstream that decodes before resolving\n * would then walk out of the tree the operator meant to expose.\n */\nfunction escapesPrefix(upstreamPath: string): boolean {\n let decoded: string;\n try {\n decoded = decodeURIComponent(upstreamPath);\n } catch {\n // A malformed percent sequence is not a path this proxy needs to serve.\n return true;\n }\n for (const candidate of [upstreamPath, decoded]) {\n for (const segment of candidate.split('/')) {\n if (segment === '.' || segment === '..') return true;\n }\n }\n return false;\n}\n\n/**\n * Whether this path is one the dev proxy owns.\n *\n * The remote guard and the proxy handler must agree about this, and they do not\n * see the same string: Hono's router hands the guard a raw slice of the request\n * line, while the handler reads `new URL(...).pathname`, which resolves `..`\n * before anyone looks at it. So `/devproxy/x/../../api/health` can be a proxy\n * path to one and an API path to the other, and a guard that answered on the\n * prefix alone would grant an `/api/` request the direct, unsealed treatment.\n *\n * Refusing every dot segment removes the disagreement instead of trying to\n * predict it. A legitimate asset URL has no reason to carry one.\n */\nexport function isDevProxyPath(path: string): boolean {\n if (!path.startsWith(DEV_PROXY_PREFIX)) return false;\n return !escapesPrefix(path.slice(DEV_PROXY_PREFIX.length));\n}\n/**\n * Identifies the target a proxied request belongs to.\n *\n * `upstreamPath` is the request path unchanged, prefix included. That is the\n * whole trick, and getting it wrong costs a redirect loop: the target is\n * configured with `base: '/devproxy/<name>/'`, so it believes it is serving\n * there and redirects anything at `/` back to its base. Stripping the prefix\n * would hand it `/`, take its redirect, and go round again. nginx draws the\n * same distinction between `proxy_pass http://host/` and `proxy_pass\n * http://host`; this is the second one.\n *\n * Reads the raw, still-encoded pathname. Hono routes and the remote guard both\n * work on the decoded value, so a request that only becomes `/devproxy/...`\n * after decoding would reach this handler, and passing the encoded form\n * through untouched is what makes a file named `a b.png` load.\n */\nexport function parseProxyPath(rawPathname: string): ProxyPathVerdict {\n if (!rawPathname.startsWith(DEV_PROXY_PREFIX)) return { kind: 'reject', reason: 'Not a proxied path.' };\n const rest = rawPathname.slice(DEV_PROXY_PREFIX.length);\n const boundary = rest.indexOf('/');\n\n if (boundary === -1) {\n const verdict = validateTargetName(rest);\n if (!verdict.ok) return { kind: 'reject', reason: verdict.reason };\n // A dev server serving at its own root needs the trailing slash, or every\n // relative URL on the page resolves one level too high. nginx answers the\n // same way rather than guessing.\n return { kind: 'redirect', location: `${DEV_PROXY_PREFIX}${verdict.name}/` };\n }\n\n const verdict = validateTargetName(rest.slice(0, boundary));\n if (!verdict.ok) return { kind: 'reject', reason: verdict.reason };\n if (escapesPrefix(rest.slice(boundary))) {\n return { kind: 'reject', reason: 'That path leaves the proxied target.' };\n }\n return { kind: 'match', name: verdict.name, upstreamPath: rawPathname };\n}\n","import net from 'node:net';\n\n/**\n * Which loopback address a local dev server is actually listening on.\n *\n * Vite binds `localhost`, which on a machine with IPv6 resolves to `::1` and\n * nothing answers on `127.0.0.1`. Other servers do the opposite. Dialling the\n * wrong one is an immediate ECONNREFUSED, which looks to the developer like\n * the proxy is broken rather than like an address-family mismatch.\n *\n * This is deliberately not a resolver. The candidates are two hard-coded\n * loopback literals and the only input is a port number, so there is no\n * hostname to poison and no DNS-rebinding window: the answer can only ever be\n * this machine.\n */\n\n/** IPv4 first: it is what a developer types, so preferring it keeps logs recognizable. */\nconst CANDIDATES = ['127.0.0.1', '::1'] as const;\nconst PROBE_TIMEOUT_MS = 400;\n\nexport type LoopbackAddress = (typeof CANDIDATES)[number];\n\n/** Remembered per port so a page of eighty assets probes once, not eighty times. */\nconst known = new Map<number, LoopbackAddress>();\n\nasync function accepts(host: LoopbackAddress, port: number): Promise<boolean> {\n return new Promise<boolean>((resolve) => {\n const socket = net.connect({ host, port });\n const settle = (answer: boolean): void => {\n socket.destroy();\n resolve(answer);\n };\n socket.setTimeout(PROBE_TIMEOUT_MS, () => settle(false));\n socket.once('connect', () => settle(true));\n socket.once('error', () => settle(false));\n });\n}\n\n/**\n * The loopback address answering on this port, preferring a remembered one.\n *\n * Falls back to IPv4 when neither answers, so the caller's own connection\n * produces the real ECONNREFUSED and its message, rather than this probe\n * inventing a different error for the same condition.\n */\nexport async function loopbackFor(port: number): Promise<LoopbackAddress> {\n const remembered = known.get(port);\n if (remembered !== undefined && (await accepts(remembered, port))) return remembered;\n for (const candidate of CANDIDATES) {\n if (await accepts(candidate, port)) {\n known.set(port, candidate);\n return candidate;\n }\n }\n known.delete(port);\n return CANDIDATES[0];\n}\n\n/** Test seam. */\nexport function forgetLoopbackAddresses(): void {\n known.clear();\n}\n","import http from 'node:http';\nimport { Readable } from 'node:stream';\n\nimport { DEV_PROXY_PREFIX } from '@agimon-ai/po-core/remoteContract';\n\nimport { loopbackFor, type LoopbackAddress } from '../loopbackAddress';\n\n/**\n * One HTTP request forwarded to a local dev server, the way nginx would.\n *\n * Three rewrites are not optional, and each one is a bug report waiting to\n * happen if it is skipped:\n *\n * - `Host` becomes the upstream's own address. Vite's `server.allowedHosts`\n * and Next's dev-origin check refuse a request whose Host they do not\n * recognize, so forwarding the cockpit's public hostname makes the dev\n * server answer with a block page rather than the app.\n * - A root-relative `Location` gains the prefix, or the first redirect walks\n * the browser out of the proxy and into the cockpit.\n * - `Set-Cookie` with `Path=/` is narrowed to the prefix, or the dev app's\n * session cookie is sent on every cockpit request for the rest of the day.\n *\n * The cockpit's own cookies are removed on the way out. nginx would forward\n * them, but `__Host-po_device` is a bearer credential for the cockpit and\n * the dev server has no use for it. Handing it to an unaudited dev dependency,\n * or into its request log, is a leak with no upside.\n */\n\n/** Headers that describe one hop and must not be copied onto the next. */\nconst HOP_BY_HOP = new Set(['connection', 'keep-alive', 'transfer-encoding', 'upgrade']);\n/** Set from the target rather than copied, so the browser's value never reaches the upstream. */\nconst REPLACED = new Set(['host']);\n/** Cookies belonging to the cockpit rather than to the proxied application. */\nconst COCKPIT_COOKIE_MARKER = 'po';\nconst BAD_GATEWAY = 502;\nconst NO_BODY_STATUSES = new Set([204, 304]);\n\nexport interface ForwardInput {\n /** The registered target's name, which is also its path segment. */\n name: string;\n port: number;\n /** Path and query exactly as the browser sent them, prefix included. */\n upstreamPath: string;\n method: string;\n headers: Headers;\n body: ReadableStream<Uint8Array> | null;\n /** The scheme the browser used, which is https whenever a tunnel is in front. */\n forwardedProto: string;\n /** The Host the browser addressed, for an app that builds absolute URLs. */\n forwardedHost: string | undefined;\n signal?: AbortSignal;\n}\n\n/** An IPv6 literal needs brackets before it can be a Host header value. */\nfunction hostHeader(host: LoopbackAddress, port: number): string {\n return host.includes(':') ? `[${host}]:${String(port)}` : `${host}:${String(port)}`;\n}\n\n/** Drops the cockpit's cookies and keeps the application's own. */\nfunction filterCookies(raw: string): string | undefined {\n const kept = raw\n .split(';')\n .map((pair) => pair.trim())\n .filter((pair) => pair !== '' && !pair.slice(0, pair.indexOf('=')).toLowerCase().includes(COCKPIT_COOKIE_MARKER));\n return kept.length === 0 ? undefined : kept.join('; ');\n}\n\nfunction outgoingHeaders(input: ForwardInput, host: LoopbackAddress): Record<string, string> {\n const out: Record<string, string> = {};\n input.headers.forEach((value, key) => {\n const normalized = key.toLowerCase();\n if (HOP_BY_HOP.has(normalized) || REPLACED.has(normalized)) return;\n if (normalized === 'cookie') {\n const kept = filterCookies(value);\n if (kept !== undefined) out.cookie = kept;\n return;\n }\n out[key] = value;\n });\n out.host = hostHeader(host, input.port);\n out['x-forwarded-proto'] = input.forwardedProto;\n if (input.forwardedHost !== undefined) out['x-forwarded-host'] = input.forwardedHost;\n // Read by frameworks that can self-configure their base path. Vite and Next\n // ignore it and need their own `base`/`basePath`, which is documented.\n out['x-forwarded-prefix'] = `${DEV_PROXY_PREFIX}${input.name}`;\n return out;\n}\n\n/** Prefixes a root-relative redirect so it stays inside the proxied target. */\nfunction rewriteLocation(value: string, name: string): string {\n const mount = `${DEV_PROXY_PREFIX}${name}`;\n if (!value.startsWith('/') || value.startsWith('//') || value.startsWith(`${mount}/`)) return value;\n return `${mount}${value}`;\n}\n\n/**\n * Narrows a cookie's Path to the proxied mount.\n *\n * A dev app setting `Path=/` means it on its own origin, where it is the only\n * tenant. Here it is not, so the attribute is rewritten rather than honoured.\n * A cookie with no Path at all already defaults to the request's directory,\n * which is inside the mount, so it is left alone.\n */\nfunction rewriteSetCookie(value: string, name: string): string {\n const mount = `${DEV_PROXY_PREFIX}${name}/`;\n return value.replaceAll(/;\\s*path=([^;]*)/giu, (_match, current: string) => {\n const trimmed = current.trim();\n if (trimmed.startsWith(mount)) return `; Path=${trimmed}`;\n const suffix = trimmed === '/' || trimmed === '' ? '' : trimmed.replace(/^\\//u, '');\n return `; Path=${mount}${suffix}`;\n });\n}\n\nfunction responseHeaders(incoming: http.IncomingMessage, name: string): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(incoming.headers)) {\n const normalized = key.toLowerCase();\n if (value === undefined || HOP_BY_HOP.has(normalized)) continue;\n if (normalized === 'set-cookie') {\n // The only header that legitimately repeats, so it is appended rather\n // than set; joining several cookies into one value discards all but one.\n for (const cookie of Array.isArray(value) ? value : [value]) {\n headers.append('set-cookie', rewriteSetCookie(cookie, name));\n }\n continue;\n }\n const single = Array.isArray(value) ? value.join(', ') : value;\n headers.set(key, normalized === 'location' ? rewriteLocation(single, name) : single);\n }\n return headers;\n}\n\n/**\n * Forwards one request and returns the upstream's answer.\n *\n * Both bodies stream. A dev server sends multi-megabyte source maps and\n * receives file uploads, and buffering either would hold the whole thing in\n * memory for no benefit.\n */\nexport async function forwardToDevServer(input: ForwardInput): Promise<Response> {\n const host = await loopbackFor(input.port);\n return new Promise<Response>((resolve, reject) => {\n const request = http.request(\n {\n host,\n port: input.port,\n path: input.upstreamPath,\n method: input.method,\n headers: outgoingHeaders(input, host),\n signal: input.signal,\n },\n (incoming) => {\n const status = incoming.statusCode ?? BAD_GATEWAY;\n // 204 and 304 carry no body, and constructing one with a stream throws.\n const body = NO_BODY_STATUSES.has(status) ? null : (Readable.toWeb(incoming) as ReadableStream);\n resolve(new Response(body, { status, headers: responseHeaders(incoming, input.name) }));\n },\n );\n request.once('error', reject);\n if (input.body === null) {\n request.end();\n return;\n }\n Readable.fromWeb(input.body as Parameters<typeof Readable.fromWeb>[0])\n .on('error', reject)\n .pipe(request);\n });\n}\n","import { DEV_PROXY_PREFIX, DEV_PROXY_TARGETS_ROUTE } from '@agimon-ai/po-core/remoteContract';\nimport type { DevProxyTarget } from '@agimon-ai/po-core/remoteContract';\nimport type { Context, Hono } from 'hono';\n\nimport { forwardToDevServer } from '../devProxyForward';\nimport { parseProxyPath, validateTargetName, validateTargetPort } from '../devProxyPolicy';\nimport type { DevProxyStore } from '../devProxyStore';\nimport type { GuardListener } from '../remoteGuardPolicy';\n\n/**\n * The dev proxy's control plane and its HTTP forwarding route.\n *\n * Registering a target is refused anywhere but the host, and that refusal is the entire consent\n * model: putting a local port on the public internet is decided by someone sitting at the machine.\n * A passkey gesture cannot carry it, because a quick tunnel's rotating hostname has no relying party.\n * Using a registered target is then open to any paired device, which is what makes the feature\n * usable away from the desk; a stolen phone reaches only the ports its owner chose to name.\n */\n\nconst BAD_REQUEST = 400;\nconst FORBIDDEN = 403;\nconst NOT_FOUND = 404;\nconst CREATED = 201;\nconst NO_CONTENT = 204;\nconst MOVED_PERMANENTLY = 301;\nconst BAD_GATEWAY = 502;\nconst CONNECTION_REFUSED = 'ECONNREFUSED';\n\nexport interface DevProxyRoutesOptions {\n store: DevProxyStore;\n listenerOf: (context: Context) => GuardListener;\n /** Ports the cockpit itself holds, read per call so a toggled tunnel is never stale. */\n reservedPorts: () => readonly (number | undefined)[];\n onNotice: (message: string) => void;\n}\n\ninterface TargetRequestBody {\n name?: unknown;\n port?: unknown;\n}\n\n/** The scheme the browser used, trusting the edge's header only for its own hop. */\nfunction forwardedProto(context: Context, listener: GuardListener): string {\n const declared = context.req.header('x-forwarded-proto');\n if (declared === 'https' || declared === 'http') return declared;\n return listener === 'local' ? 'http' : 'https';\n}\n\nfunction describeUpstreamFailure(error: unknown, target: DevProxyTarget): string {\n const code = (error as { code?: string } | undefined)?.code;\n if (code === CONNECTION_REFUSED) {\n return `Nothing is answering on port ${String(target.port)}. Is \"${target.name}\" running?`;\n }\n return `The dev server for \"${target.name}\" did not answer: ${error instanceof Error ? error.message : String(error)}`;\n}\n\nexport function registerDevProxyRoutes(app: Hono, options: DevProxyRoutesOptions): void {\n const { store } = options;\n const isLocal = (context: Context): boolean => options.listenerOf(context) === 'local';\n\n app.get(DEV_PROXY_TARGETS_ROUTE, (context) =>\n context.json({ targets: store.targets(), canRegister: isLocal(context) }),\n );\n\n app.post(DEV_PROXY_TARGETS_ROUTE, async (context) => {\n if (!isLocal(context)) {\n return context.json(\n { error: 'A dev proxy target can only be added on the host, not through the tunnel.' },\n FORBIDDEN,\n );\n }\n let body: TargetRequestBody;\n try {\n body = (await context.req.json()) as TargetRequestBody;\n } catch {\n return context.json({ error: 'Expected a JSON body with a name and a port.' }, BAD_REQUEST);\n }\n const name = validateTargetName(body.name);\n if (!name.ok) return context.json({ error: name.reason }, BAD_REQUEST);\n const port = validateTargetPort(body.port, options.reservedPorts());\n if (!port.ok) return context.json({ error: port.reason }, BAD_REQUEST);\n\n const target: DevProxyTarget = { name: name.name, port: port.port, createdAt: Date.now() };\n store.save(target);\n options.onNotice(`dev proxy target \"${target.name}\" now serves port ${String(target.port)}`);\n return context.json({ target }, CREATED);\n });\n\n app.delete(`${DEV_PROXY_TARGETS_ROUTE}/:name`, (context) => {\n if (!isLocal(context)) {\n return context.json({ error: 'A dev proxy target can only be removed on the host.' }, FORBIDDEN);\n }\n const name = validateTargetName(context.req.param('name'));\n if (!name.ok) return context.json({ error: name.reason }, BAD_REQUEST);\n if (!store.remove(name.name)) return context.json({ error: 'No such dev proxy target.' }, NOT_FOUND);\n options.onNotice(`dev proxy target \"${name.name}\" removed`);\n return context.body(null, NO_CONTENT);\n });\n\n app.all(`${DEV_PROXY_PREFIX}*`, async (context) => {\n const url = new URL(context.req.url);\n const parsed = parseProxyPath(url.pathname);\n if (parsed.kind === 'reject') return context.text(parsed.reason, BAD_REQUEST);\n if (parsed.kind === 'redirect') return context.redirect(parsed.location, MOVED_PERMANENTLY);\n\n const target = store.find(parsed.name);\n if (target === undefined) return context.text(`No dev proxy target named \"${parsed.name}\".`, NOT_FOUND);\n\n try {\n return await forwardToDevServer({\n name: target.name,\n port: target.port,\n upstreamPath: `${parsed.upstreamPath}${url.search}`,\n method: context.req.method,\n headers: context.req.raw.headers,\n body: context.req.raw.body,\n forwardedProto: forwardedProto(context, options.listenerOf(context)),\n forwardedHost: context.req.header('host'),\n signal: context.req.raw.signal,\n });\n } catch (error) {\n const message = describeUpstreamFailure(error, target);\n options.onNotice(message);\n return context.text(message, BAD_GATEWAY);\n }\n });\n}\n","import { WebSocket, type RawData } from 'ws';\n\nimport { loopbackFor } from '../loopbackAddress';\n\n/**\n * A WebSocket carried between a paired device and a local dev server.\n *\n * This is what carries hot module reload. Vite negotiates the `vite-hmr` subprotocol, so the\n * handshake's protocol list is forwarded rather than dropped; without it the dev client connects\n * and then gives up. The tunnel listener has already authorized the handshake, so this only\n * relays frames.\n */\n\n/** Sent when the upstream never came up, or died in a way with no code to relay. */\nconst INTERNAL_ERROR = 1011;\nconst NORMAL_CLOSURE = 1000;\n/** Reserved codes a peer may observe but no endpoint may transmit. */\nconst UNSENDABLE_CLOSE_CODES = new Set([1005, 1006, 1015]);\nconst MAX_CLOSE_REASON = 120;\n/** Frames held while the upstream connects; a dev client that speaks first must not lose them. */\nconst MAX_PENDING_BYTES = 1024 * 1024;\n\nexport interface DevProxySocketInput {\n port: number;\n /** Full upstream WebSocket URL; when set, `port` and `upstreamPath` only label notices. */\n target?: string;\n /** Extra handshake headers for the upstream, such as a forwarded credential. */\n headers?: Record<string, string>;\n /**\n * Close code sent to the browser when the upstream drops without a sendable code or fails.\n * A supervised upstream passes 1012 (service restart) so the browser reconnects.\n */\n upstreamLostCode?: number;\n /** Called once with the code sent to the browser when the relay closes. */\n onClose?: (code: number) => void;\n /** Path and query exactly as the browser sent them, prefix included. */\n upstreamPath: string;\n /** The browser's requested subprotocols, forwarded so HMR can negotiate. */\n protocols: string | undefined;\n onNotice?: (message: string) => void;\n}\n\n/** A code the upstream reported that this endpoint is actually allowed to send on. */\nfunction sendableCode(code: number, lostCode = NORMAL_CLOSURE): number {\n return code === 0 || UNSENDABLE_CLOSE_CODES.has(code) ? lostCode : code;\n}\n\nfunction frameBytes(data: RawData): Buffer {\n if (Array.isArray(data)) return Buffer.concat(data);\n return Buffer.isBuffer(data) ? data : Buffer.from(new Uint8Array(data));\n}\n\n/** Relays one accepted browser socket to the dev server on the target's port until either side closes. */\nexport function relayDevProxySocket(client: WebSocket, input: DevProxySocketInput): void {\n let upstream: WebSocket | undefined;\n let pending: { data: Buffer; binary: boolean }[] = [];\n let pendingBytes = 0;\n let closed = false;\n\n const closeBoth = (code: number, reason: string): void => {\n if (closed) return;\n closed = true;\n pending = [];\n if (client.readyState === WebSocket.OPEN) client.close(code, reason.slice(0, MAX_CLOSE_REASON));\n upstream?.close();\n input.onClose?.(code);\n };\n\n client.on('message', (data: RawData, binary: boolean) => {\n if (closed) return;\n const bytes = frameBytes(data);\n if (upstream?.readyState === WebSocket.OPEN) {\n upstream.send(binary ? bytes : bytes.toString('utf8'));\n return;\n }\n pendingBytes += bytes.byteLength;\n if (pendingBytes > MAX_PENDING_BYTES) closeBoth(INTERNAL_ERROR, 'dev server socket did not open');\n else pending.push({ data: bytes, binary });\n });\n client.on('close', () => closeBoth(NORMAL_CLOSURE, ''));\n client.on('error', () => closeBoth(INTERNAL_ERROR, 'browser socket failed'));\n\n const protocols = input.protocols\n ?.split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry !== '');\n // Resolving the loopback family is a round trip, so the browser socket is already open by the\n // time the upstream is dialled. That is the window `pending` covers.\n const resolveTarget = async (): Promise<string> => {\n if (input.target !== undefined) return input.target;\n const host = await loopbackFor(input.port);\n const authority = host.includes(':') ? `[${host}]` : host;\n return `ws://${authority}:${String(input.port)}${input.upstreamPath}`;\n };\n const options = input.headers === undefined ? undefined : { headers: input.headers };\n void resolveTarget().then((target) => {\n if (closed) return;\n const socket =\n protocols === undefined || protocols.length === 0\n ? new WebSocket(target, options)\n : new WebSocket(target, protocols, options);\n upstream = socket;\n socket.on('open', () => {\n for (const frame of pending) socket.send(frame.binary ? frame.data : frame.data.toString('utf8'));\n pending = [];\n pendingBytes = 0;\n });\n socket.on('message', (data: RawData, binary: boolean) => {\n if (closed || client.readyState !== WebSocket.OPEN) return;\n const bytes = frameBytes(data);\n client.send(binary ? bytes : bytes.toString('utf8'));\n });\n socket.on('close', (code: number, reason: Buffer) =>\n closeBoth(sendableCode(code, input.upstreamLostCode), reason.toString()),\n );\n socket.on('error', (error: Error) => {\n input.onNotice?.(`dev proxy socket to port ${String(input.port)} failed: ${error.message}`);\n closeBoth(input.upstreamLostCode ?? INTERNAL_ERROR, 'dev server socket failed');\n });\n });\n}\n","import type { DevProxyTarget } from '@agimon-ai/po-core/remoteContract';\n\nimport { validateTargetName } from '../devProxyPolicy';\n\n/**\n * Registered proxy targets on disk.\n *\n * Persisted, unlike a remote session, because a target is a name the developer\n * typed into their own build configuration as `base: '/devproxy/<name>/'`.\n * Losing it on restart would silently break that line, and the file holds no\n * secret: a port number and a label the operator chose while sitting at the\n * machine.\n */\n\nexport const TARGETS_FILE = 'dev-proxy.json';\nexport const DIRECTORY_MODE = 0o700;\nexport const FILE_MODE = 0o600;\n/** Any bit set for group or other; a state file readable by another account is worth repairing. */\nconst LOOSE_MODE_MASK = 0o077;\n\n/** Whether a file mode lets another account read the file. */\nexport function isLooseMode(mode: number): boolean {\n return (mode & LOOSE_MODE_MASK) !== 0;\n}\n\nexport interface DevProxyStoreOptions {\n /** The same directory the remote-access store uses; defaults to ~/.po/web. */\n stateDir: string;\n onNotice?: (message: string) => void;\n}\n\nexport interface DevProxyStore {\n targets(): readonly DevProxyTarget[];\n find(name: string): DevProxyTarget | undefined;\n /** Replaces any target already holding this name, so re-registering a moved port is one call. */\n save(target: DevProxyTarget): void;\n remove(name: string): boolean;\n}\n\n/**\n * Rebuilds one record, dropping anything the current policy would refuse.\n *\n * The file is revalidated on read rather than trusted, because a name that was\n * legal when written is not necessarily legal now, and an edited file must not\n * be able to introduce a target the API would have rejected.\n */\nfunction parseTarget(value: unknown): DevProxyTarget | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Partial<DevProxyTarget>;\n const name = validateTargetName(record.name);\n if (!name.ok) return undefined;\n if (typeof record.port !== 'number' || !Number.isSafeInteger(record.port)) return undefined;\n const createdAt = typeof record.createdAt === 'number' ? record.createdAt : 0;\n return { name: name.name, port: record.port, createdAt };\n}\n\nexport function parseDevProxyTargets(\n raw: string,\n targetsPath: string,\n notice: (message: string) => void,\n): DevProxyTarget[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n notice(`dev proxy targets at ${targetsPath} are not valid JSON; none will load`);\n return [];\n }\n if (!Array.isArray(parsed)) return [];\n return parsed.map(parseTarget).filter((target): target is DevProxyTarget => target !== undefined);\n}\n\nexport function serializeDevProxyTargets(targets: readonly DevProxyTarget[]): string {\n return `${JSON.stringify(targets, undefined, 2)}\\n`;\n}\n","// sync: documented Node-only dev proxy store API; phase 2 must migrate consumers to createDevProxyStoreAsync.\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { DevProxyTarget } from '@agimon-ai/po-core/remoteContract';\n\nimport {\n DIRECTORY_MODE,\n FILE_MODE,\n isLooseMode,\n parseDevProxyTargets,\n serializeDevProxyTargets,\n TARGETS_FILE,\n type DevProxyStore,\n type DevProxyStoreOptions,\n} from './devProxyRecords';\n\n/** Repairs a state file another account can read. */\nfunction tightenMode(filePath: string, notice: (message: string) => void): void {\n try {\n if (!isLooseMode(fs.statSync(filePath).mode)) return;\n fs.chmodSync(filePath, FILE_MODE);\n notice(`tightened permissions on ${filePath}`);\n } catch {\n // The file is missing or unreadable; the caller's own read reports that.\n }\n}\n\n/** @deprecated Node-only sync shim; use createDevProxyStoreAsync. Removed in M2. */\nexport function createDevProxyStore(options: DevProxyStoreOptions): DevProxyStore {\n const notice = options.onNotice ?? ((): void => {});\n const targetsPath = path.join(options.stateDir, TARGETS_FILE);\n let held = load();\n\n function load(): DevProxyTarget[] {\n let raw: string;\n try {\n raw = fs.readFileSync(targetsPath, 'utf8');\n } catch {\n // No file is the normal first run, so this is not worth a notice.\n return [];\n }\n tightenMode(targetsPath, notice);\n return parseDevProxyTargets(raw, targetsPath, notice);\n }\n\n function write(): void {\n const temporary = `${targetsPath}.${String(process.pid)}.tmp`;\n try {\n fs.mkdirSync(options.stateDir, { recursive: true, mode: DIRECTORY_MODE });\n fs.writeFileSync(temporary, serializeDevProxyTargets(held), { mode: FILE_MODE });\n // Rename rather than write in place, so a crash mid-write leaves the\n // previous contents rather than a truncated file.\n fs.renameSync(temporary, targetsPath);\n } catch (error) {\n notice(`${targetsPath} could not be saved: ${error instanceof Error ? error.message : String(error)}`);\n try {\n fs.rmSync(temporary, { force: true });\n } catch {\n // Nothing further to do; the temp file is inert either way.\n }\n }\n }\n\n return {\n targets: () => held,\n find: (name) => held.find((target) => target.name === name),\n\n save(target) {\n held = [...held.filter((existing) => existing.name !== target.name), target];\n write();\n },\n\n remove(name) {\n const next = held.filter((existing) => existing.name !== name);\n if (next.length === held.length) return false;\n held = next;\n write();\n return true;\n },\n };\n}\n","import path from 'node:path';\n\nimport { createSerialRunner, getOrThrow, nodeHost, writeFileAtomic } from '@agimon-ai/po-core/platform';\nimport type { DevProxyTarget } from '@agimon-ai/po-core/remoteContract';\nimport type { Context } from '@earendil-works/chord/context';\nimport type { FileSystem } from '@earendil-works/pi-durable/env';\n\nimport {\n DIRECTORY_MODE,\n FILE_MODE,\n isLooseMode,\n parseDevProxyTargets,\n serializeDevProxyTargets,\n TARGETS_FILE,\n type DevProxyStoreOptions,\n} from './devProxyRecords';\n\nexport type { DevProxyStore, DevProxyStoreOptions } from './devProxyRecords';\nexport { createDevProxyStore } from './sync';\n\n/** One queue per targets file, so concurrent writes in this process never interleave. */\nconst targetWrites = createSerialRunner();\n\n/** The async twin of `DevProxyStore`: reads stay in memory, every write resolves once it is on disk. */\nexport interface DevProxyStoreAsync {\n targets(): readonly DevProxyTarget[];\n find(name: string): DevProxyTarget | undefined;\n /** Replaces any target already holding this name, so re-registering a moved port is one call. */\n save(target: DevProxyTarget): Promise<void>;\n remove(name: string): Promise<boolean>;\n}\n\n/** Registered proxy targets on disk; a failed write is reported and never thrown, as in the sync store. */\nexport async function createDevProxyStoreAsync(\n fs: FileSystem,\n options: DevProxyStoreOptions,\n context: Context,\n): Promise<DevProxyStoreAsync> {\n const notice = options.onNotice ?? ((): void => {});\n const targetsPath = path.join(options.stateDir, TARGETS_FILE);\n const serial = targetWrites.forKey(targetsPath);\n\n const load = async (): Promise<DevProxyTarget[]> => {\n const raw = await fs.readTextFile(targetsPath, context);\n // No file is the normal first run, so this is not worth a notice.\n if (!raw.ok) return [];\n // Repairs a state file another account can read.\n try {\n const mode = await nodeHost.fileMode(targetsPath);\n if (mode !== undefined && isLooseMode(mode)) {\n await nodeHost.setMode(targetsPath, FILE_MODE);\n notice(`tightened permissions on ${targetsPath}`);\n }\n } catch {\n // The file vanished or is unreadable between the read and the check; the read above already won.\n }\n return parseDevProxyTargets(raw.value, targetsPath, notice);\n };\n\n let held = await load();\n\n const write = async (): Promise<void> => {\n try {\n if (!getOrThrow(await fs.exists(options.stateDir, context))) {\n getOrThrow(await fs.createDir(options.stateDir, { recursive: true }, context));\n await nodeHost.setMode(options.stateDir, DIRECTORY_MODE);\n }\n await writeFileAtomic(fs, targetsPath, serializeDevProxyTargets(held), context);\n await nodeHost.setMode(targetsPath, FILE_MODE);\n } catch (error) {\n notice(`${targetsPath} could not be saved: ${error instanceof Error ? error.message : String(error)}`);\n }\n };\n\n return {\n targets: () => held,\n find: (name) => held.find((target) => target.name === name),\n save: (target) =>\n serial(async () => {\n held = [...held.filter((existing) => existing.name !== target.name), target];\n await write();\n }),\n remove: (name) =>\n serial(async () => {\n const next = held.filter((existing) => existing.name !== name);\n if (next.length === held.length) return false;\n held = next;\n await write();\n return true;\n }),\n };\n}\n","export const DEVICE_AUTH_CHALLENGE_BODY_BYTES = 256;\n\nexport const DEVICE_AUTH_AUTHENTICATE_BODY_BYTES = 1024;\n\nexport const TRUSTED_DEVICE_REGISTER_BODY_BYTES = 2 * 1024;\n\n/** Most trusted native devices the host keeps on disk. */\nexport const TRUSTED_DEVICE_LIMIT = 32;\n\n/** A reconnect challenge has to survive a slow network and a cold app start. */\nexport const DEVICE_AUTH_CHALLENGE_TTL_MS = 120_000;\n\n/** Matches the passkey step-up window: long enough for Face ID, short enough to be useless when captured. */\nexport const DEVICE_STEP_UP_CHALLENGE_TTL_MS = 60_000;\n\n/** Upper bound on outstanding device challenges; the oldest is dropped first. */\nexport const DEVICE_CHALLENGE_LIMIT = 1024;\n\nexport const NATIVE_PUSH_BODY_BYTES = 8 * 1024;\n","/**\n * What makes a paired device's session still valid.\n *\n * Expiry is derived from the settings in force at the moment of the check,\n * never stamped onto the record when it was minted. That is what makes the\n * setting honest in both directions: switching expiry on has to invalidate a\n * session that is already idle, and switching it off has to bring it back. A\n * stored `expiresAt` would do neither.\n */\n\nimport type { AuthPairingIdentity } from '@agimon-ai/po-core';\nimport type { RemoteAccessSettings } from '@agimon-ai/po-core/remoteContract';\n\nimport type { DeviceTrust } from '../../types/remote';\n\nconst MS_PER_MINUTE = 60_000;\nconst MS_PER_HOUR = 3_600_000;\nconst MS_PER_SECOND = 1000;\n/** Long enough to tell an iPhone from a laptop, short enough not to be a fingerprint in a log. */\nconst MAX_USER_AGENT = 200;\n/** Upper bound of the C0 block, and the bounds of C1. Codepoints rather than a character class:\n * a regex over control characters is unreadable, hard to review, and trips no-control-regex. */\nconst C0_END = 0x1f;\nconst C1_START = 0x7f;\nconst C1_END = 0x9f;\nconst UNKNOWN_DEVICE = 'unknown device';\n\nexport interface DeviceRecord {\n /** Opaque, safe to display and to name in a revoke call. Never the secret. */\n id: string;\n /** SHA-256 of the session token. The token itself is never retained. */\n tokenHash: string;\n label: string;\n userAgent: string;\n /** Epoch milliseconds. */\n createdAt: number;\n /** Epoch milliseconds, bumped on every authenticated request. */\n lastSeenAt: number;\n /** How this session was earned; decides registration rights and step-up. */\n trust: DeviceTrust;\n /** The issuer-verified member bound before host approval, separate from any owner capability. */\n account?: AuthPairingIdentity;\n}\n\nexport type DeviceRejection = 'unknown' | 'idle' | 'absolute';\n\nexport type DeviceVerdict = { ok: true; record: DeviceRecord } | { ok: false; reason: DeviceRejection };\n\n/** Whether this record still authorizes a request, under the settings in force right now. */\nexport function evaluateDevice(\n record: DeviceRecord | undefined,\n now: number,\n settings: RemoteAccessSettings,\n): DeviceVerdict {\n if (record === undefined) return { ok: false, reason: 'unknown' };\n if (!settings.sessionExpiryEnabled) return { ok: true, record };\n if (now - record.lastSeenAt >= settings.idleMinutes * MS_PER_MINUTE) return { ok: false, reason: 'idle' };\n if (now - record.createdAt >= settings.absoluteHours * MS_PER_HOUR) return { ok: false, reason: 'absolute' };\n return { ok: true, record };\n}\n\n/** Exact deadline at which this device stops authorizing, or undefined while expiry is disabled. */\nexport function deviceExpiryAt(record: DeviceRecord, settings: RemoteAccessSettings): number | undefined {\n if (!settings.sessionExpiryEnabled) return undefined;\n return Math.min(\n record.lastSeenAt + settings.idleMinutes * MS_PER_MINUTE,\n record.createdAt + settings.absoluteHours * MS_PER_HOUR,\n );\n}\n\nexport function touchDevice(record: DeviceRecord, now: number): DeviceRecord {\n return { ...record, lastSeenAt: now };\n}\n\n/** How long the cookie should live, so the browser forgets roughly when the server does. */\nexport function cookieMaxAgeSeconds(settings: RemoteAccessSettings, ceilingSeconds: number): number {\n if (!settings.sessionExpiryEnabled) return ceilingSeconds;\n return Math.min(ceilingSeconds, Math.round((settings.absoluteHours * MS_PER_HOUR) / MS_PER_SECOND));\n}\n\n/** Replaces every C0 and C1 control character with a space; those are what could forge a log line. */\nfunction withoutControlCharacters(value: string): string {\n let out = '';\n for (const character of value) {\n const code = character.codePointAt(0) ?? 0;\n out += code <= C0_END || (code >= C1_START && code <= C1_END) ? ' ' : character;\n }\n return out;\n}\n\n/**\n * Strips anything that could forge a second line in a log or a second element\n * in the approval dialog, then truncates.\n *\n * The user agent is attacker-supplied and lands in both `notice()` output and\n * the host's approval prompt, so control characters are the concern rather than\n * length.\n */\nexport function sanitizeUserAgent(raw: string | undefined): string {\n if (raw === undefined) return UNKNOWN_DEVICE;\n const stripped = withoutControlCharacters(raw).replaceAll(/\\s+/gu, ' ').trim();\n if (stripped === '') return UNKNOWN_DEVICE;\n return stripped.slice(0, MAX_USER_AGENT);\n}\n\n/**\n * The address Cloudflare's edge reported, reduced to a safe display and key value.\n *\n * It never authorizes a request. The tunnel route may use it only for abuse\n * throttling when Cloudflare is the trusted proxy. A local process can forge it,\n * but local processes are outside that public-internet boundary.\n */\nexport function sanitizeEdgeIp(raw: string | undefined): string {\n if (raw === undefined) return 'unknown';\n const candidate = raw.split(',')[0]?.trim() ?? '';\n return /^[0-9a-f:.]{1,45}$/iu.test(candidate) ? candidate : 'unknown';\n}\n","/**\n * What a passkey is allowed to prove, and for how long.\n *\n * A session cookie is a bearer token: whoever holds the bytes is you. A passkey\n * is a private key in the device's secure enclave that never leaves it, so the\n * cookie stops being the only thing between a stolen phone and this machine.\n * The cookie does not go away, because a WebSocket cannot run a ceremony per\n * frame; what changes is that the cookie is short-lived, re-mintable with a\n * gesture rather than a QR, and insufficient on its own for the actions below.\n *\n * The crypto lives in the adapter. This file is the policy: which actions need\n * a fresh signature, how long a challenge is good for, and when a counter says\n * the credential has been cloned.\n */\n\nimport type { AuthPairingIdentity } from '@agimon-ai/po-core';\n/**\n * Actions that need a fresh gesture even from a live session.\n *\n * These are escalation paths rather than ordinary prompting or tool approval:\n * credentials redirect machine traffic, sessions run code in a selected directory,\n * repository writes change future sessions, and live MCP operations may start local\n * processes or contact remote servers.\n */\nexport const STEP_UP_ACTIONS = [\n 'provider.login',\n 'provider.logout',\n 'session.create',\n 'settings.write',\n 'mcp.discover',\n 'mcp.authorize',\n 'computer-use.activate',\n // Revoking a trusted native device ends every session it holds; from a remote caller it needs a\n // fresh gesture so a stolen cookie cannot lock the owner's phone out.\n 'device.revoke',\n 'peer.link',\n] as const;\n\nexport type StepUpAction = (typeof STEP_UP_ACTIONS)[number];\n\n/** Short enough that a captured challenge is useless, long enough for a slow Face ID. */\nexport const STEP_UP_CHALLENGE_TTL_MS = 60_000;\n/** A registration or sign-in ceremony the user has to complete. */\nexport const CEREMONY_TTL_MS = 120_000;\n\n/**\n * Which action, if any, a request is attempting.\n *\n * Matched here rather than at each route so the list of gated operations is one\n * readable table instead of three call sites that can drift apart. Anything not\n * named is not gated, which is the safe default only because the gate is an\n * addition to the session check rather than a replacement for it.\n */\nconst GATED_ROUTES: readonly { method: string; pattern: RegExp; action: StepUpAction }[] = [\n { method: 'POST', pattern: /^\\/api\\/plugins\\/session-peer\\/link\\/(?:prepare|accept|unlink)$/u, action: 'peer.link' },\n { method: 'POST', pattern: /^\\/api\\/plugins\\/marketplace\\/installs$/u, action: 'settings.write' },\n { method: 'DELETE', pattern: /^\\/api\\/plugins\\/marketplace\\/installs\\/[^/]+$/u, action: 'settings.write' },\n { method: 'POST', pattern: /^\\/api\\/workspaces$/u, action: 'session.create' },\n {\n method: 'POST',\n // Reviving a recorded session starts an agent in a directory, so it is gated\n // exactly as creating one is.\n pattern: /^\\/api\\/workspaces\\/[^/]+\\/(?:resume|sessions(?:\\/[^/]+\\/(?:resume|revive))?)$/u,\n action: 'session.create',\n },\n // The git new-session dialog starts a worktree session, which runs code in a directory.\n { method: 'POST', pattern: /^\\/api\\/workspaces\\/[^/]+\\/plugins\\/git\\/sessions$/u, action: 'session.create' },\n // Choosing a workspace's sandbox changes where its sessions run code.\n { method: 'PATCH', pattern: /^\\/api\\/workspaces\\/[^/]+$/u, action: 'settings.write' },\n // A workspace's git remote credentials redirect what the cockpit pushes and where its token goes.\n { method: 'PUT', pattern: /^\\/api\\/workspaces\\/[^/]+\\/plugins\\/git\\/auth$/u, action: 'settings.write' },\n { method: 'POST', pattern: /^\\/api\\/plugins\\/po\\/logins(?:\\/[^/]+\\/answer)?$/u, action: 'provider.login' },\n { method: 'DELETE', pattern: /^\\/api\\/plugins\\/po\\/providers\\/[^/]+$/u, action: 'provider.logout' },\n // The default preset decides which Po plugins every new session loads.\n {\n method: 'PUT',\n pattern:\n /^\\/api(?:\\/workspaces\\/[^/]+)?\\/settings\\/(?:value|repository\\/selection|images|presets(?:\\/(?:create|rename|delete|add-layer|remove-layer))?)$/u,\n action: 'settings.write',\n },\n // Saved MCP configuration changes affect future sessions, like other settings writes.\n { method: 'POST', pattern: /^\\/api(?:\\/workspaces\\/[^/]+)?\\/plugins\\/mcp\\/servers$/u, action: 'settings.write' },\n { method: 'PATCH', pattern: /^\\/api(?:\\/workspaces\\/[^/]+)?\\/plugins\\/mcp\\/servers$/u, action: 'settings.write' },\n { method: 'DELETE', pattern: /^\\/api(?:\\/workspaces\\/[^/]+)?\\/plugins\\/mcp\\/servers$/u, action: 'settings.write' },\n {\n method: 'POST',\n pattern: /^\\/api\\/workspaces\\/[^/]+\\/plugins\\/mcp\\/repository\\/discover$/u,\n action: 'mcp.discover',\n },\n {\n method: 'POST',\n pattern: /^\\/api\\/workspaces\\/[^/]+\\/plugins\\/mcp\\/repository\\/authorize$/u,\n action: 'mcp.authorize',\n },\n {\n method: 'DELETE',\n pattern: /^\\/api\\/workspaces\\/[^/]+\\/plugins\\/mcp\\/repository\\/authorize\\/[^/]+$/u,\n action: 'mcp.authorize',\n },\n // A key a plugin's MCP server asks for is a credential every session that loads it then sends.\n {\n method: 'POST',\n pattern: /^\\/api\\/workspaces\\/[^/]+\\/plugins\\/mcp\\/repository\\/secrets$/u,\n action: 'mcp.authorize',\n },\n // Creating a session MCP client hands an outside app a credential into a live session, and\n // revoking one cuts an agent off mid-conversation. Both are gated like the repository revoke.\n {\n method: 'POST',\n pattern: /^\\/api\\/workspaces\\/[^/]+\\/sessions\\/[^/]+\\/mcp\\/clients$/u,\n action: 'mcp.authorize',\n },\n {\n method: 'DELETE',\n pattern: /^\\/api\\/workspaces\\/[^/]+\\/sessions\\/[^/]+\\/mcp\\/clients\\/[^/]+$/u,\n action: 'mcp.authorize',\n },\n {\n method: 'POST',\n pattern: /^\\/api\\/workspaces\\/[^/]+\\/sessions\\/[^/]+\\/plugins\\/computer-use\\/activate$/u,\n action: 'computer-use.activate',\n },\n { method: 'DELETE', pattern: /^\\/api\\/remote\\/trusted-devices\\/[^/]+$/u, action: 'device.revoke' },\n];\nexport function stepUpActionFor(method: string, path: string): StepUpAction | undefined {\n const wanted = method.toUpperCase();\n return GATED_ROUTES.find((route) => route.method === wanted && route.pattern.test(path))?.action;\n}\n\nexport function isStepUpAction(value: unknown): value is StepUpAction {\n return typeof value === 'string' && (STEP_UP_ACTIONS as readonly string[]).includes(value);\n}\n\nexport interface StoredCredential {\n /** Opaque handle for display and revocation. */\n id: string;\n /** The authenticator's credential id, base64url, as WebAuthn reports it. */\n credentialId: string;\n /** Base64url public key; the private half never leaves the device. */\n publicKey: string;\n /** Signature counter, for clone detection. */\n counter: number;\n transports: string[];\n label: string;\n createdAt: number;\n lastUsedAt: number;\n /** The member bound at registration, retained across restart and restored only after this credential verifies. */\n account?: AuthPairingIdentity;\n}\n\nexport type CounterVerdict = 'ok' | 'clone-suspected';\n\n/**\n * Whether a signature counter moved the way a real authenticator moves it.\n *\n * A counter that stays at zero means the authenticator does not implement one,\n * which is common and not a signal. A counter that goes backwards or repeats\n * while claiming to count means two things are signing with the same key, which\n * is the definition of a cloned credential.\n */\nexport function counterVerdict(stored: number, presented: number): CounterVerdict {\n if (stored === 0 && presented === 0) return 'ok';\n return presented > stored ? 'ok' : 'clone-suspected';\n}\n\n/** Whether a ceremony or step-up challenge is still live. */\nexport function challengeIsFresh(issuedAt: number, now: number, ttlMs: number): boolean {\n return now - issuedAt < ttlMs;\n}\n\n/** A quick tunnel's domain; its hostname rotates on every start. */\nconst ROTATING_SUFFIX = '.trycloudflare.com';\nexport function isQuickTunnelHost(origin: string | undefined): boolean {\n if (origin === undefined) return false;\n try {\n return new URL(origin).hostname.toLowerCase().endsWith(ROTATING_SUFFIX);\n } catch {\n return false;\n }\n}\n/** Dotted-quad, and the bracketed form a URL uses for v6. */\nconst IPV4 = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/u;\n\n/**\n * The relying party id a passkey is bound to.\n *\n * Derived from the configured tunnel hostname and nothing else, never from a\n * request header: `rpID` is the entire scope of a credential, so a caller who\n * could influence it could mint credentials against somebody else's origin.\n *\n * Three things are refused rather than accepted and regretted later:\n *\n * - A quick tunnel, whose hostname rotates on every start, so a passkey\n * registered now would silently stop working on the next one.\n * - An IP address, which WebAuthn does not accept as a relying party id at all;\n * registering against one fails in the browser rather than here, which is a\n * much worse place to find out.\n * - Anything without a dot, which cannot be a public tunnel hostname.\n */\nexport function relyingPartyId(publicOrigin: string | undefined): string | undefined {\n if (publicOrigin === undefined) return undefined;\n let host: string;\n try {\n host = new URL(publicOrigin).hostname.toLowerCase();\n } catch {\n return undefined;\n }\n if (isQuickTunnelHost(publicOrigin)) return undefined;\n if (IPV4.test(host) || host.startsWith('[')) return undefined;\n if (!host.includes('.')) return undefined;\n return host;\n}\n","/**\n * Native device trust: message layout, key checks, and single-use challenges.\n *\n * A phone paired by QR registers two P-256 keys over the sealed gateway: an\n * identity key that signs silent reconnects, and a step-up key that only\n * biometrics unlock. Every signed message is `tag + \"\\n\" + JSON.stringify(fields)`\n * with the fields in the fixed order below, so the phone and the host build the\n * same bytes and no message can be passed off as another or as a manifest.\n *\n * No I/O and no hidden clock: the caller passes the clock, the challenge store,\n * and the record lookup, so every rule here is testable without a server.\n */\n\nimport { createPublicKey, randomBytes } from 'node:crypto';\n\nimport { DEVICE_AUTH_TAG, DEVICE_REGISTER_TAG, DEVICE_STEP_UP_TAG } from '@agimon-ai/po-core/remoteContract';\nimport type { TrustedDevicePlatform } from '@agimon-ai/po-core/remoteContract';\nimport { verifyDeviceSignature } from '@agimon-ai/po-web-security/deviceProof';\n\nimport {\n DEVICE_AUTH_CHALLENGE_TTL_MS,\n DEVICE_CHALLENGE_LIMIT,\n DEVICE_STEP_UP_CHALLENGE_TTL_MS,\n} from '../../constants/remote';\nimport type { DeviceTrust, TrustedDeviceRecord } from '../../types/remote';\nimport { sanitizeUserAgent } from '../deviceSessions';\nimport { isStepUpAction, type StepUpAction } from '../webauthnPolicy';\n\n/** Challenges and nonces are 32 random bytes, which is 43 base64url characters. */\nconst RANDOM_BYTES = 32;\nconst RANDOM_VALUE = /^[A-Za-z0-9_-]{43}$/u;\nconst CHALLENGE_ID_BYTES = 16;\n/** Opaque ids: trusted device ids, session device ids, and challenge ids. */\nconst OPAQUE_ID = /^[A-Za-z0-9_-]{1,64}$/u;\nconst MAX_SPKI_LENGTH = 512;\nconst MAX_CHANNEL_KEY_LENGTH = 128;\nconst MAX_SIGNATURE_LENGTH = 128;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/u;\nconst P256_CURVE = 'prime256v1';\nconst PLATFORMS: ReadonlySet<string> = new Set<TrustedDevicePlatform>(['ios', 'android']);\n\nexport type DeviceChallengePurpose =\n | { kind: 'auth'; trustedDeviceId: string }\n | { kind: 'step-up'; sessionDeviceId: string; action: StepUpAction };\n\nexport interface DeviceChallenge {\n id: string;\n challenge: string;\n /** The tunnel key in force when the challenge was issued; it must still be the current one. */\n hostPublicKey: string;\n issuedAt: number;\n purpose: DeviceChallengePurpose;\n}\n\nexport interface DeviceChallenges {\n issue(hostPublicKey: string, purpose: DeviceChallengePurpose): DeviceChallenge;\n /** Removes and returns a live challenge. Undefined when unknown, already used, or expired. */\n take(id: string): DeviceChallenge | undefined;\n /** Drops every challenge the predicate selects, such as those of a revoked device. */\n dropWhere(predicate: (challenge: DeviceChallenge) => boolean): void;\n clear(): void;\n size(): number;\n}\n\nexport interface DeviceChallengesOptions {\n now: () => number;\n /** Base64url random value of the given byte length; injectable for tests. */\n random?: (bytes: number) => string;\n}\n\nexport interface DeviceChannelKeys {\n session: string;\n protocol: string;\n http: string;\n}\n\nexport type RegistrationVerdict =\n | {\n ok: true;\n identityPublicKey: string;\n stepUpPublicKey: string;\n label: string;\n platform: TrustedDevicePlatform;\n }\n | { ok: false; reason: 'not-pairing' | 'invalid' };\n\nexport type AuthenticationVerdict =\n | { ok: true; record: TrustedDeviceRecord; channels: DeviceChannelKeys }\n | { ok: false };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isBase64Url(value: unknown, maximum: number): value is string {\n return typeof value === 'string' && value.length > 0 && value.length <= maximum && BASE64URL.test(value);\n}\n\nfunction ttlOf(purpose: DeviceChallengePurpose): number {\n return purpose.kind === 'auth' ? DEVICE_AUTH_CHALLENGE_TTL_MS : DEVICE_STEP_UP_CHALLENGE_TTL_MS;\n}\n\n/** `po/host-channel-key/v1`, signed by the host bundle signer. */\nexport function hostChannelKeyFields(origin: string, hostPublicKey: string, deviceNonce: string): string[] {\n return [origin, hostPublicKey, deviceNonce];\n}\n\n/** `po/device-register/v1`, signed by the identity key and separately by the step-up key. */\nexport function deviceRegisterFields(input: {\n origin: string;\n hostPublicKey: string;\n sessionDeviceId: string;\n identityPublicKey: string;\n stepUpPublicKey: string;\n platform: string;\n}): string[] {\n return [\n input.origin,\n input.hostPublicKey,\n input.sessionDeviceId,\n input.identityPublicKey,\n input.stepUpPublicKey,\n input.platform,\n ];\n}\n\n/** `po/device-auth/v1`, signed by the identity key. All three channel keys are covered. */\nexport function deviceAuthFields(input: {\n origin: string;\n challenge: string;\n hostPublicKey: string;\n trustedDeviceId: string;\n channels: DeviceChannelKeys;\n}): string[] {\n return [\n input.origin,\n input.challenge,\n input.hostPublicKey,\n input.trustedDeviceId,\n input.channels.session,\n input.channels.protocol,\n input.channels.http,\n ];\n}\n\n/** `po/device-step-up/v1`, signed by the biometric step-up key. */\nexport function deviceStepUpFields(input: {\n origin: string;\n action: string;\n sessionDeviceId: string;\n challengeId: string;\n challenge: string;\n}): string[] {\n return [input.origin, input.action, input.sessionDeviceId, input.challengeId, input.challenge];\n}\n\n/** Whether a value is a base64url DER SPKI for an EC P-256 public key, the only kind a device may register. */\nexport function isP256PublicKey(value: unknown): value is string {\n if (!isBase64Url(value, MAX_SPKI_LENGTH)) return false;\n try {\n const key = createPublicKey({ key: Buffer.from(value, 'base64url'), format: 'der', type: 'spki' });\n return key.asymmetricKeyType === 'ec' && key.asymmetricKeyDetails?.namedCurve === P256_CURVE;\n } catch {\n // Not a parseable SPKI, which is the answer: refuse it.\n return false;\n }\n}\n\n/** Whether a value is a fresh-looking 32-byte base64url nonce. */\nexport function isDeviceNonce(value: unknown): value is string {\n return typeof value === 'string' && RANDOM_VALUE.test(value);\n}\n\nexport function isOpaqueId(value: unknown): value is string {\n return typeof value === 'string' && OPAQUE_ID.test(value);\n}\n\n/**\n * Single-use challenges, bounded in count and lifetime.\n *\n * Deleted on first `take`, whatever the outcome of the check that follows, so a\n * challenge cannot be retried. Expired entries are swept on every issue, and the\n * oldest entry goes when the store is full.\n */\nexport function createDeviceChallenges(options: DeviceChallengesOptions): DeviceChallenges {\n const random = options.random ?? ((bytes: number): string => randomBytes(bytes).toString('base64url'));\n const pending = new Map<string, DeviceChallenge>();\n const live = (entry: DeviceChallenge, at: number): boolean => at - entry.issuedAt < ttlOf(entry.purpose);\n\n return {\n issue(hostPublicKey, purpose) {\n const at = options.now();\n for (const [id, entry] of pending) if (!live(entry, at)) pending.delete(id);\n while (pending.size >= DEVICE_CHALLENGE_LIMIT) {\n const oldest = pending.keys().next().value;\n if (oldest === undefined) break;\n pending.delete(oldest);\n }\n const entry: DeviceChallenge = {\n id: random(CHALLENGE_ID_BYTES),\n challenge: random(RANDOM_BYTES),\n hostPublicKey,\n issuedAt: at,\n purpose,\n };\n pending.set(entry.id, entry);\n return entry;\n },\n\n take(id) {\n const entry = pending.get(id);\n if (entry === undefined) return undefined;\n pending.delete(id);\n return live(entry, options.now()) ? entry : undefined;\n },\n\n dropWhere(predicate) {\n for (const [id, entry] of pending) if (predicate(entry)) pending.delete(id);\n },\n\n clear: () => pending.clear(),\n size: () => pending.size,\n };\n}\n\n/**\n * The public reconnect challenge.\n *\n * It never consults the trusted-device list, so a known id and an unknown one\n * produce the same shape and the route cannot be used to enumerate devices.\n * The attestation proves the fresh tunnel key with the signer the phone pinned\n * at pairing, over the phone's own nonce. Undefined while the host cannot attest.\n */\nexport function deviceAuthChallenge(input: {\n challenges: DeviceChallenges;\n trustedDeviceId: string;\n nonce: string;\n origin: string;\n hostPublicKey: string;\n attest: (fields: readonly string[]) => string | undefined;\n}): { challengeId: string; challenge: string; hostPublicKey: string; attestation: string } | undefined {\n const attestation = input.attest(hostChannelKeyFields(input.origin, input.hostPublicKey, input.nonce));\n if (attestation === undefined) return undefined;\n const issued = input.challenges.issue(input.hostPublicKey, { kind: 'auth', trustedDeviceId: input.trustedDeviceId });\n return { challengeId: issued.id, challenge: issued.challenge, hostPublicKey: input.hostPublicKey, attestation };\n}\n\n/** A step-up challenge bound to one action and one session, answered by the biometric key. */\nexport function deviceStepUpChallenge(input: {\n challenges: DeviceChallenges;\n sessionDeviceId: string;\n action: StepUpAction;\n hostPublicKey: string;\n}): { ceremonyId: string; challenge: string; kind: 'device-key' } {\n const issued = input.challenges.issue(input.hostPublicKey, {\n kind: 'step-up',\n sessionDeviceId: input.sessionDeviceId,\n action: input.action,\n });\n return { ceremonyId: issued.id, challenge: issued.challenge, kind: 'device-key' };\n}\n\n/**\n * Checks a registration from a sealed `pairing` session.\n *\n * Both keys must be distinct P-256 SPKIs and both must sign the same\n * `po/device-register/v1` message, which binds them to this origin, this\n * tunnel key, and this exact session.\n */\nexport function verifyRegistration(input: {\n origin: string;\n hostPublicKey: string;\n sessionDeviceId: string;\n trust: DeviceTrust | undefined;\n body: unknown;\n}): RegistrationVerdict {\n if (input.trust?.kind !== 'pairing') return { ok: false, reason: 'not-pairing' };\n const body = input.body;\n if (!isRecord(body)) return { ok: false, reason: 'invalid' };\n const { identityPublicKey, stepUpPublicKey, label, platform, identityProof, stepUpProof } = body;\n if (\n !isP256PublicKey(identityPublicKey) ||\n !isP256PublicKey(stepUpPublicKey) ||\n identityPublicKey === stepUpPublicKey ||\n typeof label !== 'string' ||\n typeof platform !== 'string' ||\n !PLATFORMS.has(platform) ||\n !isBase64Url(identityProof, MAX_SIGNATURE_LENGTH) ||\n !isBase64Url(stepUpProof, MAX_SIGNATURE_LENGTH)\n )\n return { ok: false, reason: 'invalid' };\n const fields = deviceRegisterFields({\n origin: input.origin,\n hostPublicKey: input.hostPublicKey,\n sessionDeviceId: input.sessionDeviceId,\n identityPublicKey,\n stepUpPublicKey,\n platform,\n });\n if (\n !verifyDeviceSignature(identityPublicKey, DEVICE_REGISTER_TAG, fields, identityProof) ||\n !verifyDeviceSignature(stepUpPublicKey, DEVICE_REGISTER_TAG, fields, stepUpProof)\n )\n return { ok: false, reason: 'invalid' };\n return {\n ok: true,\n identityPublicKey,\n stepUpPublicKey,\n // Attacker-supplied and shown in the host UI, so it is cleaned like a user agent.\n label: sanitizeUserAgent(label),\n platform: platform as TrustedDevicePlatform,\n };\n}\n\nfunction channelKeysOf(value: unknown): DeviceChannelKeys | undefined {\n if (!isRecord(value)) return undefined;\n const { session, protocol, http } = value;\n if (\n !isBase64Url(session, MAX_CHANNEL_KEY_LENGTH) ||\n !isBase64Url(protocol, MAX_CHANNEL_KEY_LENGTH) ||\n !isBase64Url(http, MAX_CHANNEL_KEY_LENGTH)\n )\n return undefined;\n if (session === protocol || session === http || protocol === http) return undefined;\n return { session, protocol, http };\n}\n\n/**\n * Checks a device sign-in. The challenge is consumed before anything else is\n * looked at, so every attempt, good or bad, burns it.\n */\nexport function verifyAuthentication(input: {\n challenges: DeviceChallenges;\n origin: string;\n /** The tunnel key in force now; a challenge issued under another one is refused. */\n hostPublicKey: string | undefined;\n find: (trustedDeviceId: string) => TrustedDeviceRecord | undefined;\n body: unknown;\n}): AuthenticationVerdict {\n const body = input.body;\n if (!isRecord(body) || !isOpaqueId(body.challengeId)) return { ok: false };\n const issued = input.challenges.take(body.challengeId);\n if (issued === undefined || issued.purpose.kind !== 'auth') return { ok: false };\n if (input.hostPublicKey === undefined || issued.hostPublicKey !== input.hostPublicKey) return { ok: false };\n if (!isOpaqueId(body.trustedDeviceId) || body.trustedDeviceId !== issued.purpose.trustedDeviceId)\n return { ok: false };\n if (!isBase64Url(body.signature, MAX_SIGNATURE_LENGTH)) return { ok: false };\n const channels = channelKeysOf(body.channels);\n if (channels === undefined) return { ok: false };\n const record = input.find(body.trustedDeviceId);\n if (record === undefined) return { ok: false };\n const fields = deviceAuthFields({\n origin: input.origin,\n challenge: issued.challenge,\n hostPublicKey: issued.hostPublicKey,\n trustedDeviceId: record.id,\n channels,\n });\n if (!verifyDeviceSignature(record.identityPublicKey, DEVICE_AUTH_TAG, fields, body.signature)) return { ok: false };\n return { ok: true, record, channels };\n}\n\n/** Checks a biometric step-up signature for one action from one device-key session. */\nexport function verifyStepUp(input: {\n challenges: DeviceChallenges;\n origin: string;\n hostPublicKey: string | undefined;\n sessionDeviceId: string;\n action: string;\n ceremonyId: unknown;\n signature: unknown;\n stepUpPublicKey: string;\n}): boolean {\n if (!isOpaqueId(input.ceremonyId) || !isStepUpAction(input.action)) return false;\n const issued = input.challenges.take(input.ceremonyId);\n if (issued === undefined || issued.purpose.kind !== 'step-up') return false;\n if (input.hostPublicKey === undefined || issued.hostPublicKey !== input.hostPublicKey) return false;\n if (issued.purpose.sessionDeviceId !== input.sessionDeviceId || issued.purpose.action !== input.action) return false;\n if (!isBase64Url(input.signature, MAX_SIGNATURE_LENGTH)) return false;\n return verifyDeviceSignature(\n input.stepUpPublicKey,\n DEVICE_STEP_UP_TAG,\n deviceStepUpFields({\n origin: input.origin,\n action: input.action,\n sessionDeviceId: input.sessionDeviceId,\n challengeId: issued.id,\n challenge: issued.challenge,\n }),\n input.signature,\n );\n}\n","import { federationEnrollmentGeneration, type FederationEnvelope, type FederationPrincipal } from '@agimon-ai/po-core';\nimport type { HubDevicePin, HubTrustState } from '@agimon-ai/po-federation';\nimport {\n isFederationIssuerOrigin,\n verifyEnvelope,\n type FederationIssuerPin,\n} from '@agimon-ai/po-web-security/deviceProof';\n\nimport { isP256PublicKey } from '../deviceTrust';\n\nexport interface HubDeviceTrustPorts {\n hostId: string;\n publicKey: string;\n now: () => number;\n /** Called only after a locally authorized claim/join. Must refuse redirects. */\n fetchIssuer?: (issuer: string) => Promise<FederationIssuerPin['jwks']>;\n store: { read(): HubTrustState; save(state: HubTrustState): boolean | Promise<boolean> };\n /** Verified current issuer authority, never a caller-supplied trust label or key. */\n accountDevice?: (\n person: FederationPrincipal,\n deviceKeyId: string,\n ) => Promise<\n | {\n publicKey: string;\n trust: 'tofu' | 'approved' | 'hub' | 'recovered' | 'org-admin';\n revoked: boolean;\n revocationEpoch: number;\n recoveredAt?: number;\n }\n | undefined\n >;\n}\n\nconst samePerson = (a: FederationPrincipal, b: FederationPrincipal) => a.issuer === b.issuer && a.subject === b.subject;\n\n/** Hub-local account pins are independent of issuer enrollment and host-scoped reconnect keys. */\nexport function createHubDeviceTrust(ports: HubDeviceTrustPorts) {\n // One mutation queue protects replay admission and pin/owner writes across awaited issuer lookups.\n let queue: Promise<unknown> = Promise.resolve();\n function mutate(work: (state: HubTrustState) => Promise<boolean>) {\n const result = queue.then(async () => {\n const state = ports.store.read();\n if (state.hostId && (state.hostId !== ports.hostId || state.publicKey !== ports.publicKey)) return false;\n state.hostId = ports.hostId;\n state.publicKey = ports.publicKey;\n if (!(await work(state))) return false;\n return ports.store.save(state);\n });\n queue = result.catch(() => false);\n return result;\n }\n function pin(state: HubTrustState, person: FederationPrincipal, deviceKeyId: string) {\n return state.pins.find((p) => p.deviceKeyId === deviceKeyId && samePerson(p.person, person));\n }\n function validPerson(person: FederationPrincipal) {\n return (\n typeof person?.issuer === 'string' && !!person.issuer && typeof person.subject === 'string' && !!person.subject\n );\n }\n function validEnrollment(envelope: FederationEnvelope<'po/hub-enrollment/v1'>) {\n const e = envelope?.payload;\n return (\n e &&\n validPerson(e) &&\n e.hostId === ports.hostId &&\n e.hostPublicKey === ports.publicKey &&\n !!federationEnrollmentGeneration(e.enrollmentGeneration) &&\n !(ports.store.read().removedEnrollments ?? []).some(\n (row) => samePerson(row, e) && federationEnrollmentGeneration(e.enrollmentGeneration) <= row.generation,\n ) &&\n typeof e.deviceKeyId === 'string' &&\n /^[A-Za-z0-9_-]{1,128}$/.test(e.deviceKeyId) &&\n isP256PublicKey(e.devicePublicKey) &&\n typeof e.pairingId === 'string' &&\n !!e.pairingId &&\n Number.isSafeInteger(e.pairedAt) &&\n e.pairedAt >= e.issuedAt &&\n e.pairedAt <= e.expiresAt &&\n e.pairedAt <= ports.now() + 30_000 &&\n verifyEnvelope(ports.publicKey, 'po/hub-enrollment/v1', envelope, ports.now())\n );\n }\n function addPin(state: HubTrustState, value: HubDevicePin) {\n const held = pin(state, value.person, value.deviceKeyId);\n if (held && held.publicKey !== value.publicKey) return false;\n if (!held) state.pins.push(value);\n else if (value.source === 'qr') {\n held.source = 'qr';\n held.pairingId = value.pairingId;\n held.revocationEpoch = value.revocationEpoch;\n delete held.trustedDeviceId;\n }\n return true;\n }\n async function currentDevice(person: FederationPrincipal, deviceKeyId: string) {\n const device = await ports.accountDevice?.(person, deviceKeyId);\n return device &&\n !device.revoked &&\n device.trust !== 'org-admin' &&\n Number.isSafeInteger(device.revocationEpoch) &&\n device.revocationEpoch >= 0\n ? device\n : undefined;\n }\n async function usablePin(state: HubTrustState, person: FederationPrincipal, deviceKeyId: string) {\n const held = pin(state, person, deviceKeyId);\n const authority = await currentDevice(person, deviceKeyId);\n if (!held || !authority || authority.publicKey !== held.publicKey) return undefined;\n if (authority.trust === 'recovered' && (held.source !== 'qr' || held.revocationEpoch !== authority.revocationEpoch))\n return undefined;\n return held;\n }\n return {\n /** Called by a locally authorized network join, never by an unauthenticated request. */\n pinIssuer(issuer: string) {\n return mutate(async (state) => {\n if (!isFederationIssuerOrigin(issuer) || !ports.fetchIssuer) return false;\n const jwks = await ports.fetchIssuer(issuer);\n state.issuers = [\n ...(state.issuers ?? []).filter((pin) => pin.issuer !== issuer),\n { issuer, jwks, fetchedAt: ports.now() },\n ];\n return true;\n });\n },\n issuer(issuer: string) {\n return ports.store.read().issuers?.find((pin) => pin.issuer === issuer);\n },\n saveIssuer(value: FederationIssuerPin) {\n return mutate(async (state) => {\n if (!state.issuers?.some((pin) => pin.issuer === value.issuer)) return false;\n state.issuers = state.issuers.map((pin) => (pin.issuer === value.issuer ? { ...pin, ...value } : pin));\n return true;\n });\n },\n pinnedDevice(person: FederationPrincipal, deviceKeyId: string) {\n const state = ports.store.read();\n if (state.hostId !== ports.hostId || state.publicKey !== ports.publicKey) return undefined;\n return pin(state, person, deviceKeyId);\n },\n owner: () => {\n const state = ports.store.read();\n return state.hostId === ports.hostId && state.publicKey === ports.publicKey ? state.owner : undefined;\n },\n /** Every owner-level federation route must check this after verifying C1/C3 and current authority. */\n async canControl(person: FederationPrincipal, deviceKeyId: string): Promise<boolean> {\n const state = ports.store.read();\n return (\n state.hostId === ports.hostId &&\n state.publicKey === ports.publicKey &&\n !!state.owner &&\n samePerson(state.owner, person) &&\n !!(await usablePin(state, person, deviceKeyId))\n );\n },\n bindAccountDevice(pairingId: string, trustedDeviceId: string) {\n return mutate(async (state) => {\n const pins = state.pins.filter((pin) => pin.source === 'qr' && pin.pairingId === pairingId);\n if (pins.some((pin) => pin.trustedDeviceId && pin.trustedDeviceId !== trustedDeviceId)) return false;\n for (const pin of pins) pin.trustedDeviceId = trustedDeviceId;\n return true;\n });\n },\n async canUnlink(deviceId: string): Promise<boolean> {\n const state = ports.store.read();\n const owner = state.owner ?? state.unlinkedOwner;\n if (!owner) return false;\n const held = state.pins.find(\n (pin) => (pin.pairingId === deviceId || pin.trustedDeviceId === deviceId) && samePerson(pin.person, owner),\n );\n return !!held && !!(await usablePin(state, owner, held.deviceKeyId));\n },\n /** Only a fresh local QR ceremony can produce the pinned host's signed attestation. */\n pinFromQr(enrollment: FederationEnvelope<'po/hub-enrollment/v1'>) {\n return mutate(async (state) => {\n if (\n !validEnrollment(enrollment) ||\n state.usedProofs.includes(enrollment.signature) ||\n state.usedProofs.includes(`qr:${enrollment.payload.pairingId}`)\n )\n return false;\n const e = enrollment.payload;\n const authority = await currentDevice(e, e.deviceKeyId);\n if (\n authority &&\n (authority.publicKey !== e.devicePublicKey ||\n (authority.recoveredAt !== undefined && e.pairedAt < authority.recoveredAt))\n )\n return false;\n if (\n !addPin(state, {\n person: { issuer: e.issuer, subject: e.subject },\n deviceKeyId: e.deviceKeyId,\n publicKey: e.devicePublicKey,\n revocationEpoch: authority?.revocationEpoch ?? 0,\n source: 'qr',\n pairingId: e.pairingId,\n })\n )\n return false;\n state.usedProofs.push(enrollment.signature, `qr:${e.pairingId}`);\n return true;\n });\n },\n approve(approval: FederationEnvelope<'po/device-approval/v1'>) {\n return mutate(async (state) => {\n const a = approval?.payload;\n if (\n !a ||\n !validPerson(a) ||\n state.usedProofs.includes(approval.signature) ||\n typeof a.networkId !== 'string' ||\n !a.networkId ||\n typeof a.newDeviceKeyId !== 'string' ||\n !/^[A-Za-z0-9_-]{1,128}$/.test(a.newDeviceKeyId)\n )\n return false;\n const approver = await usablePin(state, a, a.approverDeviceKeyId);\n if (!approver || !verifyEnvelope(approver.publicKey, 'po/device-approval/v1', approval, ports.now()))\n return false;\n const authority = await currentDevice(a, a.newDeviceKeyId);\n // Recovery and admin assistance never silently acquire local owner-level authority.\n if (\n !authority ||\n authority.revoked ||\n authority.publicKey !== a.newDeviceKey ||\n authority.trust === 'recovered' ||\n authority.trust === 'org-admin'\n )\n return false;\n if (\n !addPin(state, {\n person: { issuer: a.issuer, subject: a.subject },\n deviceKeyId: a.newDeviceKeyId,\n publicKey: a.newDeviceKey,\n revocationEpoch: authority.revocationEpoch,\n source: 'approval',\n })\n )\n return false;\n state.usedProofs.push(approval.signature);\n return true;\n });\n },\n claim(claim: FederationEnvelope<'po/hub-claim/v1'>) {\n return mutate(async (state) => {\n const c = claim?.payload;\n if (\n !c ||\n !validPerson(c) ||\n c.hostId !== ports.hostId ||\n c.hostPublicKey !== ports.publicKey ||\n (c.networkId !== undefined && (typeof c.networkId !== 'string' || !c.networkId)) ||\n state.usedProofs.includes(claim.signature) ||\n (state.owner &&\n federationEnrollmentGeneration(c.enrollmentGeneration) !==\n federationEnrollmentGeneration(state.enrollmentGeneration))\n )\n return false;\n const signer = await usablePin(state, c, c.deviceKeyId);\n const e = c.enrollment?.payload;\n if (\n !signer ||\n !e ||\n !samePerson(c, e) ||\n e.deviceKeyId !== c.deviceKeyId ||\n federationEnrollmentGeneration(c.enrollmentGeneration) !==\n federationEnrollmentGeneration(e.enrollmentGeneration) ||\n e.devicePublicKey !== signer.publicKey ||\n !validEnrollment(c.enrollment) ||\n !verifyEnvelope(signer.publicKey, 'po/hub-claim/v1', claim, ports.now()) ||\n (state.owner && !samePerson(state.owner, c))\n )\n return false;\n if (!ports.fetchIssuer) return false;\n {\n if (!isFederationIssuerOrigin(c.issuer)) return false;\n const jwks = await ports.fetchIssuer(c.issuer);\n state.issuers = [\n ...(state.issuers ?? []).filter((pin) => pin.issuer !== c.issuer),\n { issuer: c.issuer, jwks, fetchedAt: ports.now() },\n ];\n }\n state.owner = { issuer: c.issuer, subject: c.subject };\n state.ownerNetworkId = c.networkId;\n state.enrollmentGeneration = federationEnrollmentGeneration(c.enrollmentGeneration);\n delete state.unlinkedOwner;\n state.usedProofs.push(claim.signature);\n return true;\n });\n },\n };\n}\n\n/** Called only by the sealed QR-only route, before host-scoped reconnect registration. */\nexport function createHubQrEnrollment(ports: {\n hostId: string;\n publicKey: string;\n now(): number;\n trust: ReturnType<typeof createHubDeviceTrust>;\n sign(payload: import('@agimon-ai/po-core').FederationHubEnrollment): FederationEnvelope<'po/hub-enrollment/v1'>;\n}) {\n return async (pairingId: string, proof: FederationEnvelope<'po/hub-enrollment/v1'>) => {\n const p = proof?.payload;\n if (\n !p ||\n p.pairingId !== pairingId ||\n p.hostId !== ports.hostId ||\n p.hostPublicKey !== ports.publicKey ||\n p.expiresAt - p.issuedAt > 60_000 ||\n !isP256PublicKey(p.devicePublicKey) ||\n !verifyEnvelope(p.devicePublicKey, 'po/hub-enrollment/v1', proof, ports.now())\n )\n return undefined;\n const enrollment = ports.sign(p);\n return (await ports.trust.pinFromQr(enrollment)) ? enrollment : undefined;\n };\n}\n","import { randomUUID } from 'node:crypto';\n\nimport { GLOBAL_SETTINGS_READ_OPERATION } from '@agimon-ai/po-core';\nimport { federationEnrollmentGeneration } from '@agimon-ai/po-core';\nimport type {\n FederationEnvelope,\n FederationProviderConsent,\n PoFederationClient,\n FederationFireRequest,\n FederationFireOutcome,\n FederationFireReceipt,\n FederationHubUnlinkReason,\n} from '@agimon-ai/po-core';\nimport type { CallerAccess, HostTeam } from '@agimon-ai/po-core/headlessServer';\nimport {\n createFederationFeedStore,\n createHubFederationBoundary,\n createFederationGrantStore,\n createFederationHomeAccess,\n createFederationAdmissions,\n federationPartialResults,\n} from '@agimon-ai/po-federation';\nimport type { HubFederationPlatform } from '@agimon-ai/po-federation';\nimport type { HubTrustState } from '@agimon-ai/po-federation';\nimport { FEDERATION_FRESHNESS, federationEnvelopeFields } from '@agimon-ai/po-web-security';\nimport { federationDigest, createFederationIssuerHttp, verifyEnvelope } from '@agimon-ai/po-web-security/deviceProof';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\n\nimport { createHubDeviceTrust, createHubQrEnrollment } from '../hubDeviceTrust';\n\n/** Default own-hub boundary, enabled only by a durable claim and pinned issuer. */\nexport function createDefaultHubFederation(\n ports: HubFederationPlatform & {\n store: { read(): HubTrustState; save(state: HubTrustState): boolean | Promise<boolean> };\n databaseFile: string;\n now(): number;\n /** Revoke account-bound reconnect registrations, never local files or sessions. */\n removedEnrollment?(owner: import('@agimon-ai/po-core').FederationPrincipal, generation: number): Promise<void>;\n },\n) {\n let opened: Promise<Awaited<ReturnType<typeof open>>> | undefined;\n /**\n * The team of this host's owner, as the sign-in server running here lists it: undefined when the host is\n * unclaimed or its owner signed in somewhere else, `loading` while the team cannot be named.\n */\n const ownerTeam = (): HostTeam | 'loading' | undefined => {\n const state = ports.store.read();\n return state.owner && state.ownerNetworkId ? ports.team?.(state.owner) : undefined;\n };\n /** Set while this host admits a team: its owner's team has more than one person. Otherwise it is a personal host. */\n const hostTeam = (): HostTeam | 'loading' | undefined => {\n const team = ownerTeam();\n return team === 'loading' || (team !== undefined && team.size > 1) ? team : undefined;\n };\n let activeHostRequests: Omit<import('@agimon-ai/po-core/modelGateway').HostRequests, 'machineName'> | undefined;\n async function open() {\n const publicKey = ports.publicKey();\n if (!publicKey) throw new Error('The pinned host key is unavailable');\n const state = ports.store.read();\n // The pre-claim host identity is its existing physically pinned QR key.\n const hostId = state.hostId ?? publicKey;\n if (state.publicKey && state.publicKey !== publicKey) throw new Error('Host key changed');\n const database = await ports.sqlite.open(ports.databaseFile, BACKGROUND_CONTEXT);\n try {\n const storedFeed = await createFederationFeedStore(database);\n const feed = {\n ...storedFeed,\n async saveFeed(issuer: string, state: import('@agimon-ai/po-web-security/deviceProof').FederationFeedState) {\n await storedFeed.saveFeed(issuer, state);\n const owner = ports.store.read().owner;\n if (\n owner?.issuer === issuer &&\n state.records.some((row) => row.subject === owner.subject && row.deviceId === null && row.epoch === null)\n )\n await unlink('account-deleted');\n },\n };\n await database.exec(\n 'CREATE TABLE IF NOT EXISTS po_provider_consents (workspace TEXT NOT NULL, host TEXT NOT NULL, package TEXT NOT NULL, record_json TEXT NOT NULL, PRIMARY KEY(workspace, host, package))',\n );\n const consents = async (workspaceId: string): Promise<FederationProviderConsent[]> =>\n (\n await database.all<{ record_json: string }>(\n 'SELECT record_json FROM po_provider_consents WHERE workspace = ? ORDER BY host, package',\n workspaceId,\n )\n ).map((row) => JSON.parse(row.record_json) as FederationProviderConsent);\n const sign = <T extends import('@agimon-ai/po-web-security').FederationValidity>(\n tag: 'po/hub-enrollment/v1' | 'po/host-request/v1',\n payload: T,\n ) => {\n const signature = ports.attest(tag, federationEnvelopeFields(payload));\n if (!signature) throw new Error('Host signing unavailable');\n return { tag, payload, signature };\n };\n const deviceKeyProof = async (origin: string, keyId: string) => {\n const now = ports.now();\n return {\n ...sign('po/host-request/v1', {\n issuer: origin,\n hostId,\n keyId,\n issuedAt: now,\n expiresAt: now + 60_000,\n nonce: randomUUID(),\n }),\n tag: 'po/host-request/v1' as const,\n };\n };\n const issuer = async (origin: string) => ports.store.read().issuers?.find((pin) => pin.issuer === origin);\n const http = createFederationIssuerHttp({\n ...feed,\n fetch: ports.fetch,\n now: () => ports.now(),\n issuer,\n deviceKeyProof,\n });\n const trust = createHubDeviceTrust({\n hostId,\n publicKey,\n now: () => ports.now(),\n store: ports.store,\n // This bootstrap fetch is invoked only AFTER a locally pinned-device claim signature passes.\n fetchIssuer: async (origin) =>\n createFederationIssuerHttp({\n ...feed,\n fetch: ports.fetch,\n now: () => ports.now(),\n issuer: async (candidate) => (candidate === origin ? { issuer: origin, jwks: { keys: [] } } : undefined),\n }).fetchJwks(origin),\n accountDevice: async (person, keyId) => {\n if (!(await issuer(person.issuer))) {\n const local = ports.store\n .read()\n .pins.find(\n (pin) =>\n pin.deviceKeyId === keyId &&\n pin.person.issuer === person.issuer &&\n pin.person.subject === person.subject,\n );\n return local\n ? {\n publicKey: local.publicKey,\n revoked: false,\n revocationEpoch: local.revocationEpoch,\n trust: 'hub' as const,\n }\n : undefined;\n }\n const authority = await http.checkAuthority(person, keyId, await http.lookupDevice(person, keyId));\n const currentFeed = await feed.feed(person.issuer);\n const recoveredAt = currentFeed.records.reduce(\n (latest, row) =>\n row.subject === person.subject && row.epoch === authority.revocationEpoch\n ? Math.max(latest, row.createdAt)\n : latest,\n 0,\n );\n return authority.trust\n ? {\n publicKey: authority.devicePublicKey,\n revoked: authority.deviceRevoked,\n revocationEpoch: authority.revocationEpoch,\n trust: authority.trust,\n recoveredAt,\n }\n : undefined;\n },\n });\n const access = await createFederationHomeAccess(database);\n const paused = new Map<string, 'grant-expired' | 'refresh-refused'>();\n const grants = await createFederationGrantStore(database, {\n now: () => ports.now(),\n current: (grant) =>\n !network?.hostEnrollmentGeneration ||\n (network.hostEnrollmentGeneration(grant.payload.callingHostId) ===\n federationEnrollmentGeneration(grant.payload.callingEnrollmentGeneration) &&\n network.hostEnrollmentGeneration(grant.payload.targetHostId) ===\n federationEnrollmentGeneration(grant.payload.targetEnrollmentGeneration)),\n\n refresh: async (grant) =>\n ports.store.read().issuers?.some((pin) => pin.issuer === grant.payload.issuer)\n ? ports.refreshGrant?.(grant)\n : undefined,\n emit: (event) => {\n paused.set(event.workId, event.reason);\n ports.emitPaused?.(event);\n },\n });\n const admissions = await createFederationAdmissions(database, {\n hostId,\n now: () => ports.now(),\n admit: async (request) => {\n if (!ports.admitFire) throw new Error('Session admission unavailable');\n return ports.admitFire(request);\n },\n });\n let network: Awaited<ReturnType<NonNullable<HubFederationPlatform['network']>>> | undefined;\n async function unlink(_reason: FederationHubUnlinkReason) {\n const current = ports.store.read();\n if (_reason === 'host-removed') {\n if (!current.owner) return;\n await ports.removedEnrollment?.(current.owner, federationEnrollmentGeneration(current.enrollmentGeneration));\n await network?.unlink?.();\n await database.exec(\n 'DELETE FROM po_federation_work; DELETE FROM po_provider_consents; DELETE FROM po_federation_shares; DELETE FROM po_federation_consent; DELETE FROM po_federation_feed; DELETE FROM po_federation_replay;',\n );\n }\n if (\n !(await ports.store.save({\n ...current,\n unlinkedOwner: current.owner ?? current.unlinkedOwner,\n owner: undefined,\n ownerNetworkId: undefined,\n issuers: [],\n ...(_reason === 'host-removed' && current.owner\n ? {\n enrollmentGeneration: federationEnrollmentGeneration(current.enrollmentGeneration),\n pins: current.pins.filter(\n (pin) =>\n pin.person.issuer !== current.owner!.issuer || pin.person.subject !== current.owner!.subject,\n ),\n removedEnrollments: [\n ...(current.removedEnrollments ?? []).filter(\n (row) => row.issuer !== current.owner!.issuer || row.subject !== current.owner!.subject,\n ),\n { ...current.owner, generation: federationEnrollmentGeneration(current.enrollmentGeneration) },\n ],\n }\n : {}),\n }))\n )\n throw new Error('Hub unlink could not persist');\n if (_reason !== 'host-removed') await network?.unlink?.();\n await database.exec(\n 'DELETE FROM po_federation_work; DELETE FROM po_provider_consents; DELETE FROM po_federation_shares; DELETE FROM po_federation_consent; DELETE FROM po_federation_feed; DELETE FROM po_federation_replay;',\n );\n paused.clear();\n }\n async function acceptRemovalReceipt(input: unknown): Promise<boolean> {\n const receipt = input as FederationEnvelope<'po/hub-removal-receipt/v1'>;\n const current = ports.store.read();\n const payload = receipt?.payload;\n const removal = payload?.removal;\n const p = removal?.payload;\n const issuerKey = current.issuers?.find((pin) => pin.issuer === current.owner?.issuer)?.rosterPublicKey;\n const device = current.pins.find(\n (pin) =>\n pin.deviceKeyId === p?.deviceKeyId &&\n pin.person.issuer === current.owner?.issuer &&\n pin.person.subject === current.owner?.subject,\n );\n if (\n !current.owner ||\n !payload ||\n !p ||\n !issuerKey ||\n !device ||\n p.issuer !== current.owner.issuer ||\n p.subject !== current.owner.subject ||\n p.hostId !== hostId ||\n p.hostPublicKey !== publicKey ||\n !federationEnrollmentGeneration(p.enrollmentGeneration) ||\n federationEnrollmentGeneration(p.enrollmentGeneration) !==\n federationEnrollmentGeneration(current.enrollmentGeneration) ||\n !Number.isSafeInteger(payload.removedAt) ||\n payload.removedAt !== payload.issuedAt ||\n payload.removedAt > ports.now() + FEDERATION_FRESHNESS.clockSkew ||\n !['pending-quorum', 'not-required'].includes(payload.voterChange) ||\n !Array.isArray(p.changes) ||\n !verifyEnvelope(\n issuerKey,\n 'po/hub-removal-receipt/v1',\n receipt,\n Math.min(ports.now(), payload.expiresAt - FEDERATION_FRESHNESS.clockSkew - 1),\n ) ||\n !verifyEnvelope(device.publicKey, 'po/hub-removal/v1', removal, payload.removedAt)\n )\n return false;\n await unlink('host-removed');\n return true;\n }\n const boundary = await createHubFederationBoundary({\n accountDeleted: () => unlink('account-deleted'),\n database,\n trust,\n hostId,\n now: () => ports.now(),\n fetch: ports.fetch,\n deviceKeyProof,\n hostKey: async (hostId, _networkId) => network?.hostKey(hostId),\n hostEnrollmentGeneration: async (id) =>\n network?.hostEnrollmentGeneration\n ? network.hostEnrollmentGeneration(id)\n : id === hostId\n ? federationEnrollmentGeneration(ports.store.read().enrollmentGeneration)\n : 1,\n resolve: async (request) => {\n const current = ports.store.read();\n const path = new URL(request.url).pathname;\n const operationPath = path.replace(/^\\/api\\/networks\\/[^/]+\\/network\\//, '/api/network/');\n const consent = /^\\/api\\/network\\/workspaces\\/([^/]+)\\/consents(?:\\/[^/]+\\/[^/]+)?$/.exec(path);\n const fire =\n path === '/api/network/fire' && request.method === 'POST'\n ? ((await request\n .clone()\n .json()\n .catch(() => undefined)) as FederationFireRequest | undefined)\n : undefined;\n const forward =\n /^\\/api\\/network\\/workspaces\\/([^/]+)\\/calendar\\/(list|get|create|update|action|history)$/.exec(path);\n const scope = fire\n ? { workspaceId: fire.workspaceId, operation: 'fire' }\n : forward\n ? { workspaceId: decodeURIComponent(forward[1]), operation: `calendar.workspace.${forward[2]}` }\n : consent\n ? { workspaceId: decodeURIComponent(consent[1]), operation: 'provider-consent' }\n : /^\\/api\\/network\\/[^/]+$/.test(operationPath)\n ? { workspaceId: '', operation: operationPath.slice('/api/network/'.length) }\n : await ports.resolve(request);\n if (\n !scope ||\n !current.owner ||\n !current.ownerNetworkId ||\n !current.issuers?.some((pin) => pin.issuer === current.owner!.issuer)\n )\n return undefined;\n // ponytail: until phase 5, the claim's owner personal org is the only accepted network.\n return { ...scope, networkId: current.ownerNetworkId, org: current.ownerNetworkId };\n },\n authorize: async (caller, input, grant) => {\n const owner = ports.store.read().owner;\n if (owner?.issuer !== caller.principal.issuer || owner.subject !== caller.principal.subject) {\n // A teammate reaches this host's packages and nothing between hosts. What they may do with a\n // session is decided where the request lands, from the member stamp it then carries.\n const team = hostTeam();\n return (\n !!team &&\n team !== 'loading' &&\n !caller.via &&\n !grant &&\n caller.principal.issuer === team.issuer &&\n caller.org === team.org &&\n team.role(caller.principal.subject) !== undefined &&\n input.workspaceId !== '' &&\n input.operation !== 'fire' &&\n input.operation !== 'provider-consent' &&\n !input.operation.startsWith('calendar.')\n );\n }\n if (input.operation === 'fire') {\n try {\n const fire = JSON.parse(input.body) as FederationFireRequest;\n return (\n !!caller.via &&\n !!grant &&\n grant.operations.includes('fire') &&\n fire.destinationHostId === hostId &&\n fire.workspaceId === input.workspaceId &&\n fire.record?.hostId === caller.via.callingHostId &&\n grant.constraints.package === '@agimon-ai/po-calendar' &&\n grant.constraints.eventId === fire.record.recordId &&\n Object.keys(grant.constraints).length === 2\n );\n } catch {\n return false;\n }\n }\n if (caller.via && input.operation.startsWith('calendar.'))\n return (\n !!grant &&\n grant.constraints.package === '@agimon-ai/po-calendar' &&\n Object.keys(grant.constraints).length === 1\n );\n return true;\n },\n });\n network = await ports.network?.({\n hostId,\n databaseFile: `${ports.databaseFile}.network`,\n state: () => ports.store.read(),\n unlink,\n acceptRemovalReceipt,\n removedHosts: async (hosts) => {\n for (const { hostId: removedHost } of hosts) {\n await grants.purgeHost(removedHost);\n await database.run(\n \"DELETE FROM po_provider_consents WHERE host=? OR EXISTS (SELECT 1 FROM json_each(record_json,'$.grants') WHERE json_extract(value,'$.payload.callingHostId')=? OR json_extract(value,'$.payload.targetHostId')=?)\",\n removedHost,\n removedHost,\n removedHost,\n );\n await database.run('DELETE FROM po_federation_consent WHERE calling_host=?', removedHost);\n }\n },\n verify: (request) => boundary.verify(request),\n });\n activeHostRequests = network?.hostRequests;\n async function delegatedRequest(\n workId: string,\n grant: FederationEnvelope<'po/grant/v1'>,\n destination: string,\n path: string,\n body: string,\n method = 'POST',\n issuerOrigin = false,\n ): Promise<Response> {\n const token = await grants.token(workId);\n if (!token) return Response.json({ error: paused.get(workId) ?? 'refresh-refused' }, { status: 403 });\n const origin = issuerOrigin\n ? grant.payload.issuer\n : (network?.endpoint?.(destination) ??\n (grant.payload.operations.includes(GLOBAL_SETTINGS_READ_OPERATION) ? grant.payload.issuer : undefined));\n if (!origin || new URL(origin).protocol !== 'https:')\n return Response.json({ status: 'unavailable' }, { status: 503 });\n const g = grant.payload;\n const issuedAt = ports.now();\n const proof = sign('po/host-request/v1', {\n issuer: g.issuer,\n subject: g.subject,\n deviceKeyId: g.deviceKeyId,\n tokenHash: federationDigest(token),\n delegatedTokenHash: federationDigest(token),\n callingHostId: hostId,\n grantId: g.grantId,\n actingPrincipal: { issuer: g.issuer, subject: g.subject },\n destinationHostId: destination,\n networkId: g.networkId,\n workspaceId: g.workspaceId,\n method,\n canonicalTarget: path,\n bodyDigest: federationDigest(body),\n issuedAt,\n expiresAt: Math.min(\n issuedAt + FEDERATION_FRESHNESS.envelope,\n (await grants.read(workId))!.tokenExpiresAt!,\n g.expiresAt,\n ),\n nonce: randomUUID(),\n });\n return ports.fetch(new URL(path, origin), {\n method,\n ...(method === 'GET' ? {} : { body }),\n redirect: 'manual',\n credentials: 'omit',\n signal: AbortSignal.timeout(10_000),\n headers: {\n 'content-type': 'application/json',\n 'x-po-identity-token': token,\n 'x-po-federation-envelope': JSON.stringify(proof),\n 'x-po-federation-grant': JSON.stringify(grant),\n },\n });\n }\n async function calendarRequest(workId: string, kind: 'worker' | 'call', operation: string, input: unknown) {\n const work = await grants.read(workId);\n const g = work?.grant.payload;\n const state = ports.store.read();\n if (\n !work ||\n !g ||\n !state.owner ||\n g.issuer !== state.owner.issuer ||\n g.subject !== state.owner.subject ||\n g.networkId !== state.ownerNetworkId ||\n g.callingHostId !== hostId ||\n !g.operations.includes(`calendar.${kind}.${operation}`)\n )\n throw new Error('Calendar consent denied.');\n const path = `/api/calendar/${kind}/${encodeURIComponent(g.networkId)}/${encodeURIComponent(g.workspaceId)}`;\n const response = await delegatedRequest(\n workId,\n work.grant,\n g.targetHostId,\n path,\n JSON.stringify(input),\n 'POST',\n true,\n );\n if (!response.ok) throw new Error(`Central Calendar refused (${response.status}).`);\n return response.json();\n }\n const client: PoFederationClient = {\n async calendarAuthorities() {\n const state = ports.store.read();\n const result: { workId: string; workspaceId: string; securityScope: string; setupDigest: string }[] = [];\n for (const workId of await grants.under('calendar')) {\n const g = (await grants.read(workId))?.grant.payload;\n if (\n !g ||\n !state.owner ||\n g.issuer !== state.owner.issuer ||\n g.subject !== state.owner.subject ||\n g.networkId !== state.ownerNetworkId ||\n g.callingHostId !== hostId ||\n g.expiresAt <= ports.now() ||\n g.notBefore > ports.now() ||\n !g.operations.includes('calendar.worker.receive') ||\n typeof g.constraints.securityScope !== 'string' ||\n typeof g.constraints.setupDigest !== 'string'\n )\n continue;\n result.push({\n workId,\n workspaceId: g.workspaceId,\n securityScope: g.constraints.securityScope,\n setupDigest: g.constraints.setupDigest,\n });\n }\n return result;\n },\n calendarCall: async (request, workId) => {\n if ((await grants.read(workId))?.grant.payload.workspaceId !== request.workspaceId)\n throw new Error('Calendar workspace consent denied.');\n return calendarRequest(workId, 'call', request.method, request);\n },\n calendarWorker: (request, workId) => calendarRequest(workId, 'worker', request.operation, request),\n hostId: () => ports.store.read().hostId,\n owner: () => ports.store.read().owner,\n async saveGrant(workId, grant) {\n if (!ports.store.read().owner) throw new Error('Unclaimed hub');\n await grants.save(workId, grant);\n paused.delete(workId);\n },\n async fire(workId, request): Promise<FederationFireOutcome> {\n const work = await grants.read(workId);\n if (!work) return { ok: false, reason: 'denied', retryable: false, message: 'Missing grant' };\n if (\n work.grant.payload.targetHostId !== request.destinationHostId ||\n work.grant.payload.workspaceId !== request.workspaceId ||\n !work.grant.payload.operations.includes('fire')\n )\n return { ok: false, reason: 'denied', retryable: false };\n try {\n const response = await delegatedRequest(\n workId,\n work.grant,\n request.destinationHostId,\n '/api/network/fire',\n JSON.stringify(request),\n );\n if (response.ok) {\n const receipt = (await response.json()) as Partial<FederationFireReceipt> | null;\n if (\n !receipt ||\n typeof receipt.receiptId !== 'string' ||\n !receipt.receiptId ||\n typeof receipt.sessionId !== 'string' ||\n !receipt.sessionId ||\n typeof receipt.firstAdmission !== 'boolean' ||\n !Number.isSafeInteger(receipt.admittedAt)\n )\n return { ok: false, reason: 'error', retryable: false, message: 'Invalid admission receipt' };\n return { ok: true, receipt: receipt as FederationFireReceipt };\n }\n const reason =\n paused.get(workId) === 'grant-expired' || ports.now() >= work.grant.payload.expiresAt\n ? 'grant-expired'\n : response.status === 401 || response.status === 403\n ? 'denied'\n : response.status >= 500\n ? 'unavailable'\n : 'error';\n return { ok: false, reason, retryable: reason === 'unavailable' };\n } catch {\n return { ok: false, reason: 'unavailable', retryable: true };\n }\n },\n };\n return {\n ...boundary,\n client,\n consents,\n hostId,\n async requestCalendar(request: Request): Promise<Response | undefined> {\n const path = new URL(request.url).pathname;\n const match = /^\\/api\\/network\\/workspaces\\/([^/]+)\\/calendar\\/(list|get|create|update|action|history)$/.exec(\n path,\n );\n if (path !== '/api/network/fire' && !match) return undefined;\n if (request.method !== 'POST') return Response.json({ error: 'Method refused' }, { status: 405 });\n const caller = await boundary.verify(request.clone());\n if (!caller) return Response.json({ error: 'Federation proof required' }, { status: 401 });\n try {\n if (path === '/api/network/fire') {\n const fire = (await request.json()) as FederationFireRequest;\n if (!caller.via || fire.destinationHostId !== hostId)\n return Response.json({ error: 'Wrong fire destination' }, { status: 403 });\n const { actionDigest, ...fields } = fire;\n const canonical = {\n record: fields.record,\n occurrenceId: fields.occurrenceId,\n destinationHostId: fields.destinationHostId,\n workspaceId: fields.workspaceId,\n sessionId: fields.sessionId,\n cwd: fields.cwd,\n title: fields.title,\n prompt: fields.prompt,\n };\n if (\n !fire.record?.recordId ||\n !fire.occurrenceId ||\n !fire.workspaceId ||\n typeof fire.title !== 'string' ||\n typeof fire.prompt !== 'string' ||\n actionDigest !== federationDigest(JSON.stringify(canonical))\n )\n return Response.json({ error: 'Invalid fire request' }, { status: 400 });\n return Response.json(await admissions.fire(fire));\n }\n const workspaceId = decodeURIComponent(match![1]);\n if (!(await ports.workspaceExists?.(workspaceId)))\n return Response.json({ error: 'Workspace not found' }, { status: 404 });\n const operation = `calendar.workspace.${match![2]}`;\n const write = !['list', 'get', 'history'].includes(match![2]);\n const owner = ports.store.read().owner;\n if (owner?.issuer === caller.principal.issuer && owner.subject === caller.principal.subject)\n await database.run(\n 'INSERT OR IGNORE INTO po_federation_shares VALUES (?, ?, ?, ?)',\n workspaceId,\n owner.issuer,\n owner.subject,\n JSON.stringify(['view', 'edit', 'run']),\n );\n if (!(await access.permits(caller, workspaceId, write ? 'edit' : 'view', operation)))\n return Response.json({ error: 'Workspace access denied' }, { status: 403 });\n const body = (await request.json()) as { input?: Record<string, unknown>; destinationHostId?: string };\n if (write && !body.destinationHostId)\n return Response.json({ error: 'destinationHostId is required' }, { status: 400 });\n const providers = (await consents(workspaceId)).filter(\n (consent) =>\n consent.packageName === '@agimon-ai/po-calendar' &&\n consent.owner.issuer === caller.principal.issuer &&\n consent.owner.subject === caller.principal.subject,\n );\n return Response.json(\n await federationPartialResults({\n hosts: providers.map((p) => p.providerHostId),\n write,\n destinationHostId: body.destinationHostId,\n now: () => ports.now(),\n request: async (destination) => {\n const provider = providers.find((p) => p.providerHostId === destination);\n const grant = provider?.grants.find((g) => g.payload.operations.includes(operation));\n if (!grant || grant.payload.expiresAt <= ports.now())\n return Response.json({ error: 'Provider consent denied' }, { status: 403 });\n const workId = `provider/${workspaceId}/${destination}/${grant.payload.grantId}`;\n if ((await grants.read(workId))?.grant.signature !== grant.signature)\n await grants.save(workId, grant);\n // The provider derives the operation from its mounted contract, never from input.\n const input = body.input ?? {};\n const op = match![2];\n const base = `/api/workspaces/${encodeURIComponent(workspaceId)}/plugins/calendar/events`;\n const id = typeof input.id === 'string' ? encodeURIComponent(input.id) : '';\n if (!['list', 'create'].includes(op) && !id)\n return Response.json({ error: 'id is required' }, { status: 400 });\n let path = base;\n let method = 'GET';\n let payload = '';\n if (op === 'list') {\n const query = new URLSearchParams();\n if (input.query && typeof input.query === 'object')\n for (const [key, value] of Object.entries(input.query))\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')\n query.set(key, String(value));\n if (query.size) path += `?${query.toString()}`;\n } else if (op === 'create') {\n method = 'POST';\n payload = JSON.stringify({ ...(input.event as object), destinationHostId: destination });\n } else if (op === 'get') path += `/${id}`;\n else if (op === 'history') {\n path += `/${id}/history`;\n if (typeof input.cursor === 'string') path += `?cursor=${encodeURIComponent(input.cursor)}`;\n } else if (op === 'update') {\n path += `/${id}`;\n method = 'PATCH';\n payload = JSON.stringify({ ...(input.patch as object), destinationHostId: destination });\n } else {\n if (!['pause', 'resume', 'run-now', 'cancel'].includes(String(input.action)))\n return Response.json({ error: 'Invalid action' }, { status: 400 });\n path += `/${id}/action`;\n method = 'POST';\n payload = JSON.stringify({ action: input.action, destinationHostId: destination });\n }\n const response = await delegatedRequest(workId, grant, destination, path, payload, method);\n // History is one page, not a collection to flatten. Keep its continuation cursor.\n return op === 'history' && response.ok ? Response.json([await response.json()]) : response;\n },\n }),\n );\n } catch (error) {\n return Response.json(\n { error: error instanceof Error ? error.message : 'Invalid calendar request' },\n { status: 400 },\n );\n }\n },\n /**\n * Two people may hand this host a grant to read their global settings: its owner, for their own network\n * and from a device pinned here, and anyone on the team it hosts, for that team and from the device they\n * paired with. `paired` is who the sealed channel says the device is.\n */\n async requestSettingsConsent(request: Request, paired?: CallerAccess): Promise<Response | undefined> {\n if (new URL(request.url).pathname !== '/api/network/settings-consent') return undefined;\n if (request.method !== 'POST') return new Response('Method refused', { status: 405 });\n const grant = (await request\n .clone()\n .json()\n .catch(() => undefined)) as FederationEnvelope<'po/grant/v1'> | undefined;\n const g = grant?.payload;\n if (!grant || !g) return new Response('Settings consent refused', { status: 403 });\n const verified = await boundary.verify(request.clone());\n const current = ports.store.read();\n const team = hostTeam();\n const mate = paired === 'refused' ? undefined : paired?.caller;\n let consent:\n | { person: { issuer: string; subject: string }; keyId: string; networkId: string; owns: boolean }\n | undefined;\n let device: { publicKey: string; revocationEpoch: number } | undefined;\n if (\n verified &&\n !verified.via &&\n current.owner &&\n // The owner may be on the team too: the grant says which of their settings it hands over.\n g.networkId === current.ownerNetworkId &&\n verified.principal.issuer === current.owner.issuer &&\n verified.principal.subject === current.owner.subject &&\n (await trust.canControl(verified.principal, verified.device.keyId))\n ) {\n consent = {\n person: verified.principal,\n keyId: verified.device.keyId,\n networkId: current.ownerNetworkId,\n owns: true,\n };\n device = trust.pinnedDevice(verified.principal, verified.device.keyId);\n } else if (\n mate &&\n !mate.via &&\n team &&\n team !== 'loading' &&\n mate.principal.issuer === team.issuer &&\n mate.org === team.org &&\n team.role(mate.principal.subject) !== undefined\n ) {\n consent = { person: mate.principal, keyId: mate.device.keyId, networkId: team.org, owns: false };\n device = current.pins.find(\n (pin) =>\n pin.deviceKeyId === mate.device.keyId &&\n pin.person.issuer === mate.principal.issuer &&\n pin.person.subject === mate.principal.subject,\n );\n }\n if (!consent || !device) return new Response('The owner device or a teammate is required', { status: 403 });\n try {\n if (\n !verifyEnvelope(device.publicKey, 'po/grant/v1', grant, ports.now()) ||\n g.issuer !== consent.person.issuer ||\n g.subject !== consent.person.subject ||\n g.deviceKeyId !== consent.keyId ||\n (g.revocationEpoch ?? 0) !== device.revocationEpoch ||\n g.networkId !== consent.networkId ||\n g.callingHostId !== hostId ||\n // A team's settings live on the sign-in server here, so that grant names this host both ways.\n (consent.owns ? !network?.hostKey(g.targetHostId) : g.targetHostId !== hostId) ||\n g.workspaceId !== 'account' ||\n g.redelegable !== false ||\n typeof g.grantId !== 'string' ||\n !g.grantId ||\n !Number.isSafeInteger(g.notBefore) ||\n !Array.isArray(g.operations) ||\n g.operations.length !== 1 ||\n g.operations[0] !== GLOBAL_SETTINGS_READ_OPERATION ||\n Object.keys(g.constraints).length ||\n g.notBefore > ports.now()\n )\n return new Response('Settings consent refused', { status: 403 });\n // Each grant is kept apart: the owner's under the operation, a team member's beneath it.\n await client.saveGrant(\n consent.owns ? GLOBAL_SETTINGS_READ_OPERATION : `${GLOBAL_SETTINGS_READ_OPERATION}/${g.subject}`,\n grant,\n );\n ports.settingsGranted?.();\n return Response.json({ saved: true });\n } catch {\n return new Response('Settings consent refused', { status: 403 });\n }\n },\n async requestConsent(request: Request): Promise<Response | undefined> {\n const match = /^\\/api\\/network\\/workspaces\\/([^/]+)\\/consents(?:\\/([^/]+)\\/([^/]+))?$/.exec(\n new URL(request.url).pathname,\n );\n if (!match) return undefined;\n const caller = await boundary.verify(request.clone());\n const current = ports.store.read();\n if (\n !caller ||\n caller.via ||\n !current.owner ||\n caller.principal.issuer !== current.owner.issuer ||\n caller.principal.subject !== current.owner.subject ||\n !(await trust.canControl(caller.principal, caller.device.keyId))\n )\n return Response.json({ error: 'Pinned owner device required' }, { status: 403 });\n const workspaceId = decodeURIComponent(match[1]);\n if (!(await ports.workspaceExists?.(workspaceId)))\n return Response.json({ error: 'Workspace not found' }, { status: 404 });\n if (request.method === 'GET' && !match[2])\n return Response.json({\n consents: await consents(workspaceId),\n candidates: (await network?.candidates?.(workspaceId, current.owner, await consents(workspaceId))) ?? [],\n });\n if (request.method === 'DELETE' && match[2] && match[3]) {\n await database.run(\n 'DELETE FROM po_provider_consents WHERE workspace = ? AND host = ? AND package = ?',\n workspaceId,\n decodeURIComponent(match[2]),\n decodeURIComponent(match[3]),\n );\n return new Response(null, { status: 204 });\n }\n if (request.method !== 'POST' || match[2]) return Response.json({ error: 'Method refused' }, { status: 405 });\n try {\n const value = await request.json();\n if (!value || typeof value !== 'object') throw new Error('Invalid consent body');\n const body = value as Record<string, unknown>;\n if (\n typeof body.providerHostId !== 'string' ||\n typeof body.packageName !== 'string' ||\n !Array.isArray(body.grants) ||\n body.grants.length !== 2\n )\n throw new Error('Two owner grants required');\n const manifest = await network?.manifest?.(body.providerHostId);\n const packageName = body.packageName;\n const pkg = manifest?.packages.find((pkg) => pkg.name === packageName);\n if (!pkg) throw new Error('A verified provider manifest is required');\n const grants = body.grants as FederationEnvelope<'po/grant/v1'>[];\n const pin = trust.pinnedDevice(caller.principal, caller.device.keyId);\n const now = ports.now();\n for (const grant of grants) {\n const p = grant.payload;\n if (\n !pin ||\n !verifyEnvelope(pin.publicKey, 'po/grant/v1', grant, Math.max(now, p.notBefore)) ||\n p.issuedAt > now + FEDERATION_FRESHNESS.clockSkew ||\n p.issuer !== current.owner.issuer ||\n p.subject !== current.owner.subject ||\n p.deviceKeyId !== caller.device.keyId ||\n p.workspaceId !== workspaceId ||\n p.networkId !== current.ownerNetworkId ||\n p.targetHostId !== body.providerHostId ||\n p.callingHostId !== hostId ||\n p.redelegable !== false ||\n !Number.isSafeInteger(p.notBefore) ||\n p.notBefore > now + FEDERATION_FRESHNESS.clockSkew ||\n p.expiresAt - p.issuedAt > FEDERATION_FRESHNESS.grant ||\n now >= p.expiresAt - FEDERATION_FRESHNESS.clockSkew ||\n (p.revocationEpoch ?? 0) !== pin.revocationEpoch\n )\n throw new Error('Invalid owner grant');\n }\n const validation = ports.validateProviderGrants?.(\n grants.map((grant) => grant.payload),\n body.packageName,\n pkg.operations.find((op) => op.scope === 'workspace')?.names ?? [],\n ) ?? { ok: false as const, error: 'Provider consent unavailable' };\n if (!validation.ok) throw new Error(validation.error);\n const record: FederationProviderConsent = {\n workspaceId,\n providerHostId: body.providerHostId,\n packageName: body.packageName,\n owner: current.owner,\n grants,\n createdAt: now,\n expiresAt: validation.expiresAt,\n };\n await database.run(\n 'INSERT OR REPLACE INTO po_provider_consents VALUES (?, ?, ?, ?)',\n workspaceId,\n record.providerHostId,\n record.packageName,\n JSON.stringify(record),\n );\n return Response.json(record, { status: 201 });\n } catch (error) {\n return Response.json(\n { error: error instanceof Error ? error.message : 'Invalid consent' },\n { status: 400 },\n );\n }\n },\n /**\n * One answer for each person whose settings grant this host holds: its owner, and on a team host each\n * teammate. `removed` ends that person's copy here; any other refusal keeps the last one.\n */\n async accountSettings(): Promise<unknown[]> {\n const state = ports.store.read();\n const team = hostTeam();\n const answers: unknown[] = [];\n for (const workId of await grants.under(GLOBAL_SETTINGS_READ_OPERATION)) {\n const work = await grants.read(workId);\n const g = work?.grant.payload;\n if (\n !work ||\n !g ||\n g.callingHostId !== hostId ||\n g.workspaceId !== 'account' ||\n !g.operations.includes(GLOBAL_SETTINGS_READ_OPERATION)\n )\n continue;\n const person = { issuer: g.issuer, subject: g.subject };\n const binding = { ...person, org: g.networkId };\n const refused = (code: 'removed' | 'unavailable') => answers.push({ ok: false, code, binding });\n try {\n if (workId !== GLOBAL_SETTINGS_READ_OPERATION) {\n // A team that cannot be named yet removes nobody.\n if (team === 'loading') {\n refused('unavailable');\n continue;\n }\n // The grant stands while its person is on the team, their device is paired here and it has not run out.\n // ponytail: a device revoked at the sign-in server but still paired here keeps its grant until that\n // runs out (30 days at most). Ask the issuer for the device's revocation epoch here if that matters.\n const stands =\n workId === `${GLOBAL_SETTINGS_READ_OPERATION}/${g.subject}` &&\n team?.issuer === g.issuer &&\n team.org === g.networkId &&\n team.role(g.subject) !== undefined &&\n ports.now() < g.expiresAt &&\n state.pins.some(\n (pin) =>\n pin.deviceKeyId === g.deviceKeyId &&\n pin.person.issuer === g.issuer &&\n pin.person.subject === g.subject,\n );\n const here = stands ? await ports.memberSettings?.(person, g.networkId) : 'left';\n if (here === 'left') {\n await grants.remove(workId);\n refused('removed');\n } else if (here) answers.push({ ok: true, yaml: here.yaml, binding });\n else refused('unavailable');\n continue;\n }\n if (\n g.issuer !== state.owner?.issuer ||\n g.subject !== state.owner.subject ||\n g.networkId !== state.ownerNetworkId\n )\n continue;\n // The sign-in server rechecks the grant, the device and the membership before every token.\n if (!(await grants.token(workId))) {\n refused('unavailable');\n continue;\n }\n const here = await ports.memberSettings?.(person, g.networkId);\n if (here === 'left') refused('removed');\n else if (here) answers.push({ ok: true, yaml: here.yaml, binding });\n else {\n const response = await delegatedRequest(\n workId,\n work.grant,\n g.targetHostId,\n `/api/networks/${encodeURIComponent(g.networkId)}/network/${GLOBAL_SETTINGS_READ_OPERATION}`,\n '{}',\n );\n const answer = response.ok\n ? ((await response.json()) as { binding?: Partial<typeof binding> } | null)\n : undefined;\n // An answer about anyone else is no answer.\n if (\n answer?.binding?.issuer === binding.issuer &&\n answer.binding.subject === binding.subject &&\n answer.binding.org === binding.org\n )\n answers.push(answer);\n else refused('unavailable');\n }\n } catch {\n // One person's unreachable sign-in server must not cost the others their refresh.\n refused('unavailable');\n }\n }\n return answers;\n },\n network,\n unlink,\n acceptRemovalReceipt,\n trust,\n database,\n enrollAccount: createHubQrEnrollment({\n hostId,\n publicKey,\n trust,\n now: () => ports.now(),\n sign: (payload) => ({ ...sign('po/hub-enrollment/v1', payload), tag: 'po/hub-enrollment/v1' }),\n }),\n };\n } catch (error) {\n await database.close();\n throw error;\n }\n }\n const service = () =>\n (opened ??= open().catch((error) => {\n opened = undefined;\n throw error;\n }));\n return {\n team: hostTeam,\n /** What a paired device is on this host, from the account it enrolled with or the proof its request carried. */\n callerAccess(\n deviceId: string,\n verified?: import('@agimon-ai/po-web-security/deviceProof').FederationCaller,\n ): CallerAccess {\n const team = ownerTeam();\n if (!team) return undefined;\n // Until the team can be named nobody can be, so nobody is admitted.\n if (team === 'loading') return 'refused';\n const state = ports.store.read();\n const shared = team.size > 1;\n const pin = state.pins.find((held) => held.pairingId === deviceId || held.trustedDeviceId === deviceId);\n const person = verified?.principal ?? pin?.person;\n const keyId = verified?.device.keyId ?? pin?.deviceKeyId;\n // A device bound to nobody this sign-in server knows is the owner's own pairing: fine alone, refused on a team.\n if (!person || !keyId || person.issuer !== team.issuer) return shared ? 'refused' : undefined;\n if (person.subject !== state.owner?.subject) {\n // Someone else's account is a teammate or nobody. It never becomes the host's own device again, even\n // after the team is gone.\n if (team.role(person.subject) === undefined) return 'refused';\n } else if (!shared) return undefined;\n // Administering the host takes the owner's own device, enrolled at this computer's QR code.\n const owns =\n person.subject === state.owner?.subject &&\n pin?.source === 'qr' &&\n pin.person.issuer === person.issuer &&\n pin.person.subject === person.subject;\n return {\n access: owns ? 'owner' : 'member',\n // A proof that was verified is passed on whole, with the host it came through.\n caller: verified ?? {\n principal: { issuer: person.issuer, subject: person.subject },\n org: team.org,\n device: { keyId },\n },\n };\n },\n federationHost() {\n const hostPublicKey = ports.publicKey();\n if (!hostPublicKey) return undefined;\n const state = ports.store.read();\n // A re-QR after removal must claim the next generation; the phone cannot know it otherwise.\n const removed = Math.max(0, ...(state.removedEnrollments ?? []).map((row) => row.generation));\n return {\n hostId: state.hostId ?? hostPublicKey,\n hostPublicKey,\n enrollmentGeneration: state.owner ? federationEnrollmentGeneration(state.enrollmentGeneration) : removed + 1,\n };\n },\n async verify(request: Request) {\n const state = ports.store.read();\n if (!state.owner || !state.ownerNetworkId || !state.issuers?.some((pin) => pin.issuer === state.owner!.issuer))\n return undefined;\n return (await service()).verify(request);\n },\n async enrollAccount(pairingId: string, proof: FederationEnvelope<'po/hub-enrollment/v1'>) {\n return (await service()).enrollAccount(pairingId, proof);\n },\n async bindAccountDevice(pairingId: string, trustedDeviceId: string) {\n return (await service()).trust.bindAccountDevice(pairingId, trustedDeviceId);\n },\n async acceptRemovalReceipt(input: unknown) {\n return (await service()).acceptRemovalReceipt(input);\n },\n async unlinkAccount(sealedDeviceId: string) {\n const opened = await service();\n if (!(await opened.trust.canUnlink(sealedDeviceId))) return false;\n await opened.unlink('owner-request');\n return true;\n },\n async claimAccount(claim: FederationEnvelope<'po/hub-claim/v1'>) {\n const accepted = await (await service()).trust.claim(claim);\n if (!accepted) return false;\n if (!claim.payload.networkId) return true;\n const issuer = claim.payload.issuer;\n // Discovery is reached only after the locally pinned device's claim succeeds.\n const response = await ports.fetch(`${issuer}/api/auth/roster-metadata`, { redirect: 'manual' });\n if (!response.ok) throw new Error('Roster issuer discovery unavailable');\n const metadata: unknown = await response.json();\n if (\n !metadata ||\n typeof metadata !== 'object' ||\n !('issuer' in metadata) ||\n metadata.issuer !== issuer ||\n !('rosterPublicKey' in metadata) ||\n typeof metadata.rosterPublicKey !== 'string' ||\n !/^[A-Za-z0-9_-]{1,512}$/.test(metadata.rosterPublicKey)\n )\n throw new Error('Invalid roster issuer discovery');\n const current = ports.store.read();\n if (\n !(await ports.store.save({\n ...current,\n issuers: current.issuers?.map((pin) =>\n pin.issuer === issuer ? { ...pin, rosterPublicKey: metadata.rosterPublicKey as string } : pin,\n ),\n }))\n )\n throw new Error('Roster issuer pin could not persist');\n // Recompose using the newly pinned issuer rather than a pre-claim network instance.\n if (opened) {\n const previous = await opened;\n await previous.network?.close();\n await previous.database.close();\n opened = undefined;\n activeHostRequests = undefined;\n }\n return true;\n },\n async acceptNetworkRelay(socket: import('@agimon-ai/po-core/packageApi').PoApiSocket, url: URL): Promise<void> {\n const current = ports.store.read();\n if (!current.owner || !current.ownerNetworkId) {\n socket.close();\n return;\n }\n const network = (await service()).network;\n if (!network?.acceptRelay) {\n socket.close();\n return;\n }\n await network.acceptRelay(socket, url);\n },\n client: {\n hostId: () => ports.store.read().hostId,\n owner: () => ports.store.read().owner,\n saveGrant: async (workId, grant) => (await service()).client.saveGrant(workId, grant),\n fire: async (workId, request) => (await service()).client.fire(workId, request),\n calendarAuthorities: async () => (await service()).client.calendarAuthorities!(),\n calendarCall: async (request, workId) => (await service()).client.calendarCall!(request, workId),\n calendarWorker: async (request, workId) => (await service()).client.calendarWorker!(request, workId),\n } satisfies PoFederationClient,\n async hostRequests(): Promise<Omit<import('@agimon-ai/po-core/modelGateway').HostRequests, 'machineName'>> {\n const current = async () => {\n const state = ports.store.read();\n if (!state.owner || !state.ownerNetworkId) return undefined;\n return (await service()).network?.hostRequests;\n };\n await current();\n return {\n hosts: () => (ports.store.read().owner ? (activeHostRequests?.hosts() ?? []) : []),\n fetch: async (hostId, request) => (await current())?.fetch(hostId, request),\n verify: async (request, prefix) => (await current())?.verify(request, prefix),\n };\n },\n async networkPeer(): Promise<unknown> {\n return (await service()).network?.peer;\n },\n /** One signed call to the account's cloud host; `undefined` while this hub is not enrolled in a network. */\n async accountCall(operation: string, input: unknown): Promise<unknown> {\n const state = ports.store.read();\n if (!state.owner || !state.ownerNetworkId) return undefined;\n const active = await service();\n if (operation === GLOBAL_SETTINGS_READ_OPERATION) return active.accountSettings?.();\n return active.network?.accountCall?.(operation, input);\n },\n async startNetwork() {\n const state = ports.store.read();\n if (state.owner && state.ownerNetworkId) await service();\n },\n async networkComposition() {\n const state = ports.store.read();\n const team = hostTeam();\n if (!state.owner || !state.ownerNetworkId) return {};\n return {\n network: {\n hostId: (await service()).hostId,\n networkId: state.ownerNetworkId,\n // Phones bind a removal to this enrollment, so a later re-QR (generation + 1) is never purged by it.\n enrollmentGeneration: federationEnrollmentGeneration(state.enrollmentGeneration),\n // The team this host admits, so a teammate's phone knows whose settings it may hand over here.\n ...(team && team !== 'loading' ? { team: team.org } : {}),\n },\n };\n },\n async workspaceProviders(workspaceId: string) {\n const state = ports.store.read();\n if (!state.owner || !state.ownerNetworkId) return {};\n const opened = await service();\n const providers = await opened.network?.providers?.(workspaceId, state.owner, await opened.consents(workspaceId));\n return providers ? { providers } : {};\n },\n async requestNetwork(request: Request, paired?: CallerAccess): Promise<Response | undefined> {\n const path = new URL(request.url).pathname;\n if (path === '/api/web-plugin-inventory') {\n if (request.method !== 'GET') return new Response('Method refused', { status: 405 });\n const state = ports.store.read();\n const webPlugins: Record<\n string,\n NonNullable<import('@agimon-ai/po-core').FederationCapabilities['webPlugins']>\n > = {};\n if (state.owner && state.ownerNetworkId) {\n const opened = await service();\n const ids = opened.network?.rosterHostIds?.() ?? [];\n for (const id of ids) {\n const manifest = await opened.network?.manifest?.(id);\n if (manifest) webPlugins[id] = manifest.webPlugins ?? [];\n }\n }\n return Response.json(\n { networkId: state.ownerNetworkId ?? null, hostId: state.hostId ?? ports.publicKey(), webPlugins },\n { headers: { 'cache-control': 'no-store' } },\n );\n }\n const nested = /^\\/api\\/networks\\/([^/]+)\\/network\\/[^/]+$/.exec(path);\n if (!nested && !/^\\/api\\/network\\/[^/]+$/.test(path) && !path.startsWith('/api/network/workspaces/'))\n return undefined;\n const state = ports.store.read();\n if (nested && decodeURIComponent(nested[1]) !== state.ownerNetworkId)\n return Response.json({ error: 'Network not found' }, { status: 404 });\n if (!state.owner || !state.ownerNetworkId) return Response.json({ error: 'Unclaimed hub' }, { status: 401 });\n const opened = await service();\n const calendar = await opened.requestCalendar(request);\n if (calendar) return calendar;\n const settings = await opened.requestSettingsConsent(request, paired);\n if (settings) return settings;\n const consent = await opened.requestConsent(request);\n if (consent) return consent;\n return (\n (await opened.network?.request(request)) ?? Response.json({ error: 'Network unavailable' }, { status: 401 })\n );\n },\n async close() {\n if (opened) {\n const service = await opened;\n await service.network?.close();\n await service.database.close();\n }\n },\n };\n}\n","import { createHash, randomBytes } from 'node:crypto';\nimport fs, { type FileHandle } from 'node:fs/promises';\nimport path from 'node:path';\nimport { Readable } from 'node:stream';\n\nimport {\n PO_SHARE_FILE_REMOTE_OFF_MESSAGE,\n type PoOpenedRegisteredFile,\n type PoRegisteredFile,\n type PoSharedFile,\n} from '@agimon-ai/po-core/packageApi';\nimport {\n MAX_SESSION_FILE_BYTES,\n SESSION_FILE_CONTENT_TYPES,\n SESSION_FILE_DEFAULT_CONTENT_TYPE,\n sessionAttachmentRoot,\n} from '@agimon-ai/po-core/serverPlugin';\n\n/**\n * Short-lived public links to one session file, so a remote MCP server can fetch\n * what the model was asked to hand it.\n *\n * The link is the only credential, so only its hash is kept, and every way a\n * link can fail answers the same 404. A file is pinned by identity when the\n * link is minted and reopened when it is served: a path that now names another\n * file, or reaches it through a new symlink, is refused rather than followed.\n */\n\n/** Public tunnel path prefix; the token is the only segment after it. */\nexport const PUBLIC_FILE_SHARE_PREFIX = '/mcp-file/';\n\nconst TOKEN_BYTES = 32;\nconst TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/u;\nconst SHARE_TTL_MS = 10 * 60 * 1000;\nconst SHARE_DOWNLOADS = 3;\nconst MAX_LIVE_SHARES_PER_SESSION = 16;\nconst OPEN_FLAGS = fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW;\n\nexport interface PublicFileShareRequest {\n sessionId: string;\n cwd: string;\n /** Relative to cwd, or absolute. */\n path: string;\n /** Who the file is for, for the host's notice. */\n label: string;\n}\n\nexport interface PublicFileShares {\n mint(request: PublicFileShareRequest): Promise<PoSharedFile>;\n mintRegistered(sessionId: string, file: PoRegisteredFile): Promise<PoSharedFile>;\n serve(token: string, method: string): Promise<Response>;\n}\n\nexport interface PublicFileSharesOptions {\n publicOrigin(): string | undefined;\n /** Bumped whenever the tunnel goes away; a link minted under another revision is dead. */\n publicOriginRevision(): number;\n /** Never receives a token or a link. */\n onNotice(message: string): void;\n /** Locates the attachment root; defaults to the process environment, as the upload route does. */\n environment?: Readonly<Record<string, string | undefined>>;\n}\n\ninterface Share {\n sessionId: string;\n filePath: string;\n registered?: PoRegisteredFile;\n fileName: string;\n identity: string;\n size: number;\n revision: number;\n expiresAt: number;\n downloadsLeft: number;\n revoked: boolean;\n}\n\nfunction tokenDigest(token: string): string {\n return createHash('sha256').update(token).digest('base64url');\n}\n\nfunction notFound(): Response {\n return Response.json({ error: 'Not found.' }, { status: 404 });\n}\n\n/** RFC 8187 value for `filename*`: encodeURIComponent leaves a few characters the grammar forbids. */\nfunction contentDispositionName(fileName: string): string {\n return encodeURIComponent(fileName).replace(\n /['()*]/gu,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n}\n\n/** True when filePath sits strictly below the real root with no segment that starts with a dot. */\nasync function containedIn(root: string, filePath: string): Promise<boolean> {\n let realRoot: string;\n try {\n realRoot = await fs.realpath(root);\n } catch {\n return false;\n }\n const relative = path.relative(realRoot, filePath);\n return (\n relative !== '' &&\n !path.isAbsolute(relative) &&\n relative.split(path.sep).every((segment) => !segment.startsWith('.'))\n );\n}\n\n/** The real path of a shareable file: inside the session cwd or its attachment root, never through a dot segment. */\nasync function resolveShareable(\n request: PublicFileShareRequest,\n environment: Readonly<Record<string, string | undefined>>,\n): Promise<string> {\n const refused = new Error(`\"${request.path}\" is not a file in this session's working directory or attachments.`);\n if (\n request.path === '' ||\n request.path.includes('\\0') ||\n request.path.split(/[\\\\/]/u).some((segment) => segment === '.' || segment === '..')\n )\n throw refused;\n let filePath: string;\n try {\n filePath = await fs.realpath(path.resolve(request.cwd, request.path));\n } catch {\n throw refused;\n }\n const roots = [request.cwd];\n try {\n roots.push(sessionAttachmentRoot(request.sessionId, environment));\n } catch {\n // An id that cannot hold attachments only has its working directory.\n }\n for (const root of roots) if (await containedIn(root, filePath)) return filePath;\n throw refused;\n}\n\n/**\n * Opens a regular file without following a final symlink, then proves the handle is\n * still the file at that real path: a parent swapped for a symlink changes the real\n * path, and a replaced file changes the identity. Resolves undefined, with nothing\n * left open, when either check fails.\n */\nasync function openPinned(filePath: string): Promise<PoOpenedRegisteredFile | undefined> {\n let handle: FileHandle;\n try {\n handle = await fs.open(filePath, OPEN_FLAGS);\n } catch {\n return undefined;\n }\n try {\n const stat = await handle.stat();\n const named = await fs.lstat(filePath);\n if (stat.isFile() && named.dev === stat.dev && named.ino === stat.ino && (await fs.realpath(filePath)) === filePath)\n return {\n identity: [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(':'),\n size: stat.size,\n close: () => handle.close(),\n stream: () =>\n Readable.toWeb(handle.createReadStream({ start: 0, end: stat.size - 1 })) as ReadableStream<Uint8Array>,\n };\n } catch {\n // Treated like a mismatch below.\n }\n await handle.close();\n return undefined;\n}\n\nexport function createPublicFileShares(options: PublicFileSharesOptions): PublicFileShares {\n const environment = options.environment ?? process.env;\n const shares = new Map<string, Share>();\n\n const authorized = (share: Share): boolean =>\n !share.revoked &&\n Date.now() < share.expiresAt &&\n share.revision === options.publicOriginRevision() &&\n options.publicOrigin() !== undefined;\n const live = (share: Share): boolean => authorized(share) && share.downloadsLeft > 0;\n\n const mint = async (request: PublicFileShareRequest, registered?: PoRegisteredFile): Promise<PoSharedFile> => {\n const origin = options.publicOrigin();\n const revision = options.publicOriginRevision();\n if (origin === undefined) throw new Error(PO_SHARE_FILE_REMOTE_OFF_MESSAGE);\n const filePath = registered === undefined ? await resolveShareable(request, environment) : '';\n const opened = registered === undefined ? await openPinned(filePath) : await registered.open();\n if (opened === undefined) throw new Error(`\"${request.path}\" is not a regular file Po can share.`);\n const { size, identity } = opened;\n await opened.close();\n if (registered === undefined && size > MAX_SESSION_FILE_BYTES)\n throw new Error(`\"${request.path}\" is larger than the 25 MB file sharing limit.`);\n for (const [key, share] of shares) if (!live(share)) shares.delete(key);\n if (\n [...shares.values()].filter((share) => share.sessionId === request.sessionId).length >=\n MAX_LIVE_SHARES_PER_SESSION\n )\n throw new Error(\n `This session already shares ${String(MAX_LIVE_SHARES_PER_SESSION)} files. Retry after a tool call finishes.`,\n );\n const token = randomBytes(TOKEN_BYTES).toString('base64url');\n const key = tokenDigest(token);\n const fileName = registered?.fileName ?? path.basename(filePath);\n if (\n typeof identity !== 'string' ||\n !identity ||\n !Number.isSafeInteger(size) ||\n size < 0 ||\n fileName\n .split('')\n .some(\n (character) =>\n character === '/' || character === '\\\\' || character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127,\n ) ||\n !fileName\n )\n throw new Error('Invalid registered file.');\n const share: Share = {\n sessionId: request.sessionId,\n filePath,\n fileName,\n ...(registered === undefined ? {} : { registered }),\n identity,\n size,\n revision,\n expiresAt: Date.now() + SHARE_TTL_MS,\n downloadsLeft: SHARE_DOWNLOADS,\n revoked: false,\n };\n shares.set(key, share);\n options.onNotice(`file share: published \"${fileName}\" for ${request.label} on the remote-access tunnel.`);\n return {\n url: `${origin}${PUBLIC_FILE_SHARE_PREFIX}${token}`,\n fileName,\n mimeType: SESSION_FILE_CONTENT_TYPES[path.extname(fileName).toLowerCase()] ?? SESSION_FILE_DEFAULT_CONTENT_TYPE,\n size,\n expiresAt: share.expiresAt,\n maxDownloads: SHARE_DOWNLOADS,\n revoke: () => {\n share.revoked = true;\n shares.delete(key);\n },\n };\n };\n\n return {\n mint: (request) => mint(request),\n mintRegistered: (sessionId, registered) =>\n mint({ sessionId, cwd: '', path: '', label: 'explicit download' }, registered),\n async serve(token, method) {\n if ((method !== 'GET' && method !== 'HEAD') || !TOKEN_PATTERN.test(token)) return notFound();\n const key = tokenDigest(token);\n const share = shares.get(key);\n if (share === undefined) return notFound();\n if (!live(share)) {\n shares.delete(key);\n return notFound();\n }\n // Counted before the first await, so concurrent downloads cannot outrun the limit.\n if (method === 'GET') {\n share.downloadsLeft -= 1;\n if (share.downloadsLeft === 0) shares.delete(key);\n }\n const opened = await (\n share.registered === undefined ? openPinned(share.filePath) : share.registered.open()\n ).catch(() => undefined);\n if (opened === undefined || opened.identity !== share.identity || opened.size !== share.size) {\n await opened?.close();\n shares.delete(key);\n options.onNotice(`file share: refused \"${share.fileName}\" because the file changed after it was shared.`);\n return notFound();\n }\n // Opening a file yields to revocation and tunnel changes. The download already\n // reserved its allowance, so this check must not reject the final permitted GET.\n if (!authorized(share)) {\n await opened.close();\n shares.delete(key);\n return notFound();\n }\n const headers = {\n 'content-type': 'application/octet-stream',\n 'content-length': String(share.size),\n 'content-disposition': `attachment; filename*=UTF-8''${contentDispositionName(share.fileName)}`,\n 'x-content-type-options': 'nosniff',\n 'content-security-policy': \"sandbox; default-src 'none'\",\n 'cross-origin-resource-policy': 'same-origin',\n 'cache-control': 'no-store, private',\n 'referrer-policy': 'no-referrer',\n 'accept-ranges': 'none',\n 'x-robots-tag': 'noindex',\n };\n if (method === 'HEAD' || share.size === 0) {\n await opened.close();\n return new Response(method === 'HEAD' ? null : new Uint8Array(), { headers });\n }\n // The stream closes the handle when it ends, fails, or is cancelled. Bounded to the\n // pinned size, so bytes appended after the identity check are never sent.\n try {\n return new Response(opened.stream(), { headers });\n } catch {\n await opened.close();\n return notFound();\n }\n },\n };\n}\n","import { createHash, randomBytes } from 'node:crypto';\n\nimport type { AuthPairingIdentity } from '@agimon-ai/po-core';\nimport { deviceLabelFor } from '@agimon-ai/po-core/clientMetadata';\nimport type { RemoteAccessSettings } from '@agimon-ai/po-core/remoteContract';\n\nimport type { DeviceTrust } from '../../types/remote';\nimport { type DeviceRecord, deviceExpiryAt, evaluateDevice, sanitizeUserAgent, touchDevice } from '../deviceSessions';\n\n/** 256 bits. The token is scanned or set by the server, never typed, so there is no reason to economise. */\nconst TOKEN_BYTES = 32;\nconst ID_BYTES = 8;\n\nexport interface DeviceAuthOptions {\n /** Read fresh on every check, so a changed toggle takes effect on the next request. */\n settings: () => RemoteAccessSettings;\n now?: () => number;\n onNotice?: (message: string) => void;\n onDrop?: (record: DeviceRecord, reason: 'revoked' | 'expired') => void;\n}\n\nexport interface EnrolledDevice {\n /** Returned exactly once, to be sent as the cookie value. Only its digest is retained. */\n token: string;\n record: DeviceRecord;\n}\n\nexport interface DeviceAuth {\n enrol(input: { userAgent: string | undefined; trust: DeviceTrust; account?: AuthPairingIdentity }): EnrolledDevice;\n /** Changes how a live session is trusted, such as a pairing session that registered a device key. */\n setTrust(id: string, trust: DeviceTrust): boolean;\n trustOf(id: string): DeviceTrust | undefined;\n /** Revokes every session the predicate selects, through the same drop path as `revoke`. */\n revokeWhere(predicate: (record: DeviceRecord) => boolean): number;\n /** The device this cookie names, or undefined. Bumps last-seen as a side effect. */\n verify(token: string | undefined): DeviceRecord | undefined;\n revoke(id: string): boolean;\n revokeAll(): number;\n list(): readonly DeviceRecord[];\n /** Re-arms exact deadlines after expiry settings change. */\n reschedule(): void;\n /** Drops what has expired under the current settings. Returns how many went. */\n sweep(): number;\n}\n\nfunction digest(token: string): string {\n // No salt and no KDF, deliberately. The input is 256 bits of uniform\n // randomness, so there is no dictionary to attack and a slow hash would only\n // add latency to every request. Do not \"fix\" this into bcrypt.\n return createHash('sha256').update(token).digest('hex');\n}\n\n/**\n * Paired sessions, held in memory only.\n *\n * Keyed by digest rather than scanned, so verification is a map lookup and\n * there is no comparison loop for a timing side channel to live in. That is why\n * `timingSafeEqual` does not appear here: there is nothing to compare. If a\n * future change introduces a scan, it will need one.\n */\nexport function createDeviceAuth(options: DeviceAuthOptions): DeviceAuth {\n const now = options.now ?? ((): number => Date.now());\n const notice = options.onNotice ?? ((): void => {});\n /** Digest to record. The raw token exists only in flight. */\n const devices = new Map<string, DeviceRecord>();\n const timers = new Map<string, ReturnType<typeof setTimeout>>();\n\n const clearDeadline = (hash: string): void => {\n const timer = timers.get(hash);\n if (timer !== undefined) clearTimeout(timer);\n timers.delete(hash);\n };\n\n const drop = (hash: string, reason: 'revoked' | 'expired'): DeviceRecord | undefined => {\n const record = devices.get(hash);\n if (record === undefined) return undefined;\n devices.delete(hash);\n clearDeadline(hash);\n options.onDrop?.(record, reason);\n return record;\n };\n\n const schedule = (hash: string, record: DeviceRecord): void => {\n clearDeadline(hash);\n const deadline = deviceExpiryAt(record, options.settings());\n if (deadline === undefined) return;\n const remaining = deadline - now();\n if (remaining <= 0) {\n drop(hash, 'expired');\n return;\n }\n const timer = setTimeout(\n () => {\n const current = devices.get(hash);\n if (current === undefined) return;\n if (evaluateDevice(current, now(), options.settings()).ok) schedule(hash, current);\n else drop(hash, 'expired');\n },\n Math.min(remaining, 2_147_483_647),\n );\n timer.unref();\n timers.set(hash, timer);\n };\n return {\n enrol(input) {\n const token = randomBytes(TOKEN_BYTES).toString('base64url');\n const userAgent = sanitizeUserAgent(input.userAgent);\n const at = now();\n const record: DeviceRecord = {\n id: randomBytes(ID_BYTES).toString('hex'),\n tokenHash: digest(token),\n label: deviceLabelFor(userAgent),\n userAgent,\n createdAt: at,\n lastSeenAt: at,\n trust: input.trust,\n ...(input.account ? { account: { ...input.account } } : {}),\n };\n devices.set(record.tokenHash, record);\n schedule(record.tokenHash, record);\n notice(`paired ${record.label} (${record.id})`);\n return { token, record };\n },\n\n verify(token) {\n if (token === undefined || token === '') return undefined;\n const hash = digest(token);\n const at = now();\n const verdict = evaluateDevice(devices.get(hash), at, options.settings());\n if (!verdict.ok) {\n // An expired record is dropped on the way past rather than left to the\n // sweeper, so a revoked-by-time device stops appearing in the list.\n if (verdict.reason !== 'unknown') drop(hash, 'expired');\n return undefined;\n }\n const seen = touchDevice(verdict.record, at);\n devices.set(hash, seen);\n schedule(hash, seen);\n return seen;\n },\n\n revoke(id) {\n for (const [hash, record] of devices) {\n if (record.id !== id) continue;\n drop(hash, 'revoked');\n notice(`revoked ${record.label} (${record.id})`);\n return true;\n }\n return false;\n },\n\n setTrust(id, trust) {\n for (const [hash, record] of devices) {\n if (record.id !== id) continue;\n devices.set(hash, { ...record, trust });\n return true;\n }\n return false;\n },\n\n trustOf: (id) => [...devices.values()].find((record) => record.id === id)?.trust,\n\n revokeWhere(predicate) {\n const selected = [...devices].filter(([, record]) => predicate(record));\n for (const [hash, record] of selected) {\n drop(hash, 'revoked');\n notice(`revoked ${record.label} (${record.id})`);\n }\n return selected.length;\n },\n\n revokeAll() {\n const records = [...devices.values()];\n for (const [hash] of devices) drop(hash, 'revoked');\n if (records.length > 0) notice(`revoked ${String(records.length)} paired device(s)`);\n return records.length;\n },\n\n list: () => [...devices.values()],\n\n reschedule() {\n for (const [hash, record] of devices) schedule(hash, record);\n },\n sweep() {\n const at = now();\n const settings = options.settings();\n let dropped = 0;\n for (const [hash, record] of devices) {\n if (evaluateDevice(record, at, settings).ok) continue;\n drop(hash, 'expired');\n dropped += 1;\n }\n return dropped;\n },\n };\n}\n","import type { NativePushRegistration, TrustedDevicePlatform } from '@agimon-ai/po-core/remoteContract';\n\nconst MAX_TOKEN_LENGTH = 4096;\n// APNs tokens are opaque bytes. Validate hex encoding without assuming a fixed token length.\nconst APNS_TOKEN = /^(?:[a-fA-F0-9]{2})+$/u;\nconst FCM_TOKEN = /^[A-Za-z0-9_:.-]+$/u;\n\n/** Strict wire/disk validation. Return a detached value, never caller-owned metadata. */\nexport function parseNativePushRegistration(\n value: unknown,\n platform?: TrustedDevicePlatform,\n): NativePushRegistration | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const body = value as Record<string, unknown>;\n if (\n body.hostRef !== undefined &&\n (typeof body.hostRef !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u.test(body.hostRef))\n )\n return undefined;\n const attribution = body.hostRef === undefined ? {} : { hostRef: body.hostRef as string };\n if (platform !== undefined && body.platform !== platform) return undefined;\n if (typeof body.token !== 'string' || body.token.length === 0 || body.token.length > MAX_TOKEN_LENGTH)\n return undefined;\n if (body.platform === 'ios') {\n if (\n Object.keys(body).some((key) => !['platform', 'token', 'environment', 'hostRef'].includes(key)) ||\n !APNS_TOKEN.test(body.token) ||\n (body.environment !== 'development' && body.environment !== 'production')\n )\n return undefined;\n return { ...attribution, platform: 'ios', token: body.token.toLowerCase(), environment: body.environment };\n }\n if (\n body.platform !== 'android' ||\n Object.keys(body).some((key) => !['platform', 'token', 'hostRef'].includes(key)) ||\n !FCM_TOKEN.test(body.token)\n )\n return undefined;\n return { ...attribution, platform: 'android', token: body.token };\n}\n\nexport function sameNativePushRegistration(a: NativePushRegistration, b: NativePushRegistration): boolean {\n return (\n a.platform === b.platform &&\n a.token === b.token &&\n a.hostRef === b.hostRef &&\n (a.platform !== 'ios' || (b.platform === 'ios' && a.environment === b.environment))\n );\n}\n","/**\n * Pairing a device, as a state machine over injected randomness and time.\n *\n * code (120s) --claim--> pending (180s) --approve--> approved --consume--> consumed\n * | \\\n * +----- deny -------+--> denied\n *\n * The host approval step is the point. A scanned code proves someone is\n * standing where the screen is, but a screen is visible over a shoulder and in\n * a screenshare, so the code alone is a single factor for a credential that\n * ends in shell access. Approving on the machine is the second.\n *\n * Randomness and hashing arrive as functions so this file stays free of\n * node:crypto and testable with a counter.\n */\n\nimport type { AuthPairingIdentity } from '@agimon-ai/po-core';\nimport { PAIRING_CODE_TTL_MS, PAIRING_REQUEST_TTL_MS } from '@agimon-ai/po-core/remoteContract';\nimport { type PairingStatus } from '@agimon-ai/po-core/remoteContract';\n\nimport { sanitizeEdgeIp, sanitizeUserAgent } from '../deviceSessions';\n\n/** Failed claims allowed per source inside one window before the endpoint starts refusing. */\nconst ATTEMPT_LIMIT = 10;\nconst ATTEMPT_WINDOW_MS = 60_000;\n/** Caps throttle state even if many distinct peers reach the listener. */\nconst SOURCE_LIMIT = 1024;\n/** How long a settled request stays readable, so a late approval is still collectable. */\nconst PAIRING_REQUEST_RETENTION_MS = PAIRING_REQUEST_TTL_MS * 2;\n\nexport interface PairingRequest {\n id: string;\n userAgent: string;\n edgeIp: string;\n createdAt: number;\n status: PairingStatus;\n /** This claimant must prove its signed-in account before the host can approve it. */\n accountRequired?: boolean;\n account?: AuthPairingIdentity;\n}\n\nexport type ClaimOutcome = { ok: true; requestId: string } | { ok: false; code: 'unknown_code' | 'rate_limited' };\n\nexport interface PairingFlowOptions {\n /** Returns a fresh high-entropy token carried only by the QR fragment. */\n randomToken: () => string;\n /** Returns a short numeric code intended for manual entry. */\n randomManualCode: () => string;\n /** One-way digest of a token; only the digest is retained. */\n digest: (token: string) => string;\n now: () => number;\n onNotice?: (message: string) => void;\n}\n\nexport interface PairingFlow {\n /** Mints a QR token and a separate manual code. Replaces the previous pair. */\n mintCode(): { code: string; manualCode: string; expiresAt: number };\n claim(input: {\n code: string;\n userAgent: string | undefined;\n edgeIp: string | undefined;\n /** Source normalized by the adapter from trusted proxy metadata or the socket peer. */\n sourceAddress: string | undefined;\n accountRequired?: boolean;\n }): ClaimOutcome;\n status(requestId: string): PairingStatus | undefined;\n /** Internal only: the adapter resolves the issuer's one-use proof before calling this. */\n bindAccount(requestId: string, account: AuthPairingIdentity): boolean;\n approve(requestId: string): 'approved' | 'unknown' | 'expired' | 'settled' | 'account-required';\n deny(requestId: string): 'denied' | 'unknown' | 'settled';\n /** Takes an approved request exactly once, returning what the device record needs. */\n consume(requestId: string): { userAgent: string; account?: AuthPairingIdentity } | undefined;\n pending(): readonly PairingRequest[];\n /** Drops what has aged out. Only reclaims memory; expiry is derived, not scheduled. */\n sweep(): void;\n clear(): void;\n}\n\nexport function createPairingFlow(options: PairingFlowOptions): PairingFlow {\n /** Only the newest code pair is live, so minting another retires both old codes. */\n let liveCode: { hashes: readonly [string, string]; expiresAt: number } | undefined;\n const requests = new Map<string, PairingRequest>();\n const attemptsBySource = new Map<string, { windowStartedAt: number; failures: number }>();\n\n const notice = options.onNotice ?? ((): void => {});\n\n const isExpired = (request: PairingRequest, now: number): boolean =>\n request.status === 'pending' && now - request.createdAt >= PAIRING_REQUEST_TTL_MS;\n\n /** Derived rather than scheduled, so a stopped clock cannot leave a request live. */\n const statusOf = (request: PairingRequest, now: number): PairingStatus =>\n isExpired(request, now) ? 'expired' : request.status;\n\n const countFailure = (sourceAddress: string | undefined, now: number): 'ok' | 'rate_limited' => {\n const source = sourceAddress ?? 'unknown';\n let attempts = attemptsBySource.get(source);\n if (attempts === undefined || now - attempts.windowStartedAt >= ATTEMPT_WINDOW_MS) {\n if (attempts === undefined && attemptsBySource.size >= SOURCE_LIMIT) {\n const oldest = attemptsBySource.keys().next().value as string | undefined;\n if (oldest !== undefined) attemptsBySource.delete(oldest);\n }\n attempts = { windowStartedAt: now, failures: 0 };\n attemptsBySource.set(source, attempts);\n }\n attempts.failures += 1;\n if (attempts.failures === ATTEMPT_LIMIT + 1) {\n notice(`pairing claim abuse detected from ${source}; throttling invalid attempts`);\n }\n return attempts.failures > ATTEMPT_LIMIT ? 'rate_limited' : 'ok';\n };\n\n return {\n mintCode() {\n const code = options.randomToken();\n const manualCode = options.randomManualCode();\n const expiresAt = options.now() + PAIRING_CODE_TTL_MS;\n liveCode = { hashes: [options.digest(code), options.digest(manualCode)], expiresAt };\n return { code, manualCode, expiresAt };\n },\n\n claim(input) {\n const now = options.now();\n const presented = options.digest(input.code);\n // The QR token and manual code are one logical credential. A successful\n // claim retires both so neither representation can be replayed.\n if (liveCode === undefined || now >= liveCode.expiresAt || !liveCode.hashes.includes(presented)) {\n const limit = countFailure(input.sourceAddress, now);\n if (limit !== 'ok') return { ok: false, code: limit };\n return { ok: false, code: 'unknown_code' };\n }\n liveCode = undefined;\n const request: PairingRequest = {\n id: options.randomToken(),\n userAgent: sanitizeUserAgent(input.userAgent),\n edgeIp: sanitizeEdgeIp(input.edgeIp),\n createdAt: now,\n status: 'pending',\n ...(input.accountRequired ? { accountRequired: true } : {}),\n };\n requests.set(request.id, request);\n notice(`pairing requested from ${request.userAgent} via ${request.edgeIp}`);\n return { ok: true, requestId: request.id };\n },\n\n status(requestId) {\n const request = requests.get(requestId);\n return request === undefined ? undefined : statusOf(request, options.now());\n },\n\n bindAccount(requestId, account) {\n const request = requests.get(requestId);\n if (!request || statusOf(request, options.now()) !== 'pending' || !request.accountRequired || request.account)\n return false;\n request.account = { ...account };\n return true;\n },\n\n approve(requestId) {\n const request = requests.get(requestId);\n if (request === undefined) return 'unknown';\n const now = options.now();\n if (isExpired(request, now)) return 'expired';\n if (request.status !== 'pending') return 'settled';\n if (request.accountRequired && !request.account) return 'account-required';\n request.status = 'approved';\n notice(`pairing approved for ${request.userAgent}`);\n return 'approved';\n },\n\n deny(requestId) {\n const request = requests.get(requestId);\n if (request === undefined) return 'unknown';\n if (request.status !== 'pending') return 'settled';\n request.status = 'denied';\n notice(`pairing denied for ${request.userAgent}`);\n return 'denied';\n },\n\n consume(requestId) {\n const request = requests.get(requestId);\n if (request === undefined || request.status !== 'approved') return undefined;\n // Single use with no grace window. If the response is lost in flight the\n // user rescans, which costs five seconds and removes any question about\n // who else might be holding this id.\n request.status = 'consumed';\n return { userAgent: request.userAgent, ...(request.account ? { account: { ...request.account } } : {}) };\n },\n\n pending() {\n const now = options.now();\n return [...requests.values()].filter((request) => statusOf(request, now) === 'pending');\n },\n\n sweep() {\n const now = options.now();\n for (const [id, request] of requests) {\n // A settled request is kept well past its window rather than dropped on\n // sight: an approval landing in the last second still has to be\n // collected by the phone's next poll, and a denied one should read as\n // denied rather than decay into \"no such request\".\n if (now - request.createdAt >= PAIRING_REQUEST_RETENTION_MS) requests.delete(id);\n }\n if (liveCode !== undefined && now >= liveCode.expiresAt) liveCode = undefined;\n for (const [source, attempts] of attemptsBySource) {\n if (now - attempts.windowStartedAt >= ATTEMPT_WINDOW_MS) attemptsBySource.delete(source);\n }\n },\n\n clear() {\n requests.clear();\n liveCode = undefined;\n attemptsBySource.clear();\n },\n };\n}\n","/**\n * The persisted remote-access settings, and how a bad file becomes a good one.\n *\n * Every failure here is recoverable by falling back, never by throwing: a\n * corrupt settings file must not stop the cockpit from starting, because the\n * cockpit is how you would fix it.\n */\n\nimport type { RemoteAccessSettings, TunnelConfig } from '@agimon-ai/po-core/remoteContract';\n\n/** Bumped when a field changes meaning; an unrecognised version falls back to defaults. */\nexport const REMOTE_SETTINGS_VERSION = 1;\n\nconst MIN_MINUTES = 1;\nconst MAX_MINUTES = 1440;\nconst MIN_HOURS = 1;\nconst MAX_HOURS = 720;\n\n/**\n * Both time limits start off.\n *\n * The durations are still here so switching one on lands on a sensible number\n * rather than an empty field. What being off actually means: a tunnel stays up\n * until it is closed or the hub restarts, and a paired session lasts until it\n * is revoked or remote access is switched off. Those two events are the only\n * expiry there is by default.\n */\nexport const DEFAULT_REMOTE_SETTINGS: RemoteAccessSettings = {\n autoCloseEnabled: false,\n autoCloseMinutes: 60,\n sessionExpiryEnabled: false,\n idleMinutes: 30,\n absoluteHours: 12,\n tunnel: { kind: 'quick' },\n};\n\nexport interface ParsedRemoteSettings {\n settings: RemoteAccessSettings;\n /** Everything that had to be corrected, so the host can say so once rather than silently differ. */\n warnings: string[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction readBoolean(raw: unknown, fallback: boolean, field: string, warnings: string[]): boolean {\n if (raw === undefined) return fallback;\n if (typeof raw !== 'boolean') {\n warnings.push(`${field} must be true or false; using ${String(fallback)}.`);\n return fallback;\n }\n return raw;\n}\n\nfunction readClamped(\n raw: unknown,\n fallback: number,\n bounds: { min: number; max: number },\n field: string,\n warnings: string[],\n): number {\n if (raw === undefined) return fallback;\n if (typeof raw !== 'number' || !Number.isFinite(raw)) {\n warnings.push(`${field} must be a number; using ${String(fallback)}.`);\n return fallback;\n }\n const clamped = Math.min(bounds.max, Math.max(bounds.min, Math.round(raw)));\n if (clamped !== raw) {\n warnings.push(\n `${field} must be between ${String(bounds.min)} and ${String(bounds.max)}; using ${String(clamped)}.`,\n );\n }\n return clamped;\n}\n\n/**\n * A tunnel configuration is only accepted whole.\n *\n * A named tunnel missing its hostname is not a named tunnel with a default, it\n * is a misconfiguration, and quietly falling back to a quick tunnel would swap\n * a stable origin for a rotating one without telling anybody.\n */\nfunction readTunnel(raw: unknown, warnings: string[]): TunnelConfig {\n if (raw === undefined) return DEFAULT_REMOTE_SETTINGS.tunnel;\n if (!isRecord(raw)) {\n warnings.push('tunnel must be an object; using a quick tunnel.');\n return { kind: 'quick' };\n }\n if (raw.kind === 'quick') return { kind: 'quick' };\n if (raw.kind !== 'named') {\n warnings.push(`tunnel.kind must be \"quick\" or \"named\"; using a quick tunnel.`);\n return { kind: 'quick' };\n }\n if (typeof raw.hostname !== 'string' || raw.hostname === '') {\n warnings.push('A named tunnel needs a hostname; using a quick tunnel.');\n return { kind: 'quick' };\n }\n return {\n kind: 'named',\n hostname: raw.hostname,\n ...(typeof raw.name === 'string' && raw.name !== '' ? { name: raw.name } : {}),\n ...(typeof raw.tokenFile === 'string' && raw.tokenFile !== '' ? { tokenFile: raw.tokenFile } : {}),\n ...(typeof raw.configFile === 'string' && raw.configFile !== '' ? { configFile: raw.configFile } : {}),\n };\n}\n\nexport function parseRemoteAccessSettings(raw: unknown): ParsedRemoteSettings {\n const warnings: string[] = [];\n if (!isRecord(raw)) {\n return { settings: DEFAULT_REMOTE_SETTINGS, warnings };\n }\n if (raw.version !== REMOTE_SETTINGS_VERSION) {\n warnings.push(\n `Settings version ${String(raw.version)} is not version ${String(REMOTE_SETTINGS_VERSION)}; using defaults.`,\n );\n return { settings: DEFAULT_REMOTE_SETTINGS, warnings };\n }\n const defaults = DEFAULT_REMOTE_SETTINGS;\n return {\n settings: {\n autoCloseEnabled: readBoolean(raw.autoCloseEnabled, defaults.autoCloseEnabled, 'autoCloseEnabled', warnings),\n autoCloseMinutes: readClamped(\n raw.autoCloseMinutes,\n defaults.autoCloseMinutes,\n { min: MIN_MINUTES, max: MAX_MINUTES },\n 'autoCloseMinutes',\n warnings,\n ),\n sessionExpiryEnabled: readBoolean(\n raw.sessionExpiryEnabled,\n defaults.sessionExpiryEnabled,\n 'sessionExpiryEnabled',\n warnings,\n ),\n idleMinutes: readClamped(\n raw.idleMinutes,\n defaults.idleMinutes,\n { min: MIN_MINUTES, max: MAX_MINUTES },\n 'idleMinutes',\n warnings,\n ),\n absoluteHours: readClamped(\n raw.absoluteHours,\n defaults.absoluteHours,\n { min: MIN_HOURS, max: MAX_HOURS },\n 'absoluteHours',\n warnings,\n ),\n tunnel: readTunnel(raw.tunnel, warnings),\n },\n warnings,\n };\n}\n\nexport function serializeRemoteAccessSettings(settings: RemoteAccessSettings): unknown {\n return { version: REMOTE_SETTINGS_VERSION, ...settings };\n}\n","import path from 'node:path';\n\nimport { federationEnrollmentGeneration, type FederationPrincipal } from '@agimon-ai/po-core';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\nimport { nodeHost } from '@agimon-ai/po-core/platform';\nimport type { RemoteAccessSettings } from '@agimon-ai/po-core/remoteContract';\nimport type { HubTrustState } from '@agimon-ai/po-federation';\n\nimport { TRUSTED_DEVICE_LIMIT } from '../../constants/remote';\nimport type { TrustedDeviceRecord } from '../../types/remote';\nimport { parseNativePushRegistration } from '../nativePushRegistration';\nimport { DEFAULT_REMOTE_SETTINGS, parseRemoteAccessSettings, type ParsedRemoteSettings } from '../remoteAccessSettings';\nimport type { StoredCredential } from '../webauthnPolicy';\n\n/** Where the cockpit keeps machine-local state; `po sync` already writes its bundle here. */\nexport const STATE_DIRECTORY = 'web';\nexport const SETTINGS_FILE = 'remote-access.json';\nexport const CREDENTIALS_FILE = 'credentials.json';\nexport const TRUSTED_DEVICES_FILE = 'trusted-devices.json';\nexport const HUB_TRUST_FILE = 'hub-trust.json';\n\nexport function parseHubTrust(raw: string | undefined): HubTrustState {\n try {\n if (raw === undefined) return { pins: [], usedProofs: [] };\n const state = JSON.parse(raw) as HubTrustState;\n if (\n !federationEnrollmentGeneration(state.enrollmentGeneration) ||\n (state.removedEnrollments !== undefined &&\n (!Array.isArray(state.removedEnrollments) ||\n !state.removedEnrollments.every(\n (row) => isPrincipal(row) && !!federationEnrollmentGeneration(row.generation),\n ))) ||\n (state.hostId !== undefined &&\n (typeof state.hostId !== 'string' ||\n !state.hostId ||\n typeof state.publicKey !== 'string' ||\n !STORED_KEY.test(state.publicKey))) ||\n (state.ownerNetworkId !== undefined && (typeof state.ownerNetworkId !== 'string' || !state.ownerNetworkId)) ||\n (state.issuers !== undefined &&\n (!Array.isArray(state.issuers) ||\n !state.issuers.every(\n (pin) =>\n typeof pin.issuer === 'string' && pin.issuer.startsWith('https://') && Array.isArray(pin.jwks?.keys),\n ))) ||\n !Array.isArray(state.pins) ||\n !Array.isArray(state.usedProofs) ||\n !state.usedProofs.every((s) => typeof s === 'string') ||\n (state.owner !== undefined && !isPrincipal(state.owner)) ||\n (state.unlinkedOwner !== undefined && !isPrincipal(state.unlinkedOwner)) ||\n !state.pins.every(\n (p) =>\n (p.pairingId === undefined || (typeof p.pairingId === 'string' && !!p.pairingId)) &&\n (p.trustedDeviceId === undefined || (typeof p.trustedDeviceId === 'string' && !!p.trustedDeviceId)) &&\n isPrincipal(p.person) &&\n typeof p.deviceKeyId === 'string' &&\n /^[A-Za-z0-9_-]{1,128}$/.test(p.deviceKeyId) &&\n typeof p.publicKey === 'string' &&\n STORED_KEY.test(p.publicKey) &&\n Number.isSafeInteger(p.revocationEpoch) &&\n p.revocationEpoch >= 0 &&\n (p.source === 'qr' || p.source === 'approval'),\n )\n )\n throw new Error('Invalid hub trust');\n return state;\n } catch {\n // A corrupt trust file never restores authority. Local QR repair is required.\n return { pins: [], usedProofs: [] };\n }\n}\n\nexport function nativePushEnrollmentRemoved(record: TrustedDeviceRecord, state: HubTrustState): boolean {\n const binding = record.nativePushEnrollment ?? (record.person && { ...record.person, generation: 1 });\n return (\n !!binding &&\n !!state.removedEnrollments?.some(\n (row) => row.issuer === binding.issuer && row.subject === binding.subject && row.generation >= binding.generation,\n )\n );\n}\n\nfunction isPrincipal(value: unknown): value is FederationPrincipal {\n if (!value || typeof value !== 'object') return false;\n const person = value as FederationPrincipal;\n return (\n typeof person.issuer === 'string' &&\n person.issuer.length > 0 &&\n typeof person.subject === 'string' &&\n person.subject.length > 0\n );\n}\n\nconst TRUSTED_DEVICE_PLATFORMS: ReadonlySet<string> = new Set(['ios', 'android']);\nconst STORED_ID = /^[A-Za-z0-9_-]{1,64}$/u;\nconst STORED_KEY = /^[A-Za-z0-9_-]{1,512}$/u;\nconst MAX_STORED_LABEL = 200;\nexport const DIRECTORY_MODE = 0o700;\nexport const FILE_MODE = 0o600;\n/** Any bit set for group or other; a state file readable by another account is worth repairing. */\nexport const LOOSE_MODE_MASK = 0o077;\n\nexport interface RemoteAccessStoreOptions {\n /** Overridden by --state-dir and by tests; the default is ~/.po/web. */\n stateDir?: string;\n onNotice?: (message: string) => void;\n}\n\nexport interface RemoteAccessStore {\n readonly directory: string;\n settings(): RemoteAccessSettings;\n /** Re-parse the current file without losing corrections, for fail-closed automatic restore. */\n settingsForRestore(): ParsedRemoteSettings | undefined;\n save(settings: RemoteAccessSettings): void;\n /**\n * Registered passkeys. Public keys only, so the file is not a bearer secret\n * and losing it costs a re-enrolment rather than an account.\n */\n credentials(): readonly StoredCredential[];\n /** Throws on persistence failure. Failed writes leave the record unchanged. */\n saveCredential(credential: StoredCredential): void;\n /** False if absent or persistence failed. Failed writes leave the record unchanged. */\n removeCredential(id: string): boolean;\n /** Registered native devices and private push routing metadata, at most `TRUSTED_DEVICE_LIMIT`. */\n trustedDevices(): readonly TrustedDeviceRecord[];\n /** Optional only for legacy store adapters. Federation must fail closed without this port. */\n hubTrust?: { read(): HubTrustState; save(state: HubTrustState): boolean };\n /** Adds or replaces one record by id. False on persistence failure or when a new record would exceed the limit. */\n saveTrustedDevice(record: TrustedDeviceRecord): boolean;\n /** False if absent or persistence failed. Failed writes leave the record unchanged. */\n removeTrustedDevice(id: string): boolean;\n}\n\nexport function defaultRemoteStateDir(homeDir: string = nodeHost.homeDirectory()): string {\n return path.join(poHomeDirectory(homeDir), STATE_DIRECTORY);\n}\n\n/** Whether a file mode lets another account read the file. */\nexport function isLooseMode(mode: number): boolean {\n return (mode & LOOSE_MODE_MASK) !== 0;\n}\n\n/** Whether one parsed entry is a complete trusted-device record; anything else is dropped. */\nfunction isTrustedDeviceRecord(value: unknown): value is TrustedDeviceRecord {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n return (\n typeof record.id === 'string' &&\n STORED_ID.test(record.id) &&\n typeof record.identityPublicKey === 'string' &&\n STORED_KEY.test(record.identityPublicKey) &&\n typeof record.stepUpPublicKey === 'string' &&\n STORED_KEY.test(record.stepUpPublicKey) &&\n record.identityPublicKey !== record.stepUpPublicKey &&\n typeof record.label === 'string' &&\n record.label.length <= MAX_STORED_LABEL &&\n typeof record.platform === 'string' &&\n TRUSTED_DEVICE_PLATFORMS.has(record.platform) &&\n Number.isFinite(record.createdAt) &&\n Number.isFinite(record.lastSeenAt) &&\n (record.nativePushEnrollment === undefined ||\n (isPrincipal(record.nativePushEnrollment) &&\n 'generation' in record.nativePushEnrollment &&\n Number.isSafeInteger(record.nativePushEnrollment.generation) &&\n Number(record.nativePushEnrollment.generation) > 0)) &&\n ((record.person === undefined && record.accountDeviceKeyId === undefined) ||\n (isPrincipal(record.person) &&\n typeof record.accountDeviceKeyId === 'string' &&\n /^[A-Za-z0-9_-]{1,128}$/.test(record.accountDeviceKeyId)))\n );\n}\n\nexport function parseSettingsFile(\n raw: string,\n settingsPath: string,\n notice: (message: string) => void,\n): RemoteAccessSettings {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // Left in place rather than rewritten: silently overwriting a file\n // somebody hand-edited is worse than ignoring it for this run.\n notice(`remote access settings at ${settingsPath} are not valid JSON; using defaults`);\n return DEFAULT_REMOTE_SETTINGS;\n }\n const outcome = parseRemoteAccessSettings(parsed);\n for (const warning of outcome.warnings) notice(`remote access settings: ${warning}`);\n return outcome.settings;\n}\n\nfunction isStoredCredentialRecord(value: unknown): value is StoredCredential {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const record = value as StoredCredential;\n return (\n typeof record.id === 'string' &&\n !!record.id &&\n typeof record.credentialId === 'string' &&\n !!record.credentialId &&\n typeof record.publicKey === 'string' &&\n !!record.publicKey &&\n Number.isSafeInteger(record.counter) &&\n record.counter >= 0 &&\n Array.isArray(record.transports) &&\n record.transports.every((item) => typeof item === 'string') &&\n typeof record.label === 'string' &&\n record.label.length <= MAX_STORED_LABEL &&\n Number.isFinite(record.createdAt) &&\n Number.isFinite(record.lastUsedAt) &&\n (record.account === undefined ||\n (isPrincipal(record.account) && typeof record.account.org === 'string' && !!record.account.org))\n );\n}\n\nexport function parseCredentialsFile(\n raw: string,\n credentialsPath: string,\n notice: (message: string) => void,\n): StoredCredential[] {\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((entry): entry is StoredCredential => {\n if (isStoredCredentialRecord(entry)) return true;\n // Never strip malformed membership and restore the same key as an unnamed device.\n notice(`dropped an invalid passkey record from ${credentialsPath}`);\n return false;\n });\n } catch {\n // Fails closed: a half-readable credential file means enrolling again,\n // not guessing which entries survived.\n notice(`registered passkeys at ${credentialsPath} are not valid JSON; none will load`);\n return [];\n }\n}\n\nexport function parseTrustedDevicesFile(\n raw: string,\n trustedDevicesPath: string,\n notice: (message: string) => void,\n): TrustedDeviceRecord[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // Fails closed like passkeys: a device signs in only from a record read whole.\n notice(`trusted devices at ${trustedDevicesPath} are not valid JSON; none will load`);\n return [];\n }\n if (!Array.isArray(parsed)) {\n notice(`trusted devices at ${trustedDevicesPath} are not a list; none will load`);\n return [];\n }\n const loaded: TrustedDeviceRecord[] = [];\n for (const entry of parsed) {\n if (!isTrustedDeviceRecord(entry) || loaded.some((held) => held.id === entry.id)) {\n notice(`dropped an invalid trusted device record from ${trustedDevicesPath}`);\n continue;\n }\n if (loaded.length >= TRUSTED_DEVICE_LIMIT) {\n notice(`dropped trusted devices beyond the limit of ${String(TRUSTED_DEVICE_LIMIT)} from ${trustedDevicesPath}`);\n break;\n }\n const nativePush = parseNativePushRegistration(entry.nativePush, entry.platform);\n loaded.push({\n id: entry.id,\n identityPublicKey: entry.identityPublicKey,\n stepUpPublicKey: entry.stepUpPublicKey,\n label: entry.label,\n platform: entry.platform,\n createdAt: entry.createdAt,\n lastSeenAt: entry.lastSeenAt,\n ...(nativePush === undefined ? {} : { nativePush }),\n ...(entry.nativePushEnrollment === undefined ? {} : { nativePushEnrollment: { ...entry.nativePushEnrollment } }),\n ...(entry.person === undefined\n ? {}\n : { person: { ...entry.person }, accountDeviceKeyId: entry.accountDeviceKeyId }),\n });\n }\n return loaded;\n}\n\nexport function serializeStateFile(body: unknown): string {\n return `${JSON.stringify(body, undefined, 2)}\\n`;\n}\n","/**\n * Who may do what, on which listener.\n *\n * The cockpit runs one Hono app behind two sockets: a loopback listener that is\n * open to whoever already has an account on the machine, and a tunnel listener\n * that faces the public internet. Every decision here answers one question\n * about one request, with no I/O, so the whole trust boundary is readable in a\n * single sitting and testable without a server.\n */\n\nimport {\n DEVICE_AUTH_AUTHENTICATE_ROUTE,\n DEVICE_AUTH_CHALLENGE_ROUTE,\n PAIRING_ACCOUNT_ROUTE,\n PAIRING_CLAIM_ROUTE,\n PAIRING_PAGE_ROUTE,\n PAIRING_STATUS_ROUTE,\n PASSKEY_AUTH_BEGIN_ROUTE,\n PASSKEY_AUTH_FINISH_ROUTE,\n PASSKEY_REGISTER_BEGIN_ROUTE,\n PASSKEY_REGISTER_FINISH_ROUTE,\n WEB_DEV_SERVER_PORT,\n} from '@agimon-ai/po-core/remoteContract';\n\nconst METHOD_GET = 'GET';\nconst METHOD_HEAD = 'HEAD';\nconst METHOD_POST = 'POST';\n/** Cloudflare's edge speaks to us on 443, so the Host it forwards may or may not carry the port. */\nconst HTTPS_DEFAULT_PORT = '443';\n\nexport type GuardListener = 'local' | 'tunnel';\n\nexport type OriginVerdict = 'allow' | 'bad-origin' | 'bad-host' | 'not-ready';\n\nexport interface OriginPolicy {\n origins: ReadonlySet<string>;\n hosts: ReadonlySet<string>;\n}\n\nexport interface OriginVerdictInput {\n listener: GuardListener;\n method: string;\n isUpgrade: boolean;\n origin: string | undefined;\n host: string | undefined;\n local: OriginPolicy;\n /** Undefined until the tunnel reports its hostname; until then nothing on that listener is served. */\n tunnel: OriginPolicy | undefined;\n}\n\n/**\n * Which socket a request arrived on.\n *\n * Phrased as allow-only-if-provably-local on purpose. A missing env, an\n * unreadable port, or a socket torn down mid-request all resolve to 'tunnel'\n * and therefore require a credential. The mirror-image phrasing\n * (`port === tunnelPort`) fails open on every one of those.\n */\nexport function listenerOf(socketLocalPort: number | undefined, loopbackPort: number | undefined): GuardListener {\n if (loopbackPort === undefined || socketLocalPort === undefined) return 'tunnel';\n return socketLocalPort === loopbackPort ? 'local' : 'tunnel';\n}\n\n/**\n * The exact package-owned pairing and PWA bootstrap routes the tunnel listener\n * answers directly. They are matched by string equality, never prefixes or\n * wildcards. A contract test pins the list so additions require review.\n *\n * Passkey sign-in and native device sign-in are public because each creates a\n * session by proving a credential: a passkey, or a registered device identity key.\n * Passkey registration is also direct so the self-contained pairing page can run\n * it, but its handlers require the paired device cookie issued only after host\n * approval. Native device registration is not listed: it is sealed only.\n */\nexport const PUBLIC_PAIRING_ROUTES: readonly { method: string; path: string }[] = [\n { method: METHOD_GET, path: '/' },\n { method: METHOD_GET, path: PAIRING_PAGE_ROUTE },\n { method: METHOD_GET, path: '/manifest.webmanifest' },\n { method: METHOD_GET, path: '/sw.js' },\n { method: METHOD_GET, path: '/pwa/pwa.js' },\n { method: METHOD_GET, path: '/pwa/icon-192.png' },\n { method: METHOD_GET, path: '/pwa/icon-512.png' },\n { method: METHOD_POST, path: PAIRING_CLAIM_ROUTE },\n { method: METHOD_POST, path: PAIRING_ACCOUNT_ROUTE },\n { method: METHOD_GET, path: PAIRING_STATUS_ROUTE },\n { method: METHOD_POST, path: PASSKEY_AUTH_BEGIN_ROUTE },\n { method: METHOD_POST, path: PASSKEY_AUTH_FINISH_ROUTE },\n { method: METHOD_POST, path: PASSKEY_REGISTER_BEGIN_ROUTE },\n { method: METHOD_POST, path: PASSKEY_REGISTER_FINISH_ROUTE },\n { method: METHOD_POST, path: DEVICE_AUTH_CHALLENGE_ROUTE },\n { method: METHOD_POST, path: DEVICE_AUTH_AUTHENTICATE_ROUTE },\n];\n\n/**\n * Whether the tunnel listener may answer this request directly.\n *\n * Session requirements for direct routes are enforced by their exact handlers.\n * `path` must be the value the router matched on, which for Hono is\n * `c.req.path`. That value is percent-decoded, so `/%70air` reaches the `/pair`\n * handler; comparing against a separately parsed pathname would let the guard\n * and the router disagree about the same request, which is how an allowlist\n * turns into a bypass.\n */\nexport function isPublicPairingRoute(method: string, path: string): boolean {\n const wanted = method.toUpperCase();\n return PUBLIC_PAIRING_ROUTES.some((route) => route.method === wanted && route.path === path);\n}\n\n/**\n * Reads the operator's extra-origin allowlist.\n *\n * The escape hatch for a dev setup this package cannot guess: a second dev\n * server port, a reverse proxy, a `.local` hostname. Comma separated, blanks\n * dropped, so an empty or unset variable adds nothing.\n */\nexport function allowedOriginsFromEnv(raw: string | undefined): readonly string[] {\n if (raw === undefined) return [];\n return raw\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry !== '');\n}\n\n/** Normalizes to scheme://host[:port], lowercased. Undefined for anything unparseable, `null` included. */\nfunction normalizeOrigin(raw: string): string | undefined {\n try {\n return new URL(raw).origin.toLowerCase();\n } catch {\n // An Origin header that is not a URL is either the opaque `null` or a\n // forgery; neither is on any allowlist, so refusing it is the answer.\n return undefined;\n }\n}\n\nfunction normalizeHost(raw: string): string {\n return raw.trim().toLowerCase();\n}\n\n/**\n * What the loopback listener accepts.\n *\n * The port is the one the socket actually bound, not a constant, because the\n * hub takes `--port` and the e2e fixture reserves a random free one. The vite\n * dev server is allowed unconditionally so the documented two-terminal plugin\n * loop keeps working; anything that can bind that port already runs as this\n * user, so the marginal risk is close to nothing.\n */\nexport function localOriginPolicy(port: number, extraOrigins: readonly string[] = []): OriginPolicy {\n const hosts = new Set<string>();\n const origins = new Set<string>();\n // The dev server's own port belongs here too: vite proxies /api to the hub\n // without `changeOrigin`, so the browser's Host and Origin arrive unchanged\n // and both name 7534 rather than the hub's port.\n for (const listenPort of [port, WEB_DEV_SERVER_PORT]) {\n for (const name of ['127.0.0.1', 'localhost', '[::1]']) {\n const host = `${name}:${String(listenPort)}`;\n hosts.add(host);\n origins.add(`http://${host}`);\n }\n }\n for (const extra of extraOrigins) {\n const normalized = normalizeOrigin(extra);\n if (normalized !== undefined) origins.add(normalized);\n }\n return { origins, hosts };\n}\n\n/** What the tunnel listener accepts: its own origin and nothing else. */\nexport function tunnelOriginPolicy(publicOrigin: string, extraHosts: readonly string[] = []): OriginPolicy {\n const normalized = normalizeOrigin(publicOrigin);\n if (normalized === undefined) throw new Error(`The tunnel origin \"${publicOrigin}\" is not a URL.`);\n const host = new URL(normalized).host;\n const hosts = new Set([host, `${host}:${HTTPS_DEFAULT_PORT}`]);\n for (const extra of extraHosts) hosts.add(normalizeHost(extra));\n return { origins: new Set([normalized]), hosts };\n}\n\n/** A request with a side effect: anything that is not a plain read, plus every socket upgrade. */\nfunction isMutating(method: string, isUpgrade: boolean): boolean {\n if (isUpgrade) return true;\n const wanted = method.toUpperCase();\n return wanted !== METHOD_GET && wanted !== METHOD_HEAD;\n}\n\n/**\n * Whether the request's Origin and Host are ones this listener answers to.\n *\n * The loopback listener is lenient about a missing Origin and strict about one\n * that is present. That asymmetry is deliberate: a browser always sends Origin\n * on a socket handshake and on a cross-origin mutation, which is the attack\n * this closes, while curl, the health probe, and the test harness send none and\n * would break for no security gain. It buys nothing against a local program,\n * which can send whatever it likes, and is not meant to.\n *\n * The tunnel listener requires Origin on anything with a side effect and\n * tolerates its absence only on a plain read, because a top-level navigation\n * (following the scanned link) legitimately sends none.\n *\n * Host is checked on both. On the loopback listener that is the DNS-rebinding\n * defence for a well-known port, and it is the only check a socket upgrade gets\n * at all, since the upgrade path never reaches the node-server host parsing.\n */\nexport function originVerdict(input: OriginVerdictInput): OriginVerdict {\n const policy = input.listener === 'local' ? input.local : input.tunnel;\n // Before the tunnel names itself there is no legitimate traffic to serve and\n // no origin to compare against, so the listener answers nothing at all.\n if (policy === undefined) return 'not-ready';\n\n if (input.host === undefined || !policy.hosts.has(normalizeHost(input.host))) return 'bad-host';\n\n if (input.origin === undefined) {\n if (input.listener === 'local') return 'allow';\n return isMutating(input.method, input.isUpgrade) ? 'bad-origin' : 'allow';\n }\n\n const origin = normalizeOrigin(input.origin);\n if (origin === undefined || !policy.origins.has(origin)) return 'bad-origin';\n return 'allow';\n}\n","import { createHash, randomBytes } from 'node:crypto';\n\nimport type { AuthPairingIdentity } from '@agimon-ai/po-core';\nimport {\n generateAuthenticationOptions,\n generateRegistrationOptions,\n verifyAuthenticationResponse,\n verifyRegistrationResponse,\n} from '@simplewebauthn/server';\n\nimport {\n CEREMONY_TTL_MS,\n STEP_UP_CHALLENGE_TTL_MS,\n type StepUpAction,\n type StoredCredential,\n challengeIsFresh,\n counterVerdict,\n relyingPartyId,\n} from '../webauthnPolicy';\n\nconst ID_BYTES = 8;\nconst CEREMONY_ID_BYTES = 16;\nconst USER_ID_BYTES = 16;\nconst MAX_PENDING_CEREMONIES = 256;\nconst RP_NAME = 'Po cockpit';\n/** A display name only. An account-bound passkey has its own member-specific user handle. */\nconst OWNER_NAME = 'this machine';\nexport interface WebAuthnOptions {\n /** The tunnel origin, or undefined while remote access is off. */\n publicOrigin: () => string | undefined;\n /** Current credential objects. A successful write replaces the object, even for a zero-counter key. */\n credentials: () => readonly StoredCredential[];\n /** Synchronous durable write. Throws on failure so no session or step-up is granted. */\n saveCredential: (credential: StoredCredential) => void;\n removeCredential: (id: string) => boolean;\n /** The server-verified member of this paired caller, captured when registration begins. */\n accountForCaller?: (caller: string) => AuthPairingIdentity | undefined;\n now?: () => number;\n onNotice?: (message: string) => void;\n}\n\nexport type PasskeySupport = { supported: true; rpId: string } | { supported: false; reason: string };\n\nexport interface BegunCeremony {\n ceremonyId: string;\n options: Record<string, unknown>;\n}\n\nexport interface WebAuthn {\n /** Whether the current tunnel can carry passkeys at all. */\n support(): PasskeySupport;\n beginRegistration(caller: string, label: string): Promise<BegunCeremony | undefined>;\n finishRegistration(\n ceremonyId: string,\n caller: string,\n response: unknown,\n label: string,\n ): Promise<{ ok: true; id: string } | { ok: false; error: string }>;\n beginAuthentication(caller: string): Promise<BegunCeremony | undefined>;\n finishAuthentication(\n ceremonyId: string,\n caller: string,\n response: unknown,\n ): Promise<{ ok: true; credential: StoredCredential } | { ok: false; error: string }>;\n /** Mints a challenge bound to one caller and action, good once and briefly. */\n beginStepUp(caller: string, action: StepUpAction): Promise<BegunCeremony | undefined>;\n finishStepUp(ceremonyId: string, caller: string, action: StepUpAction, response: unknown): Promise<boolean>;\n clearChallenges(): void;\n}\n\ntype CeremonyType = 'registration' | 'authentication' | 'step-up';\n\ninterface PendingChallenge {\n challenge: string;\n issuedAt: number;\n caller: string;\n type: CeremonyType;\n /** Present for a step-up, so a challenge minted for one action cannot authorise another. */\n action?: StepUpAction;\n account?: AuthPairingIdentity;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Passkeys over the tunnel, and the step-up gate in front of the two actions a\n * live session should not be enough for.\n *\n * `rpID` and `expectedOrigin` come from the configured tunnel hostname, never\n * from the request. That is the entire scope of a credential, so a caller that\n * could influence it could mint credentials against somebody else's origin.\n */\nexport function createWebAuthn(options: WebAuthnOptions): WebAuthn {\n const now = options.now ?? ((): number => Date.now());\n const notice = options.onNotice ?? ((): void => {});\n /** One synthetic subject, stable for the life of the process. */\n const userId = randomBytes(USER_ID_BYTES);\n const pending = new Map<string, PendingChallenge>();\n\n const support = (): PasskeySupport => {\n const origin = options.publicOrigin();\n const rpId = relyingPartyId(origin);\n if (origin === undefined) return { supported: false, reason: 'Remote access is not on.' };\n if (rpId === undefined) {\n return {\n supported: false,\n reason:\n 'A quick tunnel gets a new hostname every start, so a passkey registered now would not work again. Configure a named tunnel to use passkeys.',\n };\n }\n return { supported: true, rpId };\n };\n\n const ceremonyKey = (id: string, caller: string, type: CeremonyType): string => `${type}\\u0000${caller}\\u0000${id}`;\n const ttlFor = (held: PendingChallenge): number =>\n held.type === 'step-up' ? STEP_UP_CHALLENGE_TTL_MS : CEREMONY_TTL_MS;\n\n const sweepPending = (): void => {\n const at = now();\n for (const [id, held] of pending) {\n if (!challengeIsFresh(held.issuedAt, at, ttlFor(held))) pending.delete(id);\n }\n };\n\n const remember = (type: CeremonyType, caller: string, challenge: string, action?: StepUpAction): string => {\n sweepPending();\n while (pending.size >= MAX_PENDING_CEREMONIES) {\n const oldest = pending.keys().next().value as string | undefined;\n if (oldest === undefined) break;\n pending.delete(oldest);\n }\n let id: string;\n do {\n id = randomBytes(CEREMONY_ID_BYTES).toString('base64url');\n } while (pending.has(ceremonyKey(id, caller, type)));\n pending.set(ceremonyKey(id, caller, type), {\n challenge,\n issuedAt: now(),\n caller,\n type,\n ...(action === undefined ? {} : { action }),\n });\n return id;\n };\n\n const take = (id: string, caller: string, type: CeremonyType, action?: StepUpAction): string | undefined => {\n const key = ceremonyKey(id, caller, type);\n const held = pending.get(key);\n if (held === undefined) return undefined;\n if (!challengeIsFresh(held.issuedAt, now(), ttlFor(held))) {\n pending.delete(key);\n return undefined;\n }\n if (held.caller !== caller || held.type !== type || held.action !== action) return undefined;\n pending.delete(key);\n return held.challenge;\n };\n\n return {\n support,\n\n async beginRegistration(caller, label) {\n const ready = support();\n if (!ready.supported) return undefined;\n const account = options.accountForCaller?.(caller);\n const member = account && { ...account };\n const options_ = await generateRegistrationOptions({\n rpName: RP_NAME,\n rpID: ready.rpId,\n userID: member\n ? createHash('sha256')\n .update(JSON.stringify([member.issuer, member.subject, member.org]))\n .digest()\n : userId,\n userName: OWNER_NAME,\n userDisplayName: label,\n attestationType: 'none',\n // Discoverable so a return visit is one gesture with nothing typed,\n // and platform so the key lands in the phone's secure enclave rather\n // than on a roaming key the user has to carry.\n authenticatorSelection: {\n residentKey: 'required',\n userVerification: 'required',\n authenticatorAttachment: 'platform',\n },\n excludeCredentials: options.credentials().map((credential) => ({ id: credential.credentialId })),\n });\n const ceremonyId = remember('registration', caller, options_.challenge);\n if (member) pending.get(ceremonyKey(ceremonyId, caller, 'registration'))!.account = member;\n return { ceremonyId, options: options_ as unknown as Record<string, unknown> };\n },\n\n async finishRegistration(ceremonyId, caller, response, label) {\n const ready = support();\n if (!ready.supported) return { ok: false, error: ready.reason };\n const account = pending.get(ceremonyKey(ceremonyId, caller, 'registration'))?.account;\n const challenge = take(ceremonyId, caller, 'registration');\n if (challenge === undefined) return { ok: false, error: 'That registration expired. Try again.' };\n try {\n const verification = await verifyRegistrationResponse({\n response: response as Parameters<typeof verifyRegistrationResponse>[0]['response'],\n expectedChallenge: challenge,\n expectedOrigin: `https://${ready.rpId}`,\n expectedRPID: ready.rpId,\n requireUserVerification: true,\n });\n if (!verification.verified || verification.registrationInfo === undefined) {\n return { ok: false, error: 'That passkey could not be verified.' };\n }\n const info = verification.registrationInfo;\n const at = now();\n const credential: StoredCredential = {\n id: randomBytes(ID_BYTES).toString('hex'),\n credentialId: info.credential.id,\n publicKey: Buffer.from(info.credential.publicKey).toString('base64url'),\n counter: info.credential.counter,\n transports: info.credential.transports ?? [],\n label,\n createdAt: at,\n lastUsedAt: at,\n ...(account ? { account: { ...account } } : {}),\n };\n options.saveCredential(credential);\n notice(`registered a passkey for ${label}`);\n return { ok: true, id: credential.id };\n } catch (error) {\n return { ok: false, error: describe(error) };\n }\n },\n\n async beginAuthentication(caller) {\n const ready = support();\n if (!ready.supported) return undefined;\n const options_ = await generateAuthenticationOptions({\n rpID: ready.rpId,\n userVerification: 'required',\n });\n const ceremonyId = remember('authentication', caller, options_.challenge);\n return { ceremonyId, options: options_ as unknown as Record<string, unknown> };\n },\n\n async finishAuthentication(ceremonyId, caller, response) {\n const ready = support();\n if (!ready.supported) return { ok: false, error: ready.reason };\n const challenge = take(ceremonyId, caller, 'authentication');\n if (challenge === undefined) return { ok: false, error: 'That sign-in expired. Try again.' };\n return await verifyAgainst(challenge, ready.rpId, response);\n },\n\n async beginStepUp(caller, action) {\n const ready = support();\n if (!ready.supported) return undefined;\n const options_ = await generateAuthenticationOptions({\n rpID: ready.rpId,\n userVerification: 'required',\n });\n const ceremonyId = remember('step-up', caller, options_.challenge, action);\n return { ceremonyId, options: options_ as unknown as Record<string, unknown> };\n },\n\n async finishStepUp(ceremonyId, caller, action, response) {\n const ready = support();\n if (!ready.supported) return false;\n const challenge = take(ceremonyId, caller, 'step-up', action);\n if (challenge === undefined) return false;\n return (await verifyAgainst(challenge, ready.rpId, response)).ok;\n },\n\n clearChallenges() {\n pending.clear();\n },\n };\n\n async function verifyAgainst(\n challenge: string,\n rpId: string,\n response: unknown,\n ): Promise<{ ok: true; credential: StoredCredential } | { ok: false; error: string }> {\n const presented = (response as { id?: unknown }).id;\n if (typeof presented !== 'string') return { ok: false, error: 'That response named no credential.' };\n const stored = options.credentials().find((candidate) => candidate.credentialId === presented);\n if (stored === undefined) return { ok: false, error: 'That passkey is not registered here.' };\n try {\n const verification = await verifyAuthenticationResponse({\n response: response as Parameters<typeof verifyAuthenticationResponse>[0]['response'],\n expectedChallenge: challenge,\n expectedOrigin: `https://${rpId}`,\n expectedRPID: rpId,\n requireUserVerification: true,\n credential: {\n id: stored.credentialId,\n publicKey: new Uint8Array(Buffer.from(stored.publicKey, 'base64url')),\n counter: stored.counter,\n transports: stored.transports as never,\n },\n });\n if (!verification.verified) return { ok: false, error: 'That passkey did not verify.' };\n // Verification awaited. Reject a revoked or replaced snapshot before the synchronous commit.\n if (!options.credentials().includes(stored)) {\n return { ok: false, error: 'That passkey changed during verification. Try again.' };\n }\n const presentedCounter = verification.authenticationInfo.newCounter;\n if (counterVerdict(stored.counter, presentedCounter) === 'clone-suspected') {\n // Two things are signing with one key. The credential is burnt.\n if (!options.removeCredential(stored.id)) {\n return { ok: false, error: 'That passkey looks cloned but could not be revoked. Try removing it again.' };\n }\n notice(`revoked passkey ${stored.label}: its signature counter went backwards, which means a clone`);\n return { ok: false, error: 'That passkey looks cloned and has been revoked.' };\n }\n const updated: StoredCredential = { ...stored, counter: presentedCounter, lastUsedAt: now() };\n options.saveCredential(updated);\n return { ok: true, credential: updated };\n } catch (error) {\n return { ok: false, error: describe(error) };\n }\n }\n}\n","import { createHash, randomBytes, randomInt } from 'node:crypto';\n\nimport type { AuthPairingIdentity } from '@agimon-ai/po-core';\nimport {\n BUNDLE_MINIMUM_REVISION_PARAM,\n BUNDLE_SIGNING_KEY_PARAM,\n PAIRING_PAGE_ROUTE,\n REMOTE_PAIRING_REQUEST_TYPE,\n REMOTE_STATE_TYPE,\n} from '@agimon-ai/po-core/remoteContract';\nimport { COOKIE_CEILING_SECONDS } from '@agimon-ai/po-core/remoteContract';\nimport {\n type BundlePairingTrust,\n type NativePushRegistration,\n type PairingStatus,\n type RemoteAccessSettings,\n type RemoteAccessStateView,\n type RemoteAccessStatus,\n type RemoteChannelScope,\n type TunnelLauncher,\n type TunnelStartResult,\n} from '@agimon-ai/po-core/remoteContract';\nimport { SEALED_KEY_PARAM } from '@agimon-ai/po-web-security';\nimport { createHostHandshake, type HostHandshake, type SealedChannel } from '@agimon-ai/po-web-security/node';\n\nimport { TRUSTED_DEVICE_LIMIT } from '../../constants/remote';\nimport { type DeviceTrust, type DeviceTrustKind } from '../../types/remote';\nimport { createDeviceAuth, type DeviceAuth, type EnrolledDevice } from '../deviceAuth';\nimport { cookieMaxAgeSeconds } from '../deviceSessions';\nimport {\n createDeviceChallenges,\n deviceAuthChallenge,\n deviceStepUpChallenge,\n type DeviceChallenges,\n isDeviceNonce,\n isOpaqueId,\n verifyAuthentication,\n verifyRegistration,\n verifyStepUp,\n} from '../deviceTrust';\nimport { parseNativePushRegistration, sameNativePushRegistration } from '../nativePushRegistration';\nimport { createPairingFlow, type PairingFlow } from '../pairingFlow';\nimport { parseRemoteAccessSettings, serializeRemoteAccessSettings } from '../remoteAccessSettings';\nimport type { RemoteAccessStore } from '../remoteAccessStore';\nimport { nativePushEnrollmentRemoved } from '../remoteAccessStore/remoteAccessRecords';\nimport { type OriginPolicy, tunnelOriginPolicy } from '../remoteGuardPolicy';\nimport { createWebAuthn, type PasskeySupport, type WebAuthn } from '../webauthn';\nimport type { StepUpAction, StoredCredential } from '../webauthnPolicy';\n\nconst TOKEN_BYTES = 32;\nconst TRUSTED_DEVICE_ID_BYTES = 16;\nconst PAIRING_TRUST: DeviceTrust = { kind: 'pairing' };\nconst PASSKEY_TRUST: DeviceTrust = { kind: 'passkey' };\nconst SWEEP_INTERVAL_MS = 5 * 60_000;\nconst MS_PER_MINUTE = 60_000;\n\n/** The tunnel listener, bound by the host so this file never imports an HTTP server. */\nexport interface TunnelListener {\n port: number;\n close: () => Promise<void>;\n}\n\nexport interface RemoteAccessOptions {\n store: RemoteAccessStore;\n launchTunnel: TunnelLauncher;\n /** Binds a fresh loopback listener for the tunnel to point at. */\n bindListener: () => Promise<TunnelListener>;\n /** Current signed publication authenticated through the physical pairing display. */\n bundleTrust?: () => { publicKey: string; revision: number } | undefined;\n /**\n * Signs `po/host-channel-key/v1` fields with the same bundle signer the QR pins, so a reconnecting\n * phone can trust a fresh tunnel key. Undefined while no shell is published.\n */\n attestHost?: (fields: readonly string[]) => string | undefined;\n /** Removes ephemeral state owned by a paired device when its authorization ends. */\n onDeviceDropped?: (deviceId: string) => void;\n onNotice?: (message: string) => void;\n /** Frames only the local cockpit may see, such as an approval prompt. */\n broadcastLocal?: (frame: object) => void;\n /** Frames both local and remote pages see. */\n broadcastAll?: (frame: object) => void;\n now?: () => number;\n}\n\nexport interface RemoteAccess {\n state(selfDeviceId?: string, forLocalCaller?: boolean): RemoteAccessStateView;\n settings(): RemoteAccessSettings;\n updateSettings(patch: Partial<RemoteAccessSettings>): RemoteAccessSettings;\n tunnelPort(): number | undefined;\n /** The public origin the tunnel currently answers on, while one is up. */\n publicOrigin(): string | undefined;\n /** Changes whenever the public origin is established or torn down. */\n publicOriginRevision(): number;\n tunnelPolicy(): OriginPolicy | undefined;\n /** An absolute deadline, preserved even when settings later disable or lengthen auto-close. */\n enable(closesAt?: number): Promise<{ ok: true } | { ok: false; error: string }>;\n disable(): Promise<void>;\n /** Mints the QR credential, separate manual code, and URL. Undefined while unavailable. */\n mintPairing():\n | ({ code: string; manualCode: string; pairUrl: string; expiresAt: string } & BundlePairingTrust)\n | undefined;\n bundleTrust(): BundlePairingTrust | undefined;\n claim(input: {\n code: string;\n userAgent: string | undefined;\n edgeIp: string | undefined;\n sourceAddress: string | undefined;\n accountRequired?: boolean;\n }): ReturnType<PairingFlow['claim']>;\n pairingStatus(requestId: string): PairingStatus | undefined;\n /** Called only with the account resolved from the issuer's proof, never caller fields. */\n bindPairingAccount(requestId: string, account: AuthPairingIdentity): boolean;\n approve(requestId: string): ReturnType<PairingFlow['approve']>;\n deny(requestId: string): ReturnType<PairingFlow['deny']>;\n /** Turns an approved request into a session, exactly once. */\n redeem(requestId: string): (EnrolledDevice & { maxAgeSeconds: number }) | undefined;\n authorize(token: string | undefined): string | undefined;\n /** The account this live pairing names. Undefined never means a previously named member became the owner. */\n accountOf(deviceId: string): AuthPairingIdentity | undefined;\n /** Liveness check for a server-authenticated device identity, without extending expiry. */\n isDeviceAuthorized(deviceId: string): boolean;\n /** Mints a session for a device that proved a registered passkey. */\n sessionForPasskey(label: string, account?: AuthPairingIdentity): EnrolledDevice & { maxAgeSeconds: number };\n passkeys(): {\n support: () => PasskeySupport;\n list: () => readonly StoredCredential[];\n beginRegistration: WebAuthn['beginRegistration'];\n finishRegistration: WebAuthn['finishRegistration'];\n beginAuthentication: WebAuthn['beginAuthentication'];\n finishAuthentication: WebAuthn['finishAuthentication'];\n beginStepUp: WebAuthn['beginStepUp'];\n finishStepUp: WebAuthn['finishStepUp'];\n forget: (id: string) => boolean;\n };\n /** Registers a native device from a sealed, QR-approved pairing session, exactly once. */\n registerTrustedDevice(\n sessionDeviceId: string,\n body: unknown,\n ):\n | { ok: true; trustedDeviceId: string }\n | { ok: false; reason: 'forbidden' | 'invalid' | 'full' | 'unavailable' | 'persistence' };\n /** Server derives durable ownership from a live device-key session. Undefined body clears self. */\n setNativePushRegistration(\n sessionDeviceId: string,\n body: unknown,\n ): { ok: true; notificationId: string } | { ok: false; reason: 'forbidden' | 'invalid' | 'persistence' };\n listNativePushRegistrations(): Array<{ notificationId: string; registration: NativePushRegistration }>;\n /** Compare-and-clear protects a newly rotated token from a stale provider failure. */\n clearNativePushRegistration(notificationId: string, expectedRegistration: NativePushRegistration): boolean;\n /** Public reconnect challenge with the same shape for known and unknown ids. */\n beginDeviceAuth(input: {\n trustedDeviceId: unknown;\n nonce: unknown;\n }):\n | { ok: true; challengeId: string; challenge: string; hostPublicKey: string; attestation: string }\n | { ok: false; reason: 'invalid' | 'unavailable' };\n /** Verifies a device sign-in, opens all three channels at once, and mints a session. */\n finishDeviceAuth(body: unknown): (EnrolledDevice & { maxAgeSeconds: number }) | undefined;\n beginDeviceStepUp(\n sessionDeviceId: string,\n action: StepUpAction,\n ): { ceremonyId: string; challenge: string; kind: 'device-key' } | undefined;\n finishDeviceStepUp(sessionDeviceId: string, action: StepUpAction, ceremonyId: unknown, signature: unknown): boolean;\n /** Removes the stored device and ends every live session, channel, and socket it holds. */\n revokeTrustedDevice(id: string): boolean;\n trustKind(deviceId: string): DeviceTrustKind | undefined;\n /** The trusted device a session signed back in as with its device key. Undefined for a first pairing. */\n trustedDeviceOf(deviceId: string): string | undefined;\n /**\n * Whether this action needs a fresh gesture that has not been supplied. Always true for a device-key\n * session; otherwise only where passkeys are supported.\n */\n stepUpRequired(action: StepUpAction, deviceId?: string): boolean;\n /** The host's ephemeral public key for this tunnel, delivered after QR pairing or passkey sign-in. */\n channelPublicKey(): string | undefined;\n /** Completes one purpose-bound sealed channel against a fresh device key. */\n openChannel(deviceId: string, scope: RemoteChannelScope, clientPublicKey: string): boolean;\n channelFor(deviceId: string, scope: RemoteChannelScope): SealedChannel | undefined;\n revokeDevice(id: string): boolean;\n isDeviceConnected(deviceId: string): boolean;\n /** Registers a remote socket against its device so revocation closes it immediately. */\n trackSocket(deviceId: string, close: (code: number, reason: string) => void): () => void;\n close(): Promise<void>;\n}\n\nfunction bundlePairingTrust(\n value: { publicKey: string; revision: number } | undefined,\n): BundlePairingTrust | undefined {\n if (value === undefined) return undefined;\n return {\n ...value,\n fingerprint: createHash('sha256').update(Buffer.from(value.publicKey, 'base64url')).digest('hex'),\n };\n}\n\nexport function createRemoteAccess(options: RemoteAccessOptions): RemoteAccess {\n const notice = options.onNotice ?? ((): void => {});\n const now = options.now ?? ((): number => Date.now());\n const broadcastLocal = options.broadcastLocal ?? ((): void => {});\n const broadcastAll = options.broadcastAll ?? ((): void => {});\n\n let settings = options.store.settings();\n let status: RemoteAccessStatus = 'off';\n let startupGeneration = 0;\n let listener: TunnelListener | undefined;\n let stopTunnel: (() => Promise<void>) | undefined;\n let tunnelStartup: { controller: AbortController; outcome: Promise<TunnelStartResult> } | undefined;\n let publicOrigin: string | undefined;\n let publicOriginRevision = 0;\n let policy: OriginPolicy | undefined;\n let startedAt: number | undefined;\n let closesAt: number | undefined;\n let failure: string | undefined;\n let autoCloseTimer: ReturnType<typeof setTimeout> | undefined;\n /** One handshake per tunnel; its public half goes in every QR while the tunnel lives. */\n let handshake: HostHandshake | undefined;\n const channels = new Map<string, SealedChannel>();\n const deviceChallenges: DeviceChallenges = createDeviceChallenges({ now });\n const sockets = new Map<string, Set<(code: number, reason: string) => void>>();\n\n const channelKey = (deviceId: string, scope: RemoteChannelScope): string => `${deviceId}:${scope}`;\n const dropDeviceAccess = (deviceId: string, reason: 'revoked' | 'expired'): void => {\n options.onDeviceDropped?.(deviceId);\n for (const scope of ['session', 'protocol', 'http'] as const) channels.delete(channelKey(deviceId, scope));\n const held = sockets.get(deviceId);\n sockets.delete(deviceId);\n for (const close of held ?? []) {\n try {\n close(1008, `device ${reason}`);\n } catch {\n // The socket is already gone.\n }\n }\n };\n\n const devices: DeviceAuth = createDeviceAuth({\n settings: () => settings,\n now,\n onNotice: notice,\n onDrop: (record, reason) => dropDeviceAccess(record.id, reason),\n });\n\n const webauthn: WebAuthn = createWebAuthn({\n publicOrigin: () => publicOrigin,\n credentials: () => options.store.credentials(),\n saveCredential: (credential) => options.store.saveCredential(credential),\n removeCredential: (id) => options.store.removeCredential(id),\n accountForCaller: (caller) =>\n caller.startsWith('device:')\n ? devices.list().find((record) => record.id === caller.slice('device:'.length))?.account\n : undefined,\n now,\n onNotice: notice,\n });\n\n const pairing: PairingFlow = createPairingFlow({\n randomToken: () => randomBytes(TOKEN_BYTES).toString('base64url'),\n randomManualCode: () => randomInt(100_000_000).toString().padStart(8, '0'),\n digest: (token) => createHash('sha256').update(token).digest('hex'),\n now,\n onNotice: notice,\n });\n\n const sweeper = setInterval(() => {\n devices.sweep();\n pairing.sweep();\n }, SWEEP_INTERVAL_MS);\n sweeper.unref();\n\n function publish(): void {\n broadcastAll({ type: REMOTE_STATE_TYPE, state: view(undefined, false) });\n }\n\n function view(selfDeviceId: string | undefined, forLocalCaller: boolean): RemoteAccessStateView {\n const selfTrust = selfDeviceId === undefined ? undefined : devices.trustOf(selfDeviceId);\n const selfTrustedDeviceId = selfTrust?.kind === 'device-key' ? selfTrust.trustedDeviceId : undefined;\n return {\n status,\n ...(publicOrigin === undefined ? {} : { publicUrl: publicOrigin }),\n ...(startedAt === undefined ? {} : { startedAt: new Date(startedAt).toISOString() }),\n ...(closesAt === undefined ? {} : { closesAt: new Date(closesAt).toISOString() }),\n ...(failure === undefined ? {} : { error: failure }),\n devices: devices.list().map((record) => ({\n id: record.id,\n label: record.label,\n userAgent: record.userAgent,\n createdAt: new Date(record.createdAt).toISOString(),\n lastSeenAt: new Date(record.lastSeenAt).toISOString(),\n self: record.id === selfDeviceId,\n })),\n // A paired phone must never see the approval queue: a device that can\n // approve devices makes its own access permanent, which is exactly what\n // host confirmation exists to prevent.\n pending: forLocalCaller\n ? pairing.pending().map((request) => ({\n id: request.id,\n userAgent: request.userAgent,\n edgeIp: request.edgeIp,\n createdAt: new Date(request.createdAt).toISOString(),\n expiresAt: new Date(request.createdAt + 180_000).toISOString(),\n }))\n : [],\n trustedDevices: options.store.trustedDevices().map((record) => ({\n id: record.id,\n label: record.label,\n platform: record.platform,\n createdAt: new Date(record.createdAt).toISOString(),\n lastSeenAt: new Date(record.lastSeenAt).toISOString(),\n self: selfTrustedDeviceId !== undefined && record.id === selfTrustedDeviceId,\n })),\n settings,\n };\n }\n\n function armAutoClose(): void {\n clearTimeout(autoCloseTimer);\n autoCloseTimer = undefined;\n if (status !== 'on' && status !== 'starting') return;\n if (settings.autoCloseEnabled) {\n const at = now() + settings.autoCloseMinutes * MS_PER_MINUTE;\n closesAt = closesAt === undefined ? at : Math.min(closesAt, at);\n }\n if (closesAt === undefined) return;\n autoCloseTimer = setTimeout(\n () => {\n notice('remote access reached its time limit; closing');\n void disable();\n },\n Math.max(0, closesAt - now()),\n );\n autoCloseTimer.unref();\n }\n\n /** Everything teardown has to do, in the order it has to happen. */\n async function teardown(): Promise<void> {\n startupGeneration += 1;\n clearTimeout(autoCloseTimer);\n autoCloseTimer = undefined;\n closesAt = undefined;\n // Sockets first. An upgraded socket has left the HTTP server's connection\n // tracking, so closing the listener does not touch it: without this a\n // paired phone keeps driving the agent after remote access is switched off.\n for (const held of sockets.values()) {\n for (const close of held) {\n try {\n close(1008, 'remote access revoked');\n } catch {\n // The socket is already gone, which is the outcome we wanted.\n }\n }\n }\n sockets.clear();\n const starting = tunnelStartup;\n tunnelStartup = undefined;\n starting?.controller.abort();\n // A launcher may settle long after abort. Revoke its listener immediately,\n // rather than leaving public routes exposed while waiting for that outcome.\n const closingListener = listener?.close().catch(() => undefined);\n listener = undefined;\n const startingOutcome = await starting?.outcome.catch(() => undefined);\n if (startingOutcome?.ok === true) await startingOutcome.stop().catch(() => undefined);\n await stopTunnel?.().catch(() => undefined);\n stopTunnel = undefined;\n await closingListener;\n if (publicOrigin !== undefined) publicOriginRevision += 1;\n publicOrigin = undefined;\n policy = undefined;\n startedAt = undefined;\n pairing.clear();\n webauthn.clearChallenges();\n // Challenges are bound to this tunnel's key. Trusted devices stay on disk, like passkeys.\n deviceChallenges.clear();\n handshake = undefined;\n channels.clear();\n // Sessions go; passkeys and any other durable credential do not, so\n // switching back on does not mean enrolling every device again.\n devices.revokeAll();\n }\n\n async function disable(): Promise<void> {\n if (status === 'off') return;\n await teardown();\n status = 'off';\n failure = undefined;\n notice('remote access off');\n publish();\n }\n\n return {\n state: (selfDeviceId, forLocalCaller = false) => view(selfDeviceId, forLocalCaller),\n settings: () => settings,\n publicOrigin: () => publicOrigin,\n publicOriginRevision: () => publicOriginRevision,\n\n updateSettings(patch) {\n // Through the parser rather than spread straight in, so a value out of\n // range is clamped now instead of silently differing until the next load.\n const parsed = parseRemoteAccessSettings(\n serializeRemoteAccessSettings({ ...settings, ...patch }) as Record<string, unknown>,\n );\n for (const warning of parsed.warnings) notice(`remote access settings: ${warning}`);\n settings = parsed.settings;\n options.store.save(settings);\n // Settings may shorten an existing deadline, but never remove or extend it.\n devices.reschedule();\n armAutoClose();\n publish();\n return settings;\n },\n\n tunnelPort: () => listener?.port,\n tunnelPolicy: () => policy,\n\n async enable(deadline) {\n if (status === 'on' || status === 'starting') return { ok: true };\n if (\n deadline !== undefined &&\n (!Number.isFinite(deadline) || !Number.isFinite(new Date(deadline).getTime()) || deadline <= now())\n )\n return { ok: false, error: 'The tunnel deadline is invalid or expired.' };\n const generation = ++startupGeneration;\n const tunnelConfig = settings.tunnel;\n closesAt = deadline;\n status = 'starting';\n failure = undefined;\n armAutoClose();\n publish();\n\n let bound: TunnelListener;\n try {\n bound = await options.bindListener();\n } catch (error) {\n if (generation !== startupGeneration) return { ok: false, error: 'Tunnel startup was cancelled.' };\n clearTimeout(autoCloseTimer);\n autoCloseTimer = undefined;\n closesAt = undefined;\n status = 'failed';\n failure = `The tunnel listener could not bind: ${error instanceof Error ? error.message : String(error)}`;\n publish();\n return { ok: false, error: failure };\n }\n if (generation !== startupGeneration) {\n await bound.close();\n return { ok: false, error: 'Tunnel startup was cancelled.' };\n }\n listener = bound;\n if (closesAt !== undefined && closesAt <= now()) {\n await disable();\n return { ok: false, error: 'The tunnel deadline expired during startup.' };\n }\n const controller = new AbortController();\n const launching = options.launchTunnel({\n port: bound.port,\n config: tunnelConfig,\n signal: controller.signal,\n acceptOrigin: (origin) => {\n if (generation === startupGeneration) policy = tunnelOriginPolicy(origin);\n },\n });\n const startup = { controller, outcome: launching };\n tunnelStartup = startup;\n const outcome = await launching;\n if (tunnelStartup !== startup || controller.signal.aborted) {\n return { ok: false, error: 'Tunnel startup was cancelled.' };\n }\n tunnelStartup = undefined;\n if (!outcome.ok) {\n await teardown();\n status = 'failed';\n failure = outcome.message;\n notice(`remote access failed: ${outcome.message}`);\n publish();\n return { ok: false, error: outcome.message };\n }\n stopTunnel = outcome.stop;\n if (closesAt !== undefined && closesAt <= now()) {\n await disable();\n return { ok: false, error: 'The tunnel deadline expired during startup.' };\n }\n // A fresh key pair per tunnel: the QR is the only place its public half\n // travels, so it must not outlive the code that carried it.\n handshake = createHostHandshake();\n if (publicOrigin !== outcome.publicOrigin) publicOriginRevision += 1;\n publicOrigin = outcome.publicOrigin;\n policy = tunnelOriginPolicy(outcome.publicOrigin);\n startedAt = now();\n status = 'on';\n armAutoClose();\n notice(`remote access on at ${outcome.publicOrigin}`);\n publish();\n return { ok: true };\n },\n\n disable,\n\n mintPairing() {\n if (status !== 'on' || publicOrigin === undefined || handshake === undefined) return undefined;\n const trust = bundlePairingTrust(options.bundleTrust?.());\n if (trust === undefined) return undefined;\n const { code, manualCode, expiresAt } = pairing.mintCode();\n // The token, channel key, signer key, and publication floor ride in the fragment,\n // so the relay never observes the values used to authenticate either channel.\n const fragment = new URLSearchParams({\n c: code,\n [SEALED_KEY_PARAM]: handshake.publicKey,\n [BUNDLE_SIGNING_KEY_PARAM]: trust.publicKey,\n [BUNDLE_MINIMUM_REVISION_PARAM]: String(trust.revision),\n });\n return {\n code,\n manualCode,\n pairUrl: `${publicOrigin}${PAIRING_PAGE_ROUTE}#${fragment.toString()}`,\n expiresAt: new Date(expiresAt).toISOString(),\n ...trust,\n };\n },\n\n bundleTrust: () => bundlePairingTrust(options.bundleTrust?.()),\n\n claim(input) {\n const outcome = pairing.claim(input);\n if (outcome.ok) {\n broadcastLocal({ type: REMOTE_PAIRING_REQUEST_TYPE, state: view(undefined, true) });\n }\n return outcome;\n },\n\n pairingStatus: (requestId) => pairing.status(requestId),\n\n bindPairingAccount(requestId, account) {\n const bound = pairing.bindAccount(requestId, account);\n if (bound) broadcastLocal({ type: REMOTE_PAIRING_REQUEST_TYPE, state: view(undefined, true) });\n return bound;\n },\n\n approve(requestId) {\n const outcome = pairing.approve(requestId);\n if (outcome === 'approved') broadcastLocal({ type: REMOTE_PAIRING_REQUEST_TYPE, state: view(undefined, true) });\n return outcome;\n },\n\n deny(requestId) {\n const outcome = pairing.deny(requestId);\n if (outcome === 'denied') broadcastLocal({ type: REMOTE_PAIRING_REQUEST_TYPE, state: view(undefined, true) });\n return outcome;\n },\n\n redeem(requestId) {\n const approved = pairing.consume(requestId);\n if (approved === undefined) return undefined;\n const enrolled = devices.enrol({\n userAgent: approved.userAgent,\n trust: PAIRING_TRUST,\n account: approved.account,\n });\n publish();\n return { ...enrolled, maxAgeSeconds: cookieMaxAgeSeconds(settings, COOKIE_CEILING_SECONDS) };\n },\n\n authorize: (token) => devices.verify(token)?.id,\n accountOf(deviceId) {\n devices.sweep();\n const account = devices.list().find((record) => record.id === deviceId)?.account;\n return account && { ...account };\n },\n isDeviceAuthorized(deviceId) {\n devices.sweep();\n return listener !== undefined && devices.list().some((record) => record.id === deviceId);\n },\n\n sessionForPasskey(label, account) {\n const enrolled = devices.enrol({ userAgent: label, trust: PASSKEY_TRUST, account });\n publish();\n return { ...enrolled, maxAgeSeconds: cookieMaxAgeSeconds(settings, COOKIE_CEILING_SECONDS) };\n },\n\n passkeys: () => ({\n support: () => webauthn.support(),\n list: () => options.store.credentials(),\n // Wrapped rather than passed by reference: an unbound method carries\n // whatever `this` the caller happens to have.\n beginRegistration: async (caller, label) => await webauthn.beginRegistration(caller, label),\n finishRegistration: async (ceremonyId, caller, response, label) =>\n await webauthn.finishRegistration(ceremonyId, caller, response, label),\n beginAuthentication: async (caller) => await webauthn.beginAuthentication(caller),\n finishAuthentication: async (ceremonyId, caller, response) =>\n await webauthn.finishAuthentication(ceremonyId, caller, response),\n beginStepUp: async (caller, action) => await webauthn.beginStepUp(caller, action),\n finishStepUp: async (ceremonyId, caller, action, response) =>\n await webauthn.finishStepUp(ceremonyId, caller, action, response),\n forget: (id) => {\n const forgotten = options.store.removeCredential(id);\n if (forgotten) publish();\n return forgotten;\n },\n }),\n\n registerTrustedDevice(sessionDeviceId, body) {\n if (publicOrigin === undefined || handshake === undefined) return { ok: false, reason: 'unavailable' };\n const verdict = verifyRegistration({\n origin: publicOrigin,\n hostPublicKey: handshake.publicKey,\n sessionDeviceId,\n trust: devices.trustOf(sessionDeviceId),\n body,\n });\n if (!verdict.ok) return { ok: false, reason: verdict.reason === 'not-pairing' ? 'forbidden' : 'invalid' };\n if (options.store.trustedDevices().length >= TRUSTED_DEVICE_LIMIT) return { ok: false, reason: 'full' };\n const at = now();\n const trustedDeviceId = randomBytes(TRUSTED_DEVICE_ID_BYTES).toString('base64url');\n const saved = options.store.saveTrustedDevice({\n id: trustedDeviceId,\n identityPublicKey: verdict.identityPublicKey,\n stepUpPublicKey: verdict.stepUpPublicKey,\n label: verdict.label,\n platform: verdict.platform,\n createdAt: at,\n lastSeenAt: at,\n });\n if (!saved) return { ok: false, reason: 'persistence' };\n // The pairing session becomes a device-key session, so it cannot register a second time and\n // every gated action from it now needs the biometric key.\n devices.setTrust(sessionDeviceId, { kind: 'device-key', trustedDeviceId });\n notice(`trusted ${verdict.label} (${trustedDeviceId})`);\n publish();\n return { ok: true, trustedDeviceId };\n },\n\n setNativePushRegistration(sessionDeviceId, body) {\n devices.sweep();\n const trust = devices.trustOf(sessionDeviceId);\n if (status !== 'on' || trust?.kind !== 'device-key') return { ok: false, reason: 'forbidden' };\n const record = options.store.trustedDevices().find((held) => held.id === trust.trustedDeviceId);\n if (record === undefined) return { ok: false, reason: 'forbidden' };\n const registration = body === undefined ? undefined : parseNativePushRegistration(body, record.platform);\n if (body !== undefined && registration === undefined) return { ok: false, reason: 'invalid' };\n const hub = options.store.hubTrust?.read();\n const binding = hub?.owner && { ...hub.owner, generation: hub.enrollmentGeneration ?? 1 };\n if (hub && nativePushEnrollmentRemoved({ ...record, nativePushEnrollment: binding }, hub))\n return { ok: false, reason: 'forbidden' };\n const { nativePush: _previous, nativePushEnrollment: _binding, ...base } = record;\n if (\n !options.store.saveTrustedDevice({\n ...base,\n ...(registration === undefined ? {} : { nativePush: registration, nativePushEnrollment: binding }),\n })\n )\n return { ok: false, reason: 'persistence' };\n return { ok: true, notificationId: record.id };\n },\n\n listNativePushRegistrations() {\n return options.store.trustedDevices().flatMap((record) => {\n const hub = options.store.hubTrust?.read();\n if (hub && nativePushEnrollmentRemoved(record, hub)) return [];\n const registration = parseNativePushRegistration(record.nativePush, record.platform);\n return registration === undefined ? [] : [{ notificationId: record.id, registration }];\n });\n },\n\n clearNativePushRegistration(notificationId, expectedRegistration) {\n const record = options.store.trustedDevices().find((held) => held.id === notificationId);\n if (record?.nativePush === undefined || !sameNativePushRegistration(record.nativePush, expectedRegistration))\n return false;\n const { nativePush: _previous, ...next } = record;\n return options.store.saveTrustedDevice(next);\n },\n\n beginDeviceAuth(input) {\n if (!isOpaqueId(input.trustedDeviceId) || !isDeviceNonce(input.nonce)) return { ok: false, reason: 'invalid' };\n if (status !== 'on' || publicOrigin === undefined || handshake === undefined || options.attestHost === undefined)\n return { ok: false, reason: 'unavailable' };\n const attest = options.attestHost;\n const begun = deviceAuthChallenge({\n challenges: deviceChallenges,\n trustedDeviceId: input.trustedDeviceId,\n nonce: input.nonce,\n origin: publicOrigin,\n hostPublicKey: handshake.publicKey,\n attest: (fields) => attest(fields),\n });\n return begun === undefined ? { ok: false, reason: 'unavailable' } : { ok: true, ...begun };\n },\n\n finishDeviceAuth(body) {\n if (status !== 'on' || publicOrigin === undefined || handshake === undefined) return undefined;\n const verdict = verifyAuthentication({\n challenges: deviceChallenges,\n origin: publicOrigin,\n hostPublicKey: handshake.publicKey,\n find: (id) => options.store.trustedDevices().find((record) => record.id === id),\n body,\n });\n if (!verdict.ok) return undefined;\n const enrolled = devices.enrol({\n userAgent: verdict.record.label,\n trust: { kind: 'device-key', trustedDeviceId: verdict.record.id },\n });\n // All three channels open together or the session goes: a relay holding the cookie must never\n // be able to add a channel of its own.\n const opened: [RemoteChannelScope, SealedChannel | undefined][] = [\n ['session', handshake.accept(verdict.channels.session)],\n ['protocol', handshake.accept(verdict.channels.protocol)],\n ['http', handshake.accept(verdict.channels.http)],\n ];\n if (opened.some(([, channel]) => channel === undefined)) {\n devices.revoke(enrolled.record.id);\n return undefined;\n }\n for (const [scope, channel] of opened) {\n if (channel !== undefined) channels.set(channelKey(enrolled.record.id, scope), channel);\n }\n if (!options.store.saveTrustedDevice({ ...verdict.record, lastSeenAt: now() })) {\n devices.revoke(enrolled.record.id);\n return undefined;\n }\n publish();\n return { ...enrolled, maxAgeSeconds: cookieMaxAgeSeconds(settings, COOKIE_CEILING_SECONDS) };\n },\n\n beginDeviceStepUp(sessionDeviceId, action) {\n if (handshake === undefined || devices.trustOf(sessionDeviceId)?.kind !== 'device-key') return undefined;\n return deviceStepUpChallenge({\n challenges: deviceChallenges,\n sessionDeviceId,\n action,\n hostPublicKey: handshake.publicKey,\n });\n },\n\n finishDeviceStepUp(sessionDeviceId, action, ceremonyId, signature) {\n const trust = devices.trustOf(sessionDeviceId);\n if (trust?.kind !== 'device-key' || publicOrigin === undefined) return false;\n const record = options.store.trustedDevices().find((held) => held.id === trust.trustedDeviceId);\n if (record === undefined) return false;\n return verifyStepUp({\n challenges: deviceChallenges,\n origin: publicOrigin,\n hostPublicKey: handshake?.publicKey,\n sessionDeviceId,\n action,\n ceremonyId,\n signature,\n stepUpPublicKey: record.stepUpPublicKey,\n });\n },\n\n revokeTrustedDevice(id) {\n const heldBy = (record: { trust: DeviceTrust }): boolean =>\n record.trust.kind === 'device-key' && record.trust.trustedDeviceId === id;\n const existed = options.store.trustedDevices().some((record) => record.id === id);\n const removed = options.store.removeTrustedDevice(id);\n if (existed && !removed) return false;\n const endedIds = new Set(\n devices\n .list()\n .filter(heldBy)\n .map((record) => record.id),\n );\n // The drop path deletes channels and closes sockets with 1008, exactly as a session revoke does.\n const ended = devices.revokeWhere(heldBy);\n deviceChallenges.dropWhere(\n (challenge) =>\n (challenge.purpose.kind === 'auth' && challenge.purpose.trustedDeviceId === id) ||\n (challenge.purpose.kind === 'step-up' && endedIds.has(challenge.purpose.sessionDeviceId)),\n );\n if (!removed && ended === 0) return false;\n notice(`revoked trusted device ${id}`);\n publish();\n return true;\n },\n\n trustKind: (deviceId) => devices.trustOf(deviceId)?.kind,\n trustedDeviceOf: (deviceId) => {\n const trust = devices.trustOf(deviceId);\n return trust?.kind === 'device-key' ? trust.trustedDeviceId : undefined;\n },\n\n // A device-key session always steps up with its biometric key, on every tunnel. Otherwise this is\n // only meaningful where passkeys are: a quick tunnel has no stable rpID, so there is nothing to\n // step up with and the session cookie is all there is.\n stepUpRequired: (_action, deviceId) =>\n (deviceId !== undefined && devices.trustOf(deviceId)?.kind === 'device-key') || webauthn.support().supported,\n\n channelPublicKey: () => handshake?.publicKey,\n\n openChannel(deviceId, scope, clientPublicKey) {\n const channel = handshake?.accept(clientPublicKey);\n if (channel === undefined) return false;\n channels.set(channelKey(deviceId, scope), channel);\n return true;\n },\n\n channelFor: (deviceId, scope) => channels.get(channelKey(deviceId, scope)),\n\n revokeDevice(id) {\n const revoked = devices.revoke(id);\n if (revoked) publish();\n return revoked;\n },\n\n isDeviceConnected: (deviceId) => (sockets.get(deviceId)?.size ?? 0) > 0,\n\n trackSocket(deviceId, close) {\n const held = sockets.get(deviceId) ?? new Set();\n held.add(close);\n sockets.set(deviceId, held);\n return () => {\n held.delete(close);\n if (held.size === 0) sockets.delete(deviceId);\n };\n },\n\n async close() {\n clearInterval(sweeper);\n await teardown();\n status = 'off';\n },\n };\n}\n","// sync: documented Node-only remote access store API; phase 2 must migrate consumers to createRemoteAccessStoreAsync.\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { RemoteAccessSettings } from '@agimon-ai/po-core/remoteContract';\n\nimport { TRUSTED_DEVICE_LIMIT } from '../../constants/remote';\nimport {\n DEFAULT_REMOTE_SETTINGS,\n parseRemoteAccessSettings,\n serializeRemoteAccessSettings,\n} from '../remoteAccessSettings';\nimport {\n HUB_TRUST_FILE,\n nativePushEnrollmentRemoved,\n parseHubTrust,\n CREDENTIALS_FILE,\n defaultRemoteStateDir,\n DIRECTORY_MODE,\n FILE_MODE,\n isLooseMode,\n parseCredentialsFile,\n parseSettingsFile,\n parseTrustedDevicesFile,\n serializeStateFile,\n SETTINGS_FILE,\n TRUSTED_DEVICES_FILE,\n type RemoteAccessStore,\n type RemoteAccessStoreOptions,\n} from './remoteAccessRecords';\n\n/**\n * Repairs a state file another account can read.\n *\n * Cheap, and it catches the cases a fresh write never would: a file restored\n * from a backup, copied with a permissive umask, or checked out of somewhere it\n * should not have been.\n */\nfunction tightenMode(filePath: string, notice: (message: string) => void): void {\n try {\n if (!isLooseMode(fs.statSync(filePath).mode)) return;\n fs.chmodSync(filePath, FILE_MODE);\n notice(`tightened permissions on ${filePath}`);\n } catch {\n // The file is missing or unreadable; the caller's own read reports that.\n }\n}\n\nfunction readState(filePath: string, notice: (message: string) => void): string | undefined {\n let raw: string;\n try {\n raw = fs.readFileSync(filePath, 'utf8');\n } catch {\n // No file is the normal first run, so this is not worth a notice.\n return undefined;\n }\n tightenMode(filePath, notice);\n return raw;\n}\n\n/**\n * Settings and passkeys on disk. Sessions deliberately not.\n *\n * A session is revoked when remote access is switched off, and a hub restart is\n * a switch-off, so persisting one would buy nothing while creating a bearer\n * secret worth stealing. A passkey is the opposite: surviving is its whole\n * point, and what is stored is a public key.\n *\n * @deprecated Node-only sync shim; use createRemoteAccessStoreAsync. Removed in M2.\n */\nexport function createRemoteAccessStore(options: RemoteAccessStoreOptions = {}): RemoteAccessStore {\n const directory = options.stateDir ?? defaultRemoteStateDir();\n const notice = options.onNotice ?? ((): void => {});\n const settingsPath = path.join(directory, SETTINGS_FILE);\n const credentialsPath = path.join(directory, CREDENTIALS_FILE);\n const trustedDevicesPath = path.join(directory, TRUSTED_DEVICES_FILE);\n const hubTrustPath = path.join(directory, HUB_TRUST_FILE);\n\n const settingsRaw = readState(settingsPath, notice);\n let current: RemoteAccessSettings =\n settingsRaw === undefined ? DEFAULT_REMOTE_SETTINGS : parseSettingsFile(settingsRaw, settingsPath, notice);\n const credentialsRaw = readState(credentialsPath, notice);\n let registered = credentialsRaw === undefined ? [] : parseCredentialsFile(credentialsRaw, credentialsPath, notice);\n const devicesRaw = readState(trustedDevicesPath, notice);\n let trusted = devicesRaw === undefined ? [] : parseTrustedDevicesFile(devicesRaw, trustedDevicesPath, notice);\n\n let hubTrust = parseHubTrust(readState(hubTrustPath, notice));\n\n function writeJson(target: string, body: unknown): boolean {\n const temporary = `${target}.${String(process.pid)}.tmp`;\n try {\n fs.mkdirSync(directory, { recursive: true, mode: DIRECTORY_MODE });\n fs.writeFileSync(temporary, serializeStateFile(body), { mode: FILE_MODE });\n // Rename rather than write in place, so a crash mid-write leaves the\n // previous contents rather than a truncated file.\n fs.renameSync(temporary, target);\n return true;\n } catch (error) {\n notice(`${target} could not be saved: ${error instanceof Error ? error.message : String(error)}`);\n try {\n fs.rmSync(temporary, { force: true });\n } catch {\n // Nothing further to do; the temp file is inert either way.\n }\n return false;\n }\n }\n\n return {\n directory,\n hubTrust: {\n read: () => structuredClone(hubTrust),\n save(state) {\n if (!writeJson(hubTrustPath, state)) return false;\n hubTrust = structuredClone(state);\n const next = trusted.map((record) => {\n if (!record.nativePush || !nativePushEnrollmentRemoved(record, state)) return record;\n const { nativePush: _push, nativePushEnrollment: _binding, ...held } = record;\n return held;\n });\n if (next.every((record, index) => record === trusted[index])) return true;\n if (!writeJson(trustedDevicesPath, next)) return false;\n trusted = next;\n return true;\n },\n },\n settings: () => current,\n settingsForRestore() {\n const raw = readState(settingsPath, notice);\n if (raw === undefined) return undefined;\n try {\n return parseRemoteAccessSettings(JSON.parse(raw) as unknown);\n } catch {\n // Invalid JSON cannot authorize automatic exposure, even if the cached settings were valid.\n return undefined;\n }\n },\n credentials: () => registered,\n\n saveCredential(credential) {\n const next = [...registered.filter((held) => held.id !== credential.id), credential];\n if (!writeJson(credentialsPath, next)) throw new Error('Passkey could not be saved.');\n registered = next;\n },\n\n removeCredential(id) {\n const next = registered.filter((held) => held.id !== id);\n if (next.length === registered.length) return false;\n if (!writeJson(credentialsPath, next)) return false;\n registered = next;\n return true;\n },\n\n trustedDevices: () => trusted,\n\n saveTrustedDevice(record) {\n const others = trusted.filter((held) => held.id !== record.id);\n if (others.length === trusted.length && trusted.length >= TRUSTED_DEVICE_LIMIT) return false;\n const next = [...others, record];\n if (!writeJson(trustedDevicesPath, next)) return false;\n trusted = next;\n return true;\n },\n\n removeTrustedDevice(id) {\n const next = trusted.filter((held) => held.id !== id);\n if (next.length === trusted.length) return false;\n if (!writeJson(trustedDevicesPath, next)) return false;\n trusted = next;\n return true;\n },\n\n save(settings) {\n current = settings;\n writeJson(settingsPath, serializeRemoteAccessSettings(settings));\n },\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport path from 'node:path';\n\nimport { createSerialRunner, getOrThrow, nodeHost, writeFileAtomic } from '@agimon-ai/po-core/platform';\nimport type { RemoteAccessSettings } from '@agimon-ai/po-core/remoteContract';\nimport type { HubTrustState } from '@agimon-ai/po-federation';\nimport type { Context } from '@earendil-works/chord/context';\nimport type { FileSystem } from '@earendil-works/pi-durable/env';\n\nimport { TRUSTED_DEVICE_LIMIT } from '../../constants/remote';\nimport type { TrustedDeviceRecord } from '../../types/remote';\nimport { DEFAULT_REMOTE_SETTINGS, serializeRemoteAccessSettings } from '../remoteAccessSettings';\nimport type { StoredCredential } from '../webauthnPolicy';\nimport {\n HUB_TRUST_FILE,\n nativePushEnrollmentRemoved,\n parseHubTrust,\n CREDENTIALS_FILE,\n defaultRemoteStateDir,\n DIRECTORY_MODE,\n FILE_MODE,\n isLooseMode,\n parseCredentialsFile,\n parseSettingsFile,\n parseTrustedDevicesFile,\n serializeStateFile,\n SETTINGS_FILE,\n TRUSTED_DEVICES_FILE,\n type RemoteAccessStoreOptions,\n} from './remoteAccessRecords';\n\nexport type { RemoteAccessStore, RemoteAccessStoreOptions } from './remoteAccessRecords';\nexport { createHubDeviceTrust, createHubQrEnrollment } from '../hubDeviceTrust';\nexport type { HubDeviceTrustPorts } from '../hubDeviceTrust';\nexport { defaultRemoteStateDir } from './remoteAccessRecords';\nexport { createRemoteAccessStore } from './sync';\n\n/** One queue per state file, so concurrent writes in this process never interleave. */\nconst stateWrites = createSerialRunner();\n\n/** The async twin of `RemoteAccessStore`: reads stay in memory, every write resolves once it is on disk. */\nexport interface RemoteAccessStoreAsync {\n readonly directory: string;\n settings(): RemoteAccessSettings;\n save(settings: RemoteAccessSettings): Promise<void>;\n /** Registered passkeys. Public keys only. */\n credentials(): readonly StoredCredential[];\n /** Rejects on persistence failure. Failed writes leave the record unchanged. */\n saveCredential(credential: StoredCredential): Promise<void>;\n /** False if absent or persistence failed. Failed writes leave the record unchanged. */\n removeCredential(id: string): Promise<boolean>;\n /** Registered native devices and private push routing metadata, at most `TRUSTED_DEVICE_LIMIT`. */\n trustedDevices(): readonly TrustedDeviceRecord[];\n hubTrust: { read(): HubTrustState; save(state: HubTrustState): Promise<boolean> };\n /** Adds or replaces one record by id. False on persistence failure or when a new record would exceed the limit. */\n saveTrustedDevice(record: TrustedDeviceRecord): Promise<boolean>;\n /** False if absent or persistence failed. Failed writes leave the record unchanged. */\n removeTrustedDevice(id: string): Promise<boolean>;\n}\n\n/**\n * Settings and passkeys on disk. Sessions deliberately not.\n *\n * A session is revoked when remote access is switched off, and a hub restart is\n * a switch-off, so persisting one would buy nothing while creating a bearer\n * secret worth stealing. A passkey is the opposite: surviving is its whole\n * point, and what is stored is a public key. Credential saves reject on failure;\n * other failed writes are reported without throwing, as in the sync store.\n */\nexport async function createRemoteAccessStoreAsync(\n fs: FileSystem,\n options: RemoteAccessStoreOptions,\n context: Context,\n): Promise<RemoteAccessStoreAsync> {\n const directory = options.stateDir ?? defaultRemoteStateDir();\n const notice = options.onNotice ?? ((): void => {});\n const settingsPath = path.join(directory, SETTINGS_FILE);\n const credentialsPath = path.join(directory, CREDENTIALS_FILE);\n const trustedDevicesPath = path.join(directory, TRUSTED_DEVICES_FILE);\n const hubTrustPath = path.join(directory, HUB_TRUST_FILE);\n\n const readState = async (filePath: string): Promise<string | undefined> => {\n const raw = await fs.readTextFile(filePath, context);\n // No file is the normal first run, so this is not worth a notice.\n if (!raw.ok) return undefined;\n // Repairs a state file another account can read: a file restored from a backup,\n // copied with a permissive umask, or checked out of somewhere it should not have been.\n try {\n const mode = await nodeHost.fileMode(filePath);\n if (mode !== undefined && isLooseMode(mode)) {\n await nodeHost.setMode(filePath, FILE_MODE);\n notice(`tightened permissions on ${filePath}`);\n }\n } catch {\n // The file vanished or is unreadable between the read and the check; the read above already won.\n }\n return raw.value;\n };\n\n const settingsRaw = await readState(settingsPath);\n let current: RemoteAccessSettings =\n settingsRaw === undefined ? DEFAULT_REMOTE_SETTINGS : parseSettingsFile(settingsRaw, settingsPath, notice);\n const credentialsRaw = await readState(credentialsPath);\n let registered = credentialsRaw === undefined ? [] : parseCredentialsFile(credentialsRaw, credentialsPath, notice);\n const devicesRaw = await readState(trustedDevicesPath);\n let trusted = devicesRaw === undefined ? [] : parseTrustedDevicesFile(devicesRaw, trustedDevicesPath, notice);\n\n let hubTrust = parseHubTrust(await readState(hubTrustPath));\n\n const writeJson = async (target: string, body: unknown): Promise<boolean> => {\n const temporary = `${target}.${randomUUID()}.tmp`;\n try {\n if (!getOrThrow(await fs.exists(directory, context))) {\n getOrThrow(await fs.createDir(directory, { recursive: true }, context));\n await nodeHost.setMode(directory, DIRECTORY_MODE);\n }\n if (target === credentialsPath || target === trustedDevicesPath || target === hubTrustPath) {\n // Set private permissions before the commit point. A failed write must leave both\n // the old disk contents and in-memory trust unchanged.\n getOrThrow(await fs.writeFile(temporary, serializeStateFile(body), context));\n await nodeHost.setMode(temporary, FILE_MODE);\n getOrThrow(await fs.renameFile(temporary, target, context));\n } else {\n await writeFileAtomic(fs, target, serializeStateFile(body), context);\n await nodeHost.setMode(target, FILE_MODE);\n }\n return true;\n } catch (error) {\n notice(`${target} could not be saved: ${error instanceof Error ? error.message : String(error)}`);\n await fs.remove(temporary, { force: true }, context);\n return false;\n }\n };\n\n return {\n directory,\n hubTrust: {\n read: () => structuredClone(hubTrust),\n save: (state) =>\n stateWrites.forKey(hubTrustPath)(async () => {\n if (!(await writeJson(hubTrustPath, state))) return false;\n hubTrust = structuredClone(state);\n return stateWrites.forKey(trustedDevicesPath)(async () => {\n const next = trusted.map((record) => {\n if (!record.nativePush || !nativePushEnrollmentRemoved(record, state)) return record;\n const { nativePush: _push, nativePushEnrollment: _binding, ...held } = record;\n return held;\n });\n if (next.every((record, index) => record === trusted[index])) return true;\n if (!(await writeJson(trustedDevicesPath, next))) return false;\n trusted = next;\n return true;\n });\n }),\n },\n settings: () => current,\n credentials: () => registered,\n\n saveCredential: (credential) =>\n stateWrites.forKey(credentialsPath)(async () => {\n const next = [...registered.filter((held) => held.id !== credential.id), credential];\n if (!(await writeJson(credentialsPath, next))) throw new Error('Passkey could not be saved.');\n registered = next;\n }),\n\n removeCredential: (id) =>\n stateWrites.forKey(credentialsPath)(async () => {\n const next = registered.filter((held) => held.id !== id);\n if (next.length === registered.length) return false;\n if (!(await writeJson(credentialsPath, next))) return false;\n registered = next;\n return true;\n }),\n\n trustedDevices: () => trusted,\n\n saveTrustedDevice: (record) =>\n stateWrites.forKey(trustedDevicesPath)(async () => {\n const others = trusted.filter((held) => held.id !== record.id);\n if (others.length === trusted.length && trusted.length >= TRUSTED_DEVICE_LIMIT) return false;\n const next = [...others, record];\n if (!(await writeJson(trustedDevicesPath, next))) return false;\n trusted = next;\n return true;\n }),\n\n removeTrustedDevice: (id) =>\n stateWrites.forKey(trustedDevicesPath)(async () => {\n const next = trusted.filter((held) => held.id !== id);\n if (next.length === trusted.length) return false;\n if (!(await writeJson(trustedDevicesPath, next))) return false;\n trusted = next;\n return true;\n }),\n\n save: (settings) =>\n stateWrites.forKey(settingsPath)(async () => {\n current = settings;\n await writeJson(settingsPath, serializeRemoteAccessSettings(settings));\n }),\n };\n}\n","import { randomBytes } from 'node:crypto';\n\nimport type { AuthPairingIdentity, AuthPairingRequest } from '@agimon-ai/po-core';\nimport { pairingPageHeaders, pairingPageHtml } from '@agimon-ai/po-core/pairingPage';\nimport {\n DEVICE_AUTH_AUTHENTICATE_ROUTE,\n DEVICE_AUTH_CHALLENGE_ROUTE,\n DEVICE_COOKIE,\n NATIVE_PUSH_ROUTE,\n PAIRING_ACCOUNT_ROUTE,\n PAIRING_CLAIM_ROUTE,\n PAIRING_PAGE_ROUTE,\n PAIRING_STATUS_QUERY,\n PAIRING_STATUS_ROUTE,\n PASSKEY_AUTH_BEGIN_ROUTE,\n PASSKEY_AUTH_FINISH_ROUTE,\n PASSKEY_REGISTER_BEGIN_ROUTE,\n PASSKEY_REGISTER_FINISH_ROUTE,\n REMOTE_API_ROUTE,\n REMOTE_CHANNEL_ROUTE,\n TRUSTED_DEVICES_ROUTE,\n} from '@agimon-ai/po-core/remoteContract';\nimport { type RemoteChannelScope } from '@agimon-ai/po-core/remoteContract';\nimport type { Context, Hono, MiddlewareHandler } from 'hono';\nimport { bodyLimit } from 'hono/body-limit';\nimport { getCookie, setCookie } from 'hono/cookie';\nimport { HTTPException } from 'hono/http-exception';\nimport { timeout } from 'hono/timeout';\n\nimport {\n DEVICE_AUTH_AUTHENTICATE_BODY_BYTES,\n DEVICE_AUTH_CHALLENGE_BODY_BYTES,\n NATIVE_PUSH_BODY_BYTES,\n TRUSTED_DEVICE_REGISTER_BODY_BYTES,\n} from '../../constants/remote';\nimport { sanitizeEdgeIp, sanitizeUserAgent } from '../deviceSessions';\nimport type { RemoteAccess } from '../remoteAccess';\nimport type { GuardListener } from '../remoteGuardPolicy';\nimport { isStepUpAction } from '../webauthnPolicy';\n\nconst NONCE_BYTES = 16;\nconst BAD_REQUEST = 400;\nconst FORBIDDEN = 403;\nconst NOT_FOUND = 404;\nconst CONFLICT = 409;\nconst GONE = 410;\nconst TOO_MANY = 429;\nconst BAD_GATEWAY = 502;\nconst UNAUTHORIZED = 401;\nconst ACCEPTED = 202;\nconst CREATED = 201;\nconst SERVICE_UNAVAILABLE = 503;\n/** Trusted Cloudflare client address, used for display and public abuse throttling only. */\nconst EDGE_IP_HEADER = 'cf-connecting-ip';\nconst PAYLOAD_TOO_LARGE = 413;\nconst REQUEST_TIMEOUT = 408;\nconst PUBLIC_REQUEST_CONCURRENCY = 8;\nconst PUBLIC_REQUEST_TIMEOUT_MS = 5000;\nconst PAIRING_BODY_BYTES = 2 * 1024;\nconst CHANNEL_BODY_BYTES = 4 * 1024;\nconst PASSKEY_BEGIN_BODY_BYTES = 256;\nconst PASSKEY_FINISH_BODY_BYTES = 64 * 1024;\nconst CEREMONY_CALLER_COOKIE = 'po_ceremony_caller';\nconst CEREMONY_CALLER_TOKEN = /^[A-Za-z0-9_-]{22}$/u;\nconst CEREMONY_CALLER_MAX_AGE_SECONDS = 10 * 60;\nconst PUBLIC_BEGIN_LIMIT = 10;\nconst PUBLIC_BEGIN_WINDOW_MS = 60_000;\nconst PUBLIC_BEGIN_SOURCE_LIMIT = 1024;\n/** Fallback wait before a remote-initiated shutdown, when the raw response is not reachable. */\nconst RESPONSE_FLUSH_GRACE_MS = 250;\nconst CHANNEL_SCOPES: ReadonlySet<RemoteChannelScope> = new Set(['session', 'protocol', 'http']);\n\ninterface NodeRequestBindings {\n incoming?: { socket?: { remoteAddress?: string } };\n sealedDeviceId?: string;\n /** Set only on a sealed re-dispatch, after the gateway checked the step-up assertion. */\n sealedStepUp?: 'verified' | 'not-required';\n}\n\nfunction isChannelScope(value: unknown): value is RemoteChannelScope {\n return typeof value === 'string' && CHANNEL_SCOPES.has(value as RemoteChannelScope);\n}\n\nexport interface RemoteRoutesOptions {\n remote: RemoteAccess;\n federationHost?(): { hostId: string; hostPublicKey: string; enrollmentGeneration?: number } | undefined;\n /** Consumes only the local issuer's account proof, bound to this request and host. */\n pairingAccount?: (proof: string, request: AuthPairingRequest) => Promise<AuthPairingIdentity | undefined>;\n /** Enables the account step on the remote pairing page, never on local attach or personal QR pairing. */\n accountPairing?(): boolean;\n bindAccountDevice?: (pairingId: string, trustedDeviceId: string) => Promise<boolean>;\n unlinkAccount?: (sealedDeviceId: string) => Promise<boolean>;\n claimAccount?: (claim: import('@agimon-ai/po-core').FederationEnvelope<'po/hub-claim/v1'>) => Promise<boolean>;\n enrollAccount?: (\n pairingId: string,\n proof: import('@agimon-ai/po-core').FederationEnvelope<'po/hub-enrollment/v1'>,\n ) => Promise<import('@agimon-ai/po-core').FederationEnvelope<'po/hub-enrollment/v1'> | undefined>;\n /** Which listener a request arrived on, so control-plane routes can stay local. */\n listenerOf: (context: Context) => GuardListener;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function readJson(context: Context): Promise<Record<string, unknown> | undefined> {\n try {\n const body: unknown = await context.req.json();\n return isRecord(body) ? body : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Runs an action once this response has reached the wire.\n *\n * Both callers tear down the listener carrying their own response, and the\n * difference between a confirmed answer and a socket error the caller cannot\n * distinguish from a failure is doing it in this order.\n */\nfunction afterResponse(context: Context, action: () => void): void {\n const outgoing = (context.env as { outgoing?: { once: (event: string, listener: () => void) => void } }).outgoing;\n if (outgoing === undefined) {\n setTimeout(action, RESPONSE_FLUSH_GRACE_MS);\n return;\n }\n outgoing.once('finish', action);\n}\n\n/** What the credential is called in the device list; the user agent is the only hint available. */\nfunction labelFrom(context: Context): string {\n return sanitizeUserAgent(context.req.header('user-agent'));\n}\n\n/**\n * Cloudflare's normalized client address on the tunnel listener, with the\n * actual socket peer as the fallback for local and direct requests.\n *\n * A local process can forge the Cloudflare header, but local processes are\n * already outside this internet-client throttle boundary. Cloudflare is the\n * trusted proxy and overwrites this header for public requests.\n */\nfunction sourceAddressOf(context: Context, listener: GuardListener): string | undefined {\n const socketPeer = (context.env as NodeRequestBindings | undefined)?.incoming?.socket?.remoteAddress;\n if (listener !== 'tunnel') return socketPeer;\n const edgeAddress = sanitizeEdgeIp(context.req.header(EDGE_IP_HEADER));\n return edgeAddress === 'unknown' ? socketPeer : `cloudflare:${edgeAddress}`;\n}\n\nfunction limitedJsonBody(maxSize: number): MiddlewareHandler {\n return bodyLimit({\n maxSize,\n onError: (context) => context.json({ error: 'The request body is too large.' }, PAYLOAD_TOO_LARGE),\n });\n}\n\nfunction createPublicRequestBudget(isLocal: (context: Context) => boolean): MiddlewareHandler {\n let active = 0;\n return async (context, next) => {\n if (isLocal(context)) return next();\n if (active >= PUBLIC_REQUEST_CONCURRENCY) {\n context.header('Retry-After', '1');\n return context.json({ error: 'Too many public requests are already in progress.' }, TOO_MANY);\n }\n active += 1;\n try {\n await next();\n } finally {\n active -= 1;\n }\n };\n}\n\nfunction createPublicBeginLimit(): (source: string) => boolean {\n const windows = new Map<string, { count: number; startedAt: number }>();\n return (source) => {\n const at = Date.now();\n let window = windows.get(source);\n if (window === undefined || at - window.startedAt >= PUBLIC_BEGIN_WINDOW_MS) {\n if (window === undefined && windows.size >= PUBLIC_BEGIN_SOURCE_LIMIT) {\n const oldest = windows.keys().next().value as string | undefined;\n if (oldest !== undefined) windows.delete(oldest);\n }\n window = { count: 0, startedAt: at };\n windows.delete(source);\n windows.set(source, window);\n }\n if (window.count >= PUBLIC_BEGIN_LIMIT) return false;\n window.count += 1;\n return true;\n };\n}\n\n/**\n * Registers the pairing surface and the remote-access control plane.\n *\n * Split by who may reach them, not by shape. The pairing, passkey sign-in, and\n * device sign-in routes are the only unauthenticated ones on the tunnel listener\n * (pinned in `PUBLIC_PAIRING_ROUTES`), so each is small, bounded, and echoes\n * nothing from its request. The control plane is mostly local-only:\n * minting a code, approving, denying, and changing settings all stay at the\n * machine, because a device that can do them can make its own access permanent.\n * Turning remote access off and revoking a credential are allowed remotely, on\n * the grounds that a panic button is worth more from the phone than the desk.\n */\nexport function registerRemoteRoutes(app: Hono, options: RemoteRoutesOptions): void {\n const { remote } = options;\n const isLocal = (context: Context): boolean => options.listenerOf(context) === 'local';\n const localOnly = (context: Context): Response | undefined =>\n isLocal(context) ? undefined : context.json({ error: 'This action is only available on the host.' }, FORBIDDEN);\n const publicBudget = createPublicRequestBudget(isLocal);\n const publicBeginAllowed = createPublicBeginLimit();\n const deviceAuthBeginAllowed = createPublicBeginLimit();\n const sealedDeviceOf = (context: Context): string | undefined =>\n (context.env as NodeRequestBindings | undefined)?.sealedDeviceId;\n const publicDeadline = timeout(\n PUBLIC_REQUEST_TIMEOUT_MS,\n () =>\n new HTTPException(REQUEST_TIMEOUT, {\n res: Response.json({ error: 'The public request timed out.' }, { status: REQUEST_TIMEOUT }),\n }),\n );\n const authenticatedCeremonyCaller = (context: Context): string => {\n const trusted = (context.env as NodeRequestBindings | undefined)?.sealedDeviceId;\n const deviceId = trusted ?? remote.authorize(getCookie(context, DEVICE_COOKIE, 'host'));\n return deviceId === undefined ? 'local' : `device:${deviceId}`;\n };\n const registrationCaller = (context: Context): string | undefined => {\n const caller = authenticatedCeremonyCaller(context);\n return isLocal(context) || caller !== 'local' ? caller : undefined;\n };\n const publicCeremonyCaller = (context: Context, create: boolean): string | undefined => {\n let token = getCookie(context, CEREMONY_CALLER_COOKIE, 'host');\n if (token !== undefined && !CEREMONY_CALLER_TOKEN.test(token)) token = undefined;\n if (token === undefined && create) token = randomBytes(16).toString('base64url');\n if (token !== undefined && create) {\n setCookie(context, CEREMONY_CALLER_COOKIE, token, {\n prefix: 'host',\n httpOnly: true,\n sameSite: 'Strict',\n maxAge: CEREMONY_CALLER_MAX_AGE_SECONDS,\n });\n }\n return token === undefined ? undefined : `public:${token}`;\n };\n app.get(PAIRING_PAGE_ROUTE, (context) => {\n const nonce = randomBytes(NONCE_BYTES).toString('base64');\n const localTrust = options.listenerOf(context) === 'local' ? remote.bundleTrust() : undefined;\n return context.body(\n pairingPageHtml({\n nonce,\n ...(localTrust === undefined ? {} : { localTrust }),\n accountPairing: !isLocal(context) && options.accountPairing?.() === true,\n }),\n 200,\n pairingPageHeaders(nonce),\n );\n });\n\n app.post(PAIRING_CLAIM_ROUTE, publicBudget, publicDeadline, limitedJsonBody(PAIRING_BODY_BYTES), async (context) => {\n let body: unknown;\n try {\n body = await context.req.json();\n } catch {\n return context.json({ error: 'The request body must be JSON.' }, BAD_REQUEST);\n }\n if (\n !isRecord(body) ||\n typeof body.code !== 'string' ||\n body.code === '' ||\n (body.accountRequired !== undefined && typeof body.accountRequired !== 'boolean') ||\n Object.keys(body).some((key) => key !== 'code' && key !== 'accountRequired')\n ) {\n return context.json({ error: 'A code and an optional accountRequired boolean are required.' }, BAD_REQUEST);\n }\n const accountRequired = body.accountRequired === true;\n const host = accountRequired ? options.federationHost?.() : undefined;\n if (accountRequired && (!host || !options.pairingAccount)) {\n return context.json({ error: 'Account pairing is unavailable on this host.' }, SERVICE_UNAVAILABLE);\n }\n const outcome = remote.claim({\n code: body.code,\n userAgent: context.req.header('user-agent'),\n edgeIp: context.req.header(EDGE_IP_HEADER),\n sourceAddress: sourceAddressOf(context, options.listenerOf(context)),\n ...(accountRequired ? { accountRequired: true } : {}),\n });\n if (outcome.ok)\n return context.json(\n {\n requestId: outcome.requestId,\n status: 'pending',\n ...(host ? { accountRequired: true, hostPublicKey: host.hostPublicKey } : {}),\n },\n ACCEPTED,\n );\n if (outcome.code === 'unknown_code') return context.json({ error: 'That code is not valid.' }, GONE);\n return context.json({ error: 'Too many attempts.' }, TOO_MANY);\n });\n\n app.post(\n PAIRING_ACCOUNT_ROUTE,\n publicBudget,\n publicDeadline,\n limitedJsonBody(PAIRING_BODY_BYTES),\n async (context) => {\n const body = await readJson(context);\n if (\n !body ||\n Object.keys(body).length !== 2 ||\n typeof body.requestId !== 'string' ||\n !/^[A-Za-z0-9_-]{1,128}$/u.test(body.requestId) ||\n typeof body.proof !== 'string' ||\n !/^[a-f0-9]{64}$/u.test(body.proof)\n ) {\n return context.json({ error: 'A pending request id and account proof are required.' }, BAD_REQUEST);\n }\n const host = options.federationHost?.();\n if (!host || !options.pairingAccount)\n return context.json({ error: 'Account pairing is unavailable on this host.' }, SERVICE_UNAVAILABLE);\n if (remote.pairingStatus(body.requestId) !== 'pending')\n return context.json({ error: 'That pairing is no longer pending.' }, CONFLICT);\n try {\n const account = await options.pairingAccount(body.proof, {\n requestId: body.requestId,\n hostPublicKey: host.hostPublicKey,\n });\n if (!account) return context.json({ error: 'That account proof was refused.' }, UNAUTHORIZED);\n if (\n context.finalized ||\n context.req.raw.signal.aborted ||\n options.federationHost?.()?.hostPublicKey !== host.hostPublicKey ||\n !remote.bindPairingAccount(body.requestId, account)\n ) {\n return context.json({ error: 'That pairing is no longer waiting for account verification.' }, CONFLICT);\n }\n return context.json({ status: 'pending' }, ACCEPTED);\n } catch {\n return context.json({ error: 'Account verification is unavailable.' }, SERVICE_UNAVAILABLE);\n }\n },\n );\n\n app.get(PAIRING_STATUS_ROUTE, (context) => {\n const requestId = context.req.query(PAIRING_STATUS_QUERY);\n if (requestId === undefined) return context.json({ error: 'A request id is required.' }, BAD_REQUEST);\n const status = remote.pairingStatus(requestId);\n if (status === undefined) return context.json({ error: 'No such pairing request.' }, NOT_FOUND);\n if (status !== 'approved') return context.json({ status });\n const redeemed = remote.redeem(requestId);\n if (redeemed === undefined) return context.json({ status: 'consumed' });\n // Secure is a constant, never derived. cloudflared terminates TLS at the\n // edge and forwards plaintext, so the request scheme here is http and\n // x-forwarded-proto is attacker-controllable; hono's host prefix hardcodes\n // Secure, Path=/ and no Domain, and throws if they are contradicted.\n setCookie(context, DEVICE_COOKIE, redeemed.token, {\n prefix: 'host',\n httpOnly: true,\n sameSite: 'Lax',\n maxAge: redeemed.maxAgeSeconds,\n });\n return context.json({\n status: 'approved',\n bundleTrust: remote.bundleTrust(),\n hostPublicKey: remote.channelPublicKey(),\n federationHost: options.federationHost?.(),\n });\n });\n\n app.get(REMOTE_API_ROUTE, (context) => {\n // So a remote caller's own row can be marked \"this device\" and it cannot\n // revoke itself by accident while hunting for a stale one.\n const self = remote.authorize(getCookie(context, DEVICE_COOKIE, 'host'));\n return context.json({ state: remote.state(self, isLocal(context)) });\n });\n\n app.post(`${REMOTE_API_ROUTE}/enable`, async (context) => {\n const refused = localOnly(context);\n if (refused) return refused;\n const outcome = await remote.enable();\n if (!outcome.ok) return context.json({ error: outcome.error }, BAD_GATEWAY);\n return context.json({ state: remote.state(undefined, true) });\n });\n\n // Deliberately reachable from a paired device: this is the panic button.\n app.post(`${REMOTE_API_ROUTE}/disable`, async (context) => {\n if (isLocal(context)) {\n await remote.disable();\n return context.json({ state: remote.state(undefined, true) });\n }\n // Switching off from the phone tears down the listener carrying this very\n // response.\n afterResponse(context, () => void remote.disable());\n return context.json({ status: 'closing' }, ACCEPTED);\n });\n\n app.post(`${REMOTE_API_ROUTE}/codes`, (context) => {\n const refused = localOnly(context);\n if (refused) return refused;\n const minted = remote.mintPairing();\n if (minted === undefined)\n return context.json({ error: 'Remote access or signed bundle publication is unavailable.' }, CONFLICT);\n return context.json(minted, CREATED);\n });\n\n app.post(`${REMOTE_API_ROUTE}/pairing/:id/approve`, (context) => {\n const refused = localOnly(context);\n if (refused) return refused;\n const outcome = remote.approve(context.req.param('id'));\n if (outcome === 'approved') return context.json({ state: remote.state(undefined, true) });\n if (outcome === 'unknown') return context.json({ error: 'No such pairing request.' }, NOT_FOUND);\n return context.json({ error: `That request is ${outcome}.` }, CONFLICT);\n });\n\n app.post(`${REMOTE_API_ROUTE}/pairing/:id/deny`, (context) => {\n const refused = localOnly(context);\n if (refused) return refused;\n const outcome = remote.deny(context.req.param('id'));\n if (outcome === 'denied') return context.json({ state: remote.state(undefined, true) });\n if (outcome === 'unknown') return context.json({ error: 'No such pairing request.' }, NOT_FOUND);\n return context.json({ error: 'That request is already settled.' }, CONFLICT);\n });\n\n app.delete(`${REMOTE_API_ROUTE}/devices/:id`, (context) => {\n if (!remote.revokeDevice(context.req.param('id'))) {\n return context.json({ error: 'No such device.' }, NOT_FOUND);\n }\n return context.json({ state: remote.state(undefined, isLocal(context)) });\n });\n\n // Registration is direct so the approved phone can enrol before opening the\n // cockpit. On the tunnel listener, the device cookie remains mandatory.\n app.get(`${REMOTE_API_ROUTE}/passkeys`, (context) => {\n const passkeys = remote.passkeys();\n return context.json({\n support: passkeys.support(),\n credentials: passkeys.list().map(({ id, label, createdAt, lastUsedAt }) => ({\n id,\n label,\n createdAt: new Date(createdAt).toISOString(),\n lastUsedAt: new Date(lastUsedAt).toISOString(),\n })),\n });\n });\n\n /**\n * Registers a native device. Sealed only, so the relay never reads the keys, and only from a session\n * the host approved by QR. Unsealed requests never get here on the tunnel listener; this check\n * covers the loopback one too.\n */\n app.post(\n `${REMOTE_API_ROUTE}/federation/unlink`,\n limitedJsonBody(TRUSTED_DEVICE_REGISTER_BODY_BYTES),\n async (context) => {\n const deviceId = sealedDeviceOf(context);\n if (!deviceId || !options.unlinkAccount) return context.json({ error: 'Hub unlink unavailable.' }, UNAUTHORIZED);\n const body = await readJson(context);\n const trustedDeviceId = remote.state(deviceId).trustedDevices?.find((device) => device.self)?.id;\n const pinnedDeviceId = trustedDeviceId ?? (remote.trustKind(deviceId) === 'pairing' ? deviceId : undefined);\n try {\n if (pinnedDeviceId && body?.reason === 'owner-request' && (await options.unlinkAccount(pinnedDeviceId)))\n return context.json({ unlinked: true });\n } catch {\n return context.json({ error: 'Hub unlink refused.' }, FORBIDDEN);\n }\n return context.json({ error: 'Hub unlink refused.' }, FORBIDDEN);\n },\n );\n\n app.post(\n `${REMOTE_API_ROUTE}/federation/claim`,\n limitedJsonBody(TRUSTED_DEVICE_REGISTER_BODY_BYTES),\n async (context) => {\n if (!sealedDeviceOf(context)) return context.json({ error: 'A sealed paired device is required.' }, UNAUTHORIZED);\n if (!options.claimAccount) return context.json({ error: 'Account claims are unavailable.' }, UNAUTHORIZED);\n const body = await readJson(context);\n try {\n const accepted =\n body?.claim &&\n (await options.claimAccount(\n body.claim as import('@agimon-ai/po-core').FederationEnvelope<'po/hub-claim/v1'>,\n ));\n return accepted ? context.json({ claimed: true }) : context.json({ error: 'Hub claim refused.' }, FORBIDDEN);\n } catch {\n return context.json({ error: 'Hub claim refused.' }, FORBIDDEN);\n }\n },\n );\n\n app.post(\n `${REMOTE_API_ROUTE}/federation/enroll`,\n limitedJsonBody(TRUSTED_DEVICE_REGISTER_BODY_BYTES),\n async (context) => {\n const pairingId = sealedDeviceOf(context);\n if (pairingId && remote.accountOf(pairingId))\n return context.json(\n { error: 'This account pairing reconnects with its passkey, not account-device enrollment.' },\n FORBIDDEN,\n );\n if (!pairingId || remote.trustKind(pairingId) !== 'pairing')\n return context.json({ error: 'A fresh sealed QR pairing is required.' }, FORBIDDEN);\n if (!options.enrollAccount)\n return context.json({ error: 'Account enrollment is unavailable.' }, SERVICE_UNAVAILABLE);\n const body = await readJson(context);\n if (!body?.enrollment) return context.json({ error: 'Account device proof required.' }, BAD_REQUEST);\n const pairedAt = Date.parse(remote.state(pairingId).devices.find((device) => device.self)?.createdAt ?? '');\n const proof = body.enrollment as import('@agimon-ai/po-core').FederationEnvelope<'po/hub-enrollment/v1'>;\n if (!Number.isSafeInteger(pairedAt) || proof.payload?.pairedAt !== pairedAt)\n return context.json({ error: 'The proof must bind the actual QR pairing time.' }, FORBIDDEN);\n try {\n const enrollment = await options.enrollAccount(\n pairingId,\n body.enrollment as import('@agimon-ai/po-core').FederationEnvelope<'po/hub-enrollment/v1'>,\n );\n return enrollment\n ? context.json({ enrollment }, CREATED)\n : context.json({ error: 'Account enrollment refused.' }, FORBIDDEN);\n } catch {\n return context.json({ error: 'Account enrollment refused.' }, FORBIDDEN);\n }\n },\n );\n\n app.post(TRUSTED_DEVICES_ROUTE, limitedJsonBody(TRUSTED_DEVICE_REGISTER_BODY_BYTES), async (context) => {\n const sessionDeviceId = sealedDeviceOf(context);\n if (sessionDeviceId === undefined)\n return context.json({ error: 'Devices register through the sealed gateway.' }, FORBIDDEN);\n if (remote.accountOf(sessionDeviceId))\n return context.json(\n { error: 'This account pairing reconnects with its passkey, not native device enrollment.' },\n FORBIDDEN,\n );\n const body = await readJson(context);\n if (body === undefined) return context.json({ error: 'The request body must be a JSON object.' }, BAD_REQUEST);\n const outcome = remote.registerTrustedDevice(sessionDeviceId, body);\n if (outcome.ok) {\n if (options.bindAccountDevice && !(await options.bindAccountDevice(sessionDeviceId, outcome.trustedDeviceId)))\n return context.json({ error: 'The account device binding could not be saved.' }, SERVICE_UNAVAILABLE);\n return context.json({ trustedDeviceId: outcome.trustedDeviceId }, CREATED);\n }\n if (outcome.reason === 'forbidden')\n return context.json({ error: 'Only a freshly paired session can register this device.' }, FORBIDDEN);\n if (outcome.reason === 'persistence')\n return context.json({ error: 'The trusted device could not be saved.' }, SERVICE_UNAVAILABLE);\n if (outcome.reason === 'full')\n return context.json({ error: 'Too many trusted devices. Revoke one first.' }, CONFLICT);\n if (outcome.reason === 'unavailable') return context.json({ error: 'Remote access is unavailable.' }, CONFLICT);\n return context.json({ error: 'The device keys or proofs were not valid.' }, BAD_REQUEST);\n });\n\n // No cookie or body-supplied identity can substitute for the sealed session binding.\n app.post(NATIVE_PUSH_ROUTE, limitedJsonBody(NATIVE_PUSH_BODY_BYTES), async (context) => {\n const sessionDeviceId = sealedDeviceOf(context);\n if (sessionDeviceId === undefined)\n return context.json({ error: 'Native push requires a sealed trusted device session.' }, FORBIDDEN);\n const body = await readJson(context);\n if (body === undefined) return context.json({ error: 'A registration object is required.' }, BAD_REQUEST);\n const outcome = remote.setNativePushRegistration(sessionDeviceId, body);\n if (outcome.ok) return context.json({ notificationId: outcome.notificationId });\n if (outcome.reason === 'forbidden')\n return context.json({ error: 'A trusted native session is required.' }, FORBIDDEN);\n if (outcome.reason === 'persistence')\n return context.json({ error: 'The registration could not be saved.' }, SERVICE_UNAVAILABLE);\n return context.json({ error: 'The native push registration is invalid.' }, BAD_REQUEST);\n });\n\n app.delete(NATIVE_PUSH_ROUTE, limitedJsonBody(NATIVE_PUSH_BODY_BYTES), (context) => {\n const sessionDeviceId = sealedDeviceOf(context);\n if (sessionDeviceId === undefined)\n return context.json({ error: 'Native push requires a sealed trusted device session.' }, FORBIDDEN);\n const outcome = remote.setNativePushRegistration(sessionDeviceId, undefined);\n if (outcome.ok) return context.json({ notificationId: outcome.notificationId });\n if (outcome.reason === 'persistence')\n return context.json({ error: 'The registration could not be saved.' }, SERVICE_UNAVAILABLE);\n return context.json({ error: 'A trusted native session is required.' }, FORBIDDEN);\n });\n\n /**\n * Revokes a trusted device and every session it holds. From the host, or from a sealed caller that\n * passed step-up. A quick-tunnel browser cannot step up, so it is told where revoking works.\n */\n app.delete(`${TRUSTED_DEVICES_ROUTE}/:id`, (context) => {\n const stepUp = (context.env as NodeRequestBindings | undefined)?.sealedStepUp;\n if (!isLocal(context) && stepUp !== 'verified')\n return context.json({ error: 'Revoke from the host or a trusted native device.' }, FORBIDDEN);\n if (!remote.revokeTrustedDevice(context.req.param('id'))) {\n if (remote.state().trustedDevices.some((record) => record.id === context.req.param('id')))\n return context.json({ error: 'The trusted device could not be removed.' }, SERVICE_UNAVAILABLE);\n return context.json({ error: 'No such trusted device.' }, NOT_FOUND);\n }\n return context.json({\n state: remote.state(isLocal(context) ? undefined : sealedDeviceOf(context), isLocal(context)),\n });\n });\n\n /**\n * Public reconnect challenge for a trusted native device. Rate limited on its own, and the answer has\n * the same shape for an unknown id, so probing cannot list devices.\n */\n app.post(\n DEVICE_AUTH_CHALLENGE_ROUTE,\n publicBudget,\n publicDeadline,\n limitedJsonBody(DEVICE_AUTH_CHALLENGE_BODY_BYTES),\n async (context) => {\n const listener = options.listenerOf(context);\n const source = sourceAddressOf(context, listener) ?? 'unknown';\n if (listener === 'tunnel' && !deviceAuthBeginAllowed(source)) {\n context.header('Retry-After', '60');\n return context.json({ error: 'Too many device sign-in attempts. Try again shortly.' }, TOO_MANY);\n }\n const body = await readJson(context);\n const begun = remote.beginDeviceAuth({ trustedDeviceId: body?.trustedDeviceId, nonce: body?.nonce });\n if (begun.ok) {\n const { challengeId, challenge, hostPublicKey, attestation } = begun;\n return context.json({ challengeId, challenge, hostPublicKey, attestation });\n }\n if (begun.reason === 'invalid')\n return context.json({ error: 'A trustedDeviceId and a 32-byte nonce are required.' }, BAD_REQUEST);\n return context.json({ error: 'Device sign-in is unavailable.' }, CONFLICT);\n },\n );\n\n /** Completes a device sign-in. Any failure is the same plain 401. */\n app.post(\n DEVICE_AUTH_AUTHENTICATE_ROUTE,\n publicBudget,\n publicDeadline,\n limitedJsonBody(DEVICE_AUTH_AUTHENTICATE_BODY_BYTES),\n async (context) => {\n const session = remote.finishDeviceAuth(await readJson(context));\n if (session === undefined) return context.json({ error: 'Device sign-in failed.' }, UNAUTHORIZED);\n // Same attributes as passkey sign-in: Secure, Path=/, Domain-less through the host prefix.\n setCookie(context, DEVICE_COOKIE, session.token, {\n prefix: 'host',\n httpOnly: true,\n sameSite: 'Lax',\n maxAge: session.maxAgeSeconds,\n });\n return context.json({ ok: true });\n },\n );\n\n app.post(\n PASSKEY_REGISTER_BEGIN_ROUTE,\n publicBudget,\n publicDeadline,\n limitedJsonBody(PASSKEY_BEGIN_BODY_BYTES),\n async (context) => {\n const caller = registrationCaller(context);\n if (caller === undefined) return context.json({ error: 'This device is not paired.' }, UNAUTHORIZED);\n const begun = await remote.passkeys().beginRegistration(caller, labelFrom(context));\n if (begun === undefined) return context.json({ error: remote.passkeys().support() }, CONFLICT);\n return context.json(begun);\n },\n );\n\n app.post(\n PASSKEY_REGISTER_FINISH_ROUTE,\n publicBudget,\n publicDeadline,\n limitedJsonBody(PASSKEY_FINISH_BODY_BYTES),\n async (context) => {\n const caller = registrationCaller(context);\n if (caller === undefined) return context.json({ error: 'This device is not paired.' }, UNAUTHORIZED);\n const body = await readJson(context);\n if (body === undefined || typeof body.ceremonyId !== 'string' || !('response' in body)) {\n return context.json({ error: 'A ceremonyId and response are required.' }, BAD_REQUEST);\n }\n const outcome = await remote\n .passkeys()\n .finishRegistration(body.ceremonyId, caller, body.response, labelFrom(context));\n if (!outcome.ok) return context.json({ error: outcome.error }, BAD_REQUEST);\n return context.json({ id: outcome.id });\n },\n );\n\n // Sign-in is reachable unauthenticated on purpose: proving a registered\n // passkey is how a returning device gets a session without another QR.\n app.post(\n PASSKEY_AUTH_BEGIN_ROUTE,\n publicBudget,\n publicDeadline,\n limitedJsonBody(PASSKEY_BEGIN_BODY_BYTES),\n async (context) => {\n const listener = options.listenerOf(context);\n const source = sourceAddressOf(context, listener) ?? 'unknown';\n if (listener === 'tunnel' && !publicBeginAllowed(source)) {\n context.header('Retry-After', '60');\n return context.json({ error: 'Too many passkey sign-in attempts. Try again shortly.' }, TOO_MANY);\n }\n const caller = publicCeremonyCaller(context, true);\n if (caller === undefined) return context.json({ error: 'Could not start this sign-in.' }, CONFLICT);\n const begun = await remote.passkeys().beginAuthentication(caller);\n if (begun === undefined) return context.json({ error: 'Passkeys are unavailable.' }, CONFLICT);\n return context.json(begun);\n },\n );\n\n app.post(\n PASSKEY_AUTH_FINISH_ROUTE,\n publicBudget,\n publicDeadline,\n limitedJsonBody(PASSKEY_FINISH_BODY_BYTES),\n async (context) => {\n const body = await readJson(context);\n if (body === undefined || typeof body.ceremonyId !== 'string' || !('response' in body)) {\n return context.json({ error: 'A ceremonyId and response are required.' }, BAD_REQUEST);\n }\n const caller = publicCeremonyCaller(context, false);\n if (caller === undefined)\n return context.json({ error: 'That sign-in was not started by this browser.' }, UNAUTHORIZED);\n const outcome = await remote.passkeys().finishAuthentication(body.ceremonyId, caller, body.response);\n if (!outcome.ok) return context.json({ error: outcome.error }, UNAUTHORIZED);\n const hostPublicKey = remote.channelPublicKey();\n if (hostPublicKey === undefined) return context.json({ error: 'Sealed channels are unavailable.' }, CONFLICT);\n const session = remote.sessionForPasskey(outcome.credential.label, outcome.credential.account);\n setCookie(context, DEVICE_COOKIE, session.token, {\n prefix: 'host',\n httpOnly: true,\n sameSite: 'Lax',\n maxAge: session.maxAgeSeconds,\n });\n return context.json({ ok: true, hostPublicKey });\n },\n );\n\n app.delete(`${REMOTE_API_ROUTE}/passkeys/:id`, (context) => {\n const refused = localOnly(context);\n if (refused) return refused;\n if (!remote.passkeys().forget(context.req.param('id'))) {\n return context.json({ error: 'No such passkey.' }, NOT_FOUND);\n }\n return context.json({ ok: true });\n });\n\n /** A challenge bound to one action, so it cannot be replayed to authorise another. */\n app.post(`${REMOTE_API_ROUTE}/challenge`, async (context) => {\n const body = await readJson(context);\n if (body === undefined || !isStepUpAction(body.action)) {\n return context.json({ error: 'A known action is required.' }, BAD_REQUEST);\n }\n const deviceId = sealedDeviceOf(context) ?? remote.authorize(getCookie(context, DEVICE_COOKIE, 'host'));\n // A device-key session answers with its biometric key, never a passkey.\n if (deviceId !== undefined && remote.trustKind(deviceId) === 'device-key') {\n const challenge = remote.beginDeviceStepUp(deviceId, body.action);\n if (challenge === undefined) return context.json({ error: 'Device step-up is unavailable.' }, CONFLICT);\n return context.json(challenge);\n }\n const begun = await remote.passkeys().beginStepUp(authenticatedCeremonyCaller(context), body.action);\n if (begun === undefined) return context.json({ error: 'Passkeys are unavailable.' }, CONFLICT);\n return context.json(begun);\n });\n\n /**\n * Completes the sealed channel for the calling device.\n *\n * Unsealed by necessity: this is the request that establishes sealing. It\n * carries only a public key, which is safe for the relay to see, and needs the\n * host key delivered by an approved QR or successful passkey sign-in.\n */\n app.post(REMOTE_CHANNEL_ROUTE, limitedJsonBody(CHANNEL_BODY_BYTES), async (context) => {\n const device = remote.authorize(getCookie(context, DEVICE_COOKIE, 'host'));\n if (device === undefined) return context.json({ error: 'This device is not paired.' }, UNAUTHORIZED);\n // A device-key session opened all of its channels inside the signed sign-in; adding one here would\n // let a relay holding the cookie splice in its own key.\n if (remote.trustKind(device) === 'device-key')\n return context.json({ error: 'This session opened its channels at sign-in.' }, FORBIDDEN);\n const body = await readJson(context);\n if (body === undefined || typeof body.clientPublicKey !== 'string' || !isChannelScope(body.scope)) {\n return context.json({ error: 'A clientPublicKey and known scope are required.' }, BAD_REQUEST);\n }\n if (!remote.openChannel(device, body.scope, body.clientPublicKey)) {\n return context.json({ error: 'That key did not complete a fresh channel.' }, BAD_REQUEST);\n }\n return context.json({ ok: true });\n });\n\n app.put(`${REMOTE_API_ROUTE}/settings`, async (context) => {\n const refused = localOnly(context);\n if (refused) return refused;\n let body: unknown;\n try {\n body = await context.req.json();\n } catch {\n return context.json({ error: 'The request body must be JSON.' }, BAD_REQUEST);\n }\n if (!isRecord(body)) return context.json({ error: 'The settings must be an object.' }, BAD_REQUEST);\n const settings = remote.updateSettings(body);\n return context.json({ settings });\n });\n}\n","/**\n * Turning a tunnel configuration into a command line, and cloudflared's output\n * back into a public origin.\n *\n * The parsing half only exists for quick tunnels. A named tunnel is configured\n * with its hostname, so nothing has to be scraped and the origin is known\n * before the process starts. That difference is the strongest practical\n * argument for named mode: the banner cloudflared prints is an undocumented\n * detail of its logging, and a release that reformats it breaks quick mode\n * until the readiness deadline fires.\n */\n\nimport type { TunnelConfig, TunnelFailure } from '@agimon-ai/po-core/remoteContract';\n\n/**\n * A trycloudflare hostname, and nothing that merely ends near one.\n *\n * The trailing lookahead is the whole point. Without it,\n * `https://evil.trycloudflare.com.attacker.tld` printed by a confused or\n * hostile process would match, and the extracted value becomes the origin the\n * guard then trusts for every subsequent request.\n */\nconst QUICK_TUNNEL_URL = /https:\\/\\/[a-z0-9][a-z0-9-]*(?:\\.[a-z0-9-]+)*\\.trycloudflare\\.com(?![a-z0-9.-])/iu;\n\n/** Cloudflare reports a connection registered; readiness waits for this as well as a URL. */\nconst CONNECTION_READY = /registered tunnel connection|connection .* registered/iu;\n\nexport function tunnelTarget(port: number): string {\n return `http://127.0.0.1:${String(port)}`;\n}\n\n/**\n * The cloudflared argument vector.\n *\n * `--url` is a flag on the `tunnel` command rather than on `run`, so it comes\n * before the subcommand in both shapes. `--token-file` belongs to `run`.\n *\n * Flag placement here follows cloudflared's documented usage and local help.\n */\nexport function tunnelArgs(config: TunnelConfig, port: number, tokenFile?: string): string[] {\n const args = ['tunnel', '--no-autoupdate'];\n if (config.kind === 'named' && config.configFile !== undefined) args.push('--config', config.configFile);\n args.push('--url', tunnelTarget(port));\n if (config.kind === 'quick') return args;\n args.push('run');\n if (tokenFile !== undefined && tokenFile !== '') args.push('--token-file', tokenFile);\n if (config.name !== undefined) args.push(config.name);\n return args;\n}\n\n/** The public origin a quick tunnel announced, or undefined if this output does not carry one. */\nexport function extractTunnelUrl(text: string): string | undefined {\n return QUICK_TUNNEL_URL.exec(text)?.[0].toLowerCase();\n}\n\nexport function mentionsRegisteredConnection(text: string): boolean {\n return CONNECTION_READY.test(text);\n}\n\n/** Operator-facing copy for a failure, with the cause appended by the caller. */\nexport function describeTunnelFailure(failure: TunnelFailure): string {\n switch (failure) {\n case 'not_installed':\n return 'cloudflared is not installed. Install it (brew install cloudflared) or set PO_CLOUDFLARED.';\n case 'spawn_failed':\n return 'cloudflared could not be started.';\n case 'timeout':\n return 'cloudflared did not report a public URL in time.';\n case 'self_test_failed':\n return 'The tunnel came up unguarded and was closed immediately.';\n case 'exited':\n return 'cloudflared stopped on its own.';\n }\n}\n","import { type ChildProcess, spawn } from 'node:child_process';\nimport { readFileSync, rmSync } from 'node:fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { PAIRING_PAGE_MARKER } from '@agimon-ai/po-core/pairingPage';\nimport { PAIRING_PAGE_ROUTE } from '@agimon-ai/po-core/remoteContract';\nimport {\n type TunnelConfig,\n type TunnelLauncher,\n type TunnelStartInput,\n type TunnelStartResult,\n} from '@agimon-ai/po-core/remoteContract';\n\nimport { describeTunnelFailure, extractTunnelUrl, mentionsRegisteredConnection, tunnelArgs } from '../tunnelOutput';\n\n/** Explicit binary path, ahead of a PATH scan. */\nexport const CLOUDFLARED_ENV = 'PO_CLOUDFLARED';\n// Give new quick-host DNS and negative caches time to settle, within a bounded startup.\nconst START_TIMEOUT_MS = 120_000;\nconst TERMINATE_GRACE_MS = 2000;\nconst SELF_TEST_ATTEMPTS = 240;\nconst SELF_TEST_RETRY_MS = 500;\nconst NAMED_RESTART_ATTEMPTS = 3;\nconst NAMED_RESTART_BASE_DELAY_MS = 500;\nconst NAMED_RESTART_MAX_DELAY_MS = 4000;\nconst NAMED_RESTART_STABLE_MS = 60_000;\n/** Lines of process output kept for a failure report. */\nconst LOG_TAIL = 20;\nconst UNAUTHORIZED = 401;\n/** Cloudflare has the DNS route but no connector has registered yet. */\nconst EDGE_TUNNEL_UNAVAILABLE = 530;\nconst OK = 200;\nconst PID_FILE = 'tunnel.pid';\nconst TOKEN_FILE = 'tunnel.token';\nconst FILE_MODE = 0o600;\n/** A pid file older than this is stale beyond usefulness and the pid has likely been recycled. */\nconst PID_FILE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport interface ProbeResult {\n status: number;\n body: string;\n}\n\nexport interface TunnelProcessOptions {\n /** Explicit binary, ahead of the env var and the PATH scan. */\n cloudflaredPath?: string;\n stateDir: string;\n onNotice?: (message: string) => void;\n /** Test seam: stands in for node:child_process.spawn. */\n spawnProcess?: typeof spawn;\n /** Test seam: reaches the tunnel from outside, so the self-test needs no network. */\n probe?: (url: string, signal: AbortSignal) => Promise<ProbeResult>;\n /** Test seam: production waits briefly for a new public hostname to propagate. */\n selfTestRetryMs?: number;\n /** Test seam: production bounds the complete startup, including its self-test. */\n startTimeoutMs?: number;\n /** Test seam: production backs named-tunnel restarts off from 500 ms. */\n restartBaseDelayMs?: number;\n /** Test seam: production resets the rapid-crash budget after one stable minute. */\n restartStableMs?: number;\n /** Called after a quick tunnel exits, or after named-tunnel recovery is exhausted. */\n onExit?: (message: string) => void;\n}\n\n/**\n * Finds cloudflared without a shell.\n *\n * A manual scan rather than `which`: spawning a shell to locate a binary is a\n * quoting hazard for no benefit, and this also works the same on every platform.\n */\nexport async function findCloudflared(env: NodeJS.ProcessEnv = process.env): Promise<string | undefined> {\n const names = process.platform === 'win32' ? ['cloudflared.exe', 'cloudflared'] : ['cloudflared'];\n for (const directory of (env.PATH ?? '').split(path.delimiter)) {\n if (directory === '') continue;\n for (const name of names) {\n const candidate = path.join(directory, name);\n try {\n await fs.access(candidate, fs.constants.X_OK);\n return candidate;\n } catch {\n // Not here, or not executable; keep looking.\n }\n }\n }\n return undefined;\n}\n\nasync function defaultProbe(url: string, signal: AbortSignal): Promise<ProbeResult> {\n const response = await fetch(url, { redirect: 'manual', signal });\n return { status: response.status, body: await response.text() };\n}\n\n/**\n * Kills a tunnel left behind by a hub that could not clean up after itself.\n *\n * A SIGKILLed hub never runs its exit handler, and the child is not detached so\n * it is reparented rather than killed. It then holds the tunnel open against a\n * dead port. This is the sweep on the next start.\n *\n * The residual risk is pid reuse after a reboot. The age window narrows it and\n * on Linux the command line is checked; macOS has no equally cheap check, so\n * there the window stands.\n */\ninterface TunnelPidRecord {\n pid?: unknown;\n ownerPid?: unknown;\n startedAt?: unknown;\n}\n\nfunction validPid(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\n/** Only ESRCH proves the owner is gone; permission and platform errors fail safe. */\nfunction ownerMayBeAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n}\n\n// sync: exported createRemoteRuntime must reap stale public tunnels before its synchronous startup returns.\nexport function reapStaleTunnel(stateDir: string, onNotice: (message: string) => void): void {\n const pidPath = path.join(stateDir, PID_FILE);\n const tokenPath = path.join(stateDir, TOKEN_FILE);\n let raw: string;\n try {\n raw = readFileSync(pidPath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') rmSync(tokenPath, { force: true });\n return; // No pid file is the normal case; other read failures are unsafe to guess through.\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return; // A malformed record cannot prove that its owner is gone.\n }\n if (typeof parsed !== 'object' || parsed === null) return;\n const record = parsed as TunnelPidRecord;\n if (Object.hasOwn(record, 'ownerPid')) {\n if (!validPid(record.ownerPid) || ownerMayBeAlive(record.ownerPid)) return;\n }\n\n rmSync(tokenPath, { force: true });\n rmSync(pidPath, { force: true });\n const pid = validPid(record.pid) ? record.pid : undefined;\n const startedAt = typeof record.startedAt === 'number' ? record.startedAt : 0;\n if (pid === undefined || Date.now() - startedAt > PID_FILE_MAX_AGE_MS) return;\n if (process.platform === 'linux') {\n try {\n if (!readFileSync(`/proc/${String(pid)}/cmdline`, 'utf8').includes('cloudflared')) return;\n } catch {\n return; // The process is gone.\n }\n }\n try {\n process.kill(pid, 'SIGTERM');\n onNotice(`stopped a tunnel left running by a previous hub (pid ${String(pid)})`);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') onNotice(`Could not stop stale tunnel: ${String(error)}`);\n }\n}\n\nfunction tailOf(lines: readonly string[]): string {\n return lines.slice(-LOG_TAIL).join('').trim();\n}\n\n/** Copies a named tunnel token to a private runtime file understood by cloudflared. */\nasync function writeTokenFile(config: TunnelConfig, stateDir: string): Promise<string | undefined> {\n if (config.kind !== 'named' || config.tokenFile === undefined) return undefined;\n let token: string;\n let sourcePath: string;\n try {\n sourcePath = await fs.realpath(config.tokenFile);\n token = (await fs.readFile(sourcePath, 'utf8')).trim();\n } catch {\n return undefined;\n }\n if (token === '') return undefined;\n await fs.mkdir(stateDir, { recursive: true, mode: 0o700 });\n const tokenPath = path.join(stateDir, TOKEN_FILE);\n let existingTarget: string | undefined;\n try {\n existingTarget = await fs.realpath(tokenPath);\n } catch (error) {\n // Missing is the normal state before launch; other failures must not hide an alias.\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (sourcePath === path.resolve(tokenPath) || sourcePath === existingTarget) {\n throw new Error('The configured tunnel token file cannot also be Po runtime token storage.');\n }\n await fs.rm(tokenPath, { force: true });\n await fs.writeFile(tokenPath, token, { mode: FILE_MODE });\n await fs.chmod(tokenPath, FILE_MODE);\n return tokenPath;\n}\n\nexport function createTunnelLauncher(options: TunnelProcessOptions): TunnelLauncher {\n const notice = options.onNotice ?? ((): void => {});\n const restartBaseDelayMs = options.restartBaseDelayMs ?? NAMED_RESTART_BASE_DELAY_MS;\n const restartStableMs = options.restartStableMs ?? NAMED_RESTART_STABLE_MS;\n\n return async function launch(input: TunnelStartInput): Promise<TunnelStartResult> {\n let stopped = false;\n let activeStop: (() => Promise<void>) | undefined;\n let stopPromise: Promise<void> | undefined;\n let recoveryPromise: Promise<void> | undefined;\n let pendingExit: string | undefined;\n let restartCount = 0;\n let lastReadyAt = 0;\n const recoveryAbort = new AbortController();\n const signal =\n input.signal === undefined ? recoveryAbort.signal : AbortSignal.any([input.signal, recoveryAbort.signal]);\n const supervisedInput: TunnelStartInput = { ...input, signal };\n\n function queueUnexpectedExit(message: string): void {\n if (stopped) return;\n if (input.config.kind === 'quick') {\n options.onExit?.(message);\n return;\n }\n if (recoveryPromise !== undefined) {\n pendingExit = message;\n return;\n }\n beginRecovery(message);\n }\n\n const single = createSingleTunnelLauncher({ ...options, onExit: queueUnexpectedExit });\n\n async function waitForRestart(attempt: number): Promise<void> {\n if (recoveryAbort.signal.aborted) return;\n const delayMs = Math.min(restartBaseDelayMs * 2 ** (attempt - 1), NAMED_RESTART_MAX_DELAY_MS);\n await new Promise<void>((resolve) => {\n let timer: ReturnType<typeof setTimeout>;\n const done = (): void => {\n clearTimeout(timer);\n recoveryAbort.signal.removeEventListener('abort', done);\n resolve();\n };\n timer = setTimeout(done, delayMs);\n recoveryAbort.signal.addEventListener('abort', done, { once: true });\n if (recoveryAbort.signal.aborted) done();\n });\n }\n\n async function recover(initialMessage: string): Promise<void> {\n if (Date.now() - lastReadyAt >= restartStableMs) restartCount = 0;\n let lastFailure = initialMessage;\n while (!stopped && restartCount < NAMED_RESTART_ATTEMPTS) {\n restartCount += 1;\n notice(\n `cloudflared stopped; restarting named tunnel (attempt ${String(restartCount)} of ${String(NAMED_RESTART_ATTEMPTS)})`,\n );\n await waitForRestart(restartCount);\n if (stopped) return;\n\n const outcome = await single(supervisedInput);\n if (stopped) {\n if (outcome.ok) {\n await outcome.stop().catch((error: unknown) => {\n notice(`Could not stop recovered tunnel: ${String(error)}`);\n });\n }\n return;\n }\n if (!outcome.ok) {\n lastFailure = outcome.message;\n continue;\n }\n activeStop = outcome.stop;\n lastReadyAt = Date.now();\n notice(`named tunnel recovered at ${outcome.publicOrigin}`);\n return;\n }\n\n if (!stopped) {\n options.onExit?.(\n `${initialMessage}\\nNamed tunnel recovery failed after ${String(NAMED_RESTART_ATTEMPTS)} attempts. Last failure: ${lastFailure}`,\n );\n }\n }\n\n function beginRecovery(message: string): void {\n recoveryPromise = recover(message)\n .catch((error: unknown) => {\n if (!stopped) {\n const cause = error instanceof Error ? error.message : String(error);\n options.onExit?.(`${message}\\nNamed tunnel recovery failed: ${cause}`);\n }\n })\n .finally(() => {\n recoveryPromise = undefined;\n const queued = pendingExit;\n pendingExit = undefined;\n if (queued !== undefined && !stopped) beginRecovery(queued);\n });\n }\n\n const initial = await single(supervisedInput);\n if (!initial.ok) {\n stopped = true;\n recoveryAbort.abort();\n return initial;\n }\n activeStop = initial.stop;\n lastReadyAt = Date.now();\n\n const stop = async (): Promise<void> => {\n if (stopPromise !== undefined) return await stopPromise;\n stopped = true;\n recoveryAbort.abort();\n const recovering = recoveryPromise;\n stopPromise = (async () => {\n await activeStop?.().catch((error: unknown) => {\n notice(`Could not stop tunnel: ${String(error)}`);\n });\n await recovering?.catch((error: unknown) => {\n notice(`Tunnel recovery cleanup failed: ${String(error)}`);\n });\n await fs.rm(path.join(options.stateDir, PID_FILE), { force: true });\n await fs.rm(path.join(options.stateDir, TOKEN_FILE), { force: true });\n })();\n return await stopPromise;\n };\n\n return { ok: true, publicOrigin: initial.publicOrigin, stop };\n };\n}\n\n/** Starts one cloudflared child; the exported launcher supervises successive named-tunnel children. */\nfunction createSingleTunnelLauncher(options: TunnelProcessOptions): TunnelLauncher {\n const notice = options.onNotice ?? ((): void => {});\n const spawnProcess = options.spawnProcess ?? spawn;\n const probe = options.probe ?? defaultProbe;\n const selfTestRetryMs = options.selfTestRetryMs ?? SELF_TEST_RETRY_MS;\n const startTimeoutMs = options.startTimeoutMs ?? START_TIMEOUT_MS;\n const pidPath = path.join(options.stateDir, PID_FILE);\n const runtimeTokenPath = path.join(options.stateDir, TOKEN_FILE);\n\n return async function launch(input: TunnelStartInput): Promise<TunnelStartResult> {\n if (input.signal?.aborted === true) {\n return { ok: false, failure: 'exited', message: 'Tunnel startup was cancelled.' };\n }\n const binary = options.cloudflaredPath ?? process.env[CLOUDFLARED_ENV] ?? (await findCloudflared());\n if (binary === undefined || binary === '') {\n return { ok: false, failure: 'not_installed', message: describeTunnelFailure('not_installed') };\n }\n\n let tokenPath: string | undefined;\n try {\n tokenPath = await writeTokenFile(input.config, options.stateDir);\n } catch (error) {\n const cause = error instanceof Error ? error.message : String(error);\n return { ok: false, failure: 'spawn_failed', message: `${describeTunnelFailure('spawn_failed')} ${cause}` };\n }\n const args = tunnelArgs(input.config, input.port, tokenPath);\n let child: ChildProcess;\n try {\n // Never detached and never unref'd. A detached child becomes a process\n // group leader that survives the terminal's SIGINT, which is exactly the\n // orphaned public tunnel this must avoid. Contrast serverSpawner.ts,\n // which detaches on purpose because sessions outlive the hub.\n child = spawnProcess(binary, args, { detached: false, stdio: ['ignore', 'pipe', 'pipe'] });\n } catch (error) {\n await fs.rm(runtimeTokenPath, { force: true });\n const cause = error instanceof Error ? error.message : String(error);\n return { ok: false, failure: 'spawn_failed', message: `${describeTunnelFailure('spawn_failed')} ${cause}` };\n }\n\n const lines: string[] = [];\n let stopped = false;\n let settle: ((result: TunnelStartResult) => void) | undefined;\n let selfTestStarted = false;\n const selfTestAbort = new AbortController();\n\n const killTree = (): void => {\n try {\n child.kill('SIGTERM');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') notice(`Could not stop tunnel: ${String(error)}`);\n }\n };\n const onProcessExit = (): void => {\n // sync: Node does not await filesystem cleanup in the process exit handler.\n // This is the net under process.exit(), an uncaught exception, and an\n // unhandled rejection, none of which reach the graceful close path.\n rmSync(runtimeTokenPath, { force: true });\n try {\n if (child.pid !== undefined) process.kill(child.pid, 'SIGKILL');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH')\n notice(`Could not kill tunnel at exit: ${String(error)}`);\n }\n };\n process.once('exit', onProcessExit);\n\n const stop = async (): Promise<void> => {\n if (stopped) return;\n stopped = true;\n if (child.exitCode !== null || child.signalCode !== null) {\n process.off('exit', onProcessExit);\n await pidWrite;\n await fs.rm(pidPath, { force: true });\n await fs.rm(runtimeTokenPath, { force: true });\n return;\n }\n await new Promise<void>((resolve) => {\n const escalate = setTimeout(() => {\n try {\n child.kill('SIGKILL');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') notice(`Could not kill tunnel: ${String(error)}`);\n }\n }, TERMINATE_GRACE_MS);\n child.once('exit', () => {\n clearTimeout(escalate);\n resolve();\n });\n killTree();\n });\n process.off('exit', onProcessExit);\n await pidWrite;\n await fs.rm(pidPath, { force: true });\n await fs.rm(runtimeTokenPath, { force: true });\n };\n\n // Register child listeners below without yielding, so early exits cannot be missed.\n // Cleanup waits for this ordered write before removing the record.\n const pidWrite = fs\n .mkdir(options.stateDir, { recursive: true, mode: 0o700 })\n .then(() =>\n fs.writeFile(\n pidPath,\n JSON.stringify({ pid: child.pid, ownerPid: process.pid, startedAt: Date.now(), command: binary }),\n { mode: FILE_MODE },\n ),\n )\n .catch((error: unknown) => {\n // The reaper is a safety net; report unavailable recovery without blocking startup.\n notice(`Could not write tunnel process record: ${String(error)}`);\n });\n\n const configuredOrigin = input.config.kind === 'named' ? `https://${input.config.hostname}` : undefined;\n let seenUrl = configuredOrigin;\n let seenConnection = false;\n\n const waitToRetry = async (): Promise<void> => {\n if (selfTestRetryMs <= 0) return;\n await new Promise<void>((resolve) => {\n const done = (): void => {\n clearTimeout(timer);\n selfTestAbort.signal.removeEventListener('abort', done);\n resolve();\n };\n const timer = setTimeout(done, selfTestRetryMs);\n selfTestAbort.signal.addEventListener('abort', done, { once: true });\n });\n };\n\n /** Proves end to end that pairing is reachable and that everything else is not. */\n const runSelfTest = async (origin: string): Promise<TunnelStartResult> => {\n let pairResponse: ProbeResult | undefined;\n let healthResponse: ProbeResult | undefined;\n let cause = 'fetch failed';\n for (let attempt = 0; attempt < SELF_TEST_ATTEMPTS && !selfTestAbort.signal.aborted; attempt += 1) {\n try {\n pairResponse = await probe(`${origin}${PAIRING_PAGE_ROUTE}`, selfTestAbort.signal);\n healthResponse = await probe(`${origin}/api/health`, selfTestAbort.signal);\n if (pairResponse.status !== EDGE_TUNNEL_UNAVAILABLE && healthResponse.status !== EDGE_TUNNEL_UNAVAILABLE)\n break;\n cause = `Cloudflare edge answered ${String(healthResponse.status)} before the connector registered`;\n } catch (error) {\n cause = error instanceof Error ? error.message : String(error);\n }\n if (attempt + 1 < SELF_TEST_ATTEMPTS && !selfTestAbort.signal.aborted) await waitToRetry();\n }\n if (pairResponse === undefined || healthResponse === undefined) {\n return { ok: false, failure: 'self_test_failed', message: `The tunnel did not answer: ${cause}` };\n }\n // Still 530 after every retry: Cloudflare has no connector for this hostname, so nothing was exposed. Usually a\n // named tunnel whose name or config file is missing, which makes cloudflared run its default tunnel instead.\n if (healthResponse.status === EDGE_TUNNEL_UNAVAILABLE || pairResponse.status === EDGE_TUNNEL_UNAVAILABLE) {\n const message = `Cloudflare has no connector for ${origin} (530). Check the tunnel name or config file.`;\n notice(message);\n return { ok: false, failure: 'self_test_failed', message };\n }\n if (healthResponse.status !== UNAUTHORIZED) {\n // The agent would be on the public internet unauthenticated. This is\n // the one failure worth an automatic abort rather than a warning.\n const message = `${describeTunnelFailure('self_test_failed')} /api/health answered ${String(healthResponse.status)} through the tunnel.`;\n notice(message);\n return { ok: false, failure: 'self_test_failed', message };\n }\n if (pairResponse.status !== OK || !pairResponse.body.includes(PAIRING_PAGE_MARKER)) {\n const message = `The pairing page answered ${String(pairResponse.status)} through the tunnel.`;\n notice(message);\n return { ok: false, failure: 'self_test_failed', message };\n }\n notice(`tunnel ready at ${origin}`);\n return { ok: true, publicOrigin: origin, stop };\n };\n\n const consider = (chunk: string): void => {\n lines.push(chunk);\n if (settle === undefined || selfTestStarted) return;\n seenUrl ??= extractTunnelUrl(chunk);\n seenConnection ||= mentionsRegisteredConnection(chunk);\n if (seenUrl === undefined || !seenConnection) return;\n selfTestStarted = true;\n input.acceptOrigin?.(seenUrl);\n void runSelfTest(seenUrl).then((result) => settle?.(result));\n };\n\n child.stdout?.on('data', (data: Buffer) => consider(data.toString()));\n child.stderr?.on('data', (data: Buffer) => consider(data.toString()));\n\n return await new Promise<TunnelStartResult>((resolve) => {\n let deadline: ReturnType<typeof setTimeout>;\n const finish = (result: TunnelStartResult, stopProcess = !result.ok): void => {\n if (settle === undefined) return;\n settle = undefined;\n clearTimeout(deadline);\n input.signal?.removeEventListener('abort', cancel);\n selfTestAbort.abort();\n if (stopProcess) {\n void stop().then(() => resolve(result));\n } else {\n resolve(result);\n }\n };\n const cancel = (): void => {\n finish({ ok: false, failure: 'exited', message: 'Tunnel startup was cancelled.' });\n };\n settle = (result) => finish(result);\n deadline = setTimeout(() => {\n finish({\n ok: false,\n failure: 'timeout',\n message: `${describeTunnelFailure('timeout')}\\n${tailOf(lines)}`,\n });\n }, startTimeoutMs);\n input.signal?.addEventListener('abort', cancel, { once: true });\n\n child.once('error', (error) => {\n finish({\n ok: false,\n failure: 'spawn_failed',\n message: `${describeTunnelFailure('spawn_failed')} ${error.message}`,\n });\n });\n\n child.once('exit', async (code) => {\n process.off('exit', onProcessExit);\n await pidWrite;\n await fs.rm(runtimeTokenPath, { force: true }).catch((error: unknown) => {\n notice(`Tunnel token cleanup failed: ${error instanceof Error ? error.message : String(error)}`);\n });\n const message = `${describeTunnelFailure('exited')} (code ${String(code)})\\n${tailOf(lines)}`;\n if (settle !== undefined) {\n finish({ ok: false, failure: 'exited', message }, false);\n return;\n }\n // It came up and then died: network loss, an edge rejection, or a\n // self-update. The supervisor either replaces a named connector or tells\n // the host to fail closed rather than leave an unreachable cockpit enabled.\n if (!stopped) options.onExit?.(message);\n });\n\n // A named tunnel already knows its hostname, but it still waits for\n // cloudflared to register an edge connection before probing the public URL.\n if (input.signal?.aborted === true) cancel();\n });\n };\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\n\nimport type { PoClientMetadata } from '@agimon-ai/po-core/clientMetadata';\nimport { poClientMetadataFrom } from '@agimon-ai/po-core/clientMetadata';\nimport type { CallerAccess } from '@agimon-ai/po-core/headlessServer';\nimport {\n PO_API_CALLER_ACCESS_HEADER,\n PO_API_CALLER_DEVICE_ID_HEADER,\n PO_API_CALLER_HEADERS,\n PO_API_CALLER_FEDERATION_HEADER,\n type PoFederationCaller,\n PO_API_CALLER_LOCALITY_HEADER,\n PO_API_CALLER_STEP_UP_HEADER,\n PO_API_PEER_ADDRESS_HEADER,\n parsePoSocketPath,\n} from '@agimon-ai/po-core/packageApi';\nimport {\n COMPLETION_SPAN_MIN_BYTES,\n COMPLETION_SPAN_MIN_DURATION_MS,\n contentClass,\n} from '@agimon-ai/po-core/packageApiServer';\nimport { createTextLink, type ProtocolLink } from '@agimon-ai/po-core/protocolTransport';\nimport {\n DEVICE_COOKIE,\n REMOTE_API_ROUTE,\n REMOTE_CHANNEL_ROUTE,\n REMOTE_HTTP_ROUTE,\n STEP_UP_HEADER,\n} from '@agimon-ai/po-core/remoteContract';\nimport { ownDeviceRemoteRoute } from '@agimon-ai/po-core/remoteContract';\nimport { type TunnelLauncher } from '@agimon-ai/po-core/remoteContract';\nimport { observe, type ServerTelemetry } from '@agimon-ai/po-core/serverTelemetry';\nimport {\n isPublicSessionMcpRoute,\n isSessionMcpHostRoute,\n isSessionMcpPhoneRoute,\n} from '@agimon-ai/po-core/sessionMcpContract';\nimport type { HubFederationPlatform } from '@agimon-ai/po-federation';\nimport { Hono } from 'hono';\nimport { getCookie } from 'hono/cookie';\nimport { WebSocketServer, type RawData } from 'ws';\n\nimport { isDevProxyPath, parseProxyPath } from '../devProxyPolicy';\nimport { registerDevProxyRoutes } from '../devProxyRoutes';\nimport { relayDevProxySocket } from '../devProxySocket';\nimport { createDevProxyStore } from '../devProxyStore';\nimport { createDefaultHubFederation } from '../hubFederation';\nimport { createPublicFileShares, PUBLIC_FILE_SHARE_PREFIX, type PublicFileShares } from '../publicFileShares';\nimport { createRemoteAccess, type RemoteAccess } from '../remoteAccess';\nimport { createRemoteAccessStore, defaultRemoteStateDir } from '../remoteAccessStore';\nimport { isPublicPairingRoute, originVerdict, type GuardListener, localOriginPolicy } from '../remoteGuardPolicy';\nimport { registerRemoteRoutes } from '../remoteRoutes';\nimport { createTunnelLauncher, reapStaleTunnel } from '../tunnelProcess';\nimport { isQuickTunnelHost, stepUpActionFor } from '../webauthnPolicy';\n\nconst MAX_REQUEST_BYTES = 8 * 1024 * 1024;\nconst PROTOCOL_ADMISSION_TIMEOUT_MS = 10_000;\nconst MAX_PROTOCOL_FIRST_FRAME_BYTES = 8 * 1024;\nconst TUNNEL_HEADERS_TIMEOUT_MS = 5_000;\nconst TUNNEL_REQUEST_TIMEOUT_MS = 10_000;\nconst TUNNEL_CONNECTION_LIMIT = 64;\nconst TUNNEL_REQUESTS_PER_SOCKET = 100;\nconst SEALED_HTTP_VERSION = 1;\nconst SEALED_HTTP_METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']);\n/** HMAC-authenticated peer routes are the only non-device tunnel APIs. */\nconst SESSION_PEER_ROUTES = new Set(['/api/plugins/session-peer/inbox', '/api/plugins/session-peer/control']);\nconst VOICE_PEER_ROUTES = new Set(['/api/plugins/voice/peer', '/api/plugins/voice/peer-ownership']);\n/** The one public file share shape: a 256-bit base64url token and nothing after it. */\nconst PUBLIC_FILE_SHARE_ROUTE = /^\\/mcp-file\\/([A-Za-z0-9_-]{43})$/u;\n/** Everything under this name is reserved for shares, so a near miss never reaches another route. */\nconst PUBLIC_FILE_SHARE_NAMESPACE = PUBLIC_FILE_SHARE_PREFIX.slice(0, -1);\n\n/** The local cockpit's proxy to other hubs, matched decoded and case-blind so no spelling slips through. */\nfunction isHostProxyPath(path: string): boolean {\n let decoded: string;\n try {\n decoded = decodeURIComponent(path).toLowerCase();\n } catch {\n return true; // A path that does not decode is refused rather than guessed at.\n }\n return decoded === '/hosts' || decoded.startsWith('/hosts/');\n}\nconst FORBIDDEN_HEADERS = new Set([\n 'authorization',\n 'connection',\n 'content-length',\n 'cookie',\n 'forwarded',\n 'host',\n 'origin',\n 'transfer-encoding',\n 'upgrade',\n 'x-po-token',\n 'x-po-desktop',\n ...PO_API_CALLER_HEADERS,\n 'x-forwarded-for',\n 'x-forwarded-host',\n 'x-forwarded-proto',\n]);\n\ninterface SealedHttpRequest {\n v: number;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\nfunction sealedRequest(value: unknown): SealedHttpRequest | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const request = value as Partial<SealedHttpRequest>;\n if (\n request.v !== SEALED_HTTP_VERSION ||\n typeof request.method !== 'string' ||\n !SEALED_HTTP_METHODS.has(request.method) ||\n typeof request.target !== 'string' ||\n !request.target.startsWith('/') ||\n request.target.startsWith('//') ||\n request.target.includes('#') ||\n !Array.isArray(request.headers) ||\n !request.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) ||\n (request.body !== undefined && typeof request.body !== 'string')\n )\n return undefined;\n const parsed = new URL(request.target, 'http://po.local');\n if (parsed.pathname === REMOTE_HTTP_ROUTE || parsed.pathname === REMOTE_CHANNEL_ROUTE) return undefined;\n return request as SealedHttpRequest;\n}\n\nfunction decodedBody(value: string | undefined): Buffer | undefined {\n if (value === undefined) return Buffer.alloc(0);\n if (!/^(?:[A-Za-z\\d+/]{4})*(?:[A-Za-z\\d+/]{2}==|[A-Za-z\\d+/]{3}=)?$/u.test(value)) return undefined;\n const body = Buffer.from(value, 'base64');\n return body.toString('base64') === value ? body : undefined;\n}\n\ninterface ListenerBindings {\n listener: GuardListener;\n incoming?: IncomingMessage;\n sealedDeviceId?: string;\n /** Whether the sealed gateway verified a step-up for this re-dispatched request. */\n sealedStepUp?: 'verified' | 'not-required';\n}\n\n/** Only public exposure intent is durable. Credentials and pairing state never belong here. */\nexport interface TunnelIntent {\n hostname: string;\n closesAt?: number;\n}\n\nexport interface RemoteRuntimeOptions {\n homeDirectory: string;\n registrationToken: string;\n bundleTrust(): { publicKey: string; revision: number } | undefined;\n /** Signs `po/host-channel-key/v1` fields with the shell signer, for native device reconnects. */\n attestHost?: (fields: readonly string[]) => string | undefined;\n onNotice(message: string): void;\n /** The cohosted issuer resolves a one-use identity proof, never an account signing key. */\n pairingAccount?: import('../remoteRoutes').RemoteRoutesOptions['pairingAccount'];\n /** Auth-owned public routes only, when this issuer is the tunnel origin. Never uses the host-token forwarder. */\n publicAuth?: { issuer(): string | undefined; fetch(request: Request): Promise<Response> };\n /** The listener to which a sealed, authenticated request is forwarded. */\n forward(request: Request): Promise<Response>;\n /** Destination verifier, composed with the hub's local pins and current issuer feed. */\n federation?: {\n verify(request: Request): Promise<PoFederationCaller | undefined>;\n /** What a paired device is on this host. Absent stamps nothing, as on a personal host. */\n callerAccess?(deviceId: string, verified?: PoFederationCaller): CallerAccess;\n /** The team this host admits right now. */\n team?(): import('@agimon-ai/po-core/headlessServer').HostTeam | 'loading' | undefined;\n federationHost?: () => { hostId: string; hostPublicKey: string; enrollmentGeneration?: number } | undefined;\n enrollAccount?: import('../remoteRoutes').RemoteRoutesOptions['enrollAccount'];\n claimAccount?: import('../remoteRoutes').RemoteRoutesOptions['claimAccount'];\n unlinkAccount?: import('../remoteRoutes').RemoteRoutesOptions['unlinkAccount'];\n bindAccountDevice?: import('../remoteRoutes').RemoteRoutesOptions['bindAccountDevice'];\n };\n federationPlatform?: HubFederationPlatform;\n /** Hands a paired device's relayed Chord link to the protocol host, as an upgrade at `pathname` would. */\n acceptProtocol(\n pathname: string,\n link: ProtocolLink,\n deviceId: string,\n client?: PoClientMetadata,\n /** Set on a team host: who the device's person is there. Absent on a personal host. */\n access?: Exclude<CallerAccess, 'refused' | undefined>,\n ): boolean;\n onDeviceDropped?: (deviceId: string) => void;\n onStateChanged?: () => void;\n onTunnelIntentChanged?: (intent: TunnelIntent | undefined) => void;\n launchTunnel?: TunnelLauncher;\n /** Ports the host itself listens on, which a dev proxy target may never name. */\n reservedPorts?: () => readonly (number | undefined)[];\n /** Records slow, large or failing sealed HTTP exchanges, to attribute heap and event-loop cost. */\n telemetry?: ServerTelemetry;\n /** Keeps a line in the host's audit log when the gateway itself refuses a device its team cannot name. */\n audit?: (entry: import('@agimon-ai/po-core/serverPlugin').PoAuditEntry) => void;\n}\n\nexport interface RemoteRuntime {\n readonly federationClient?: import('@agimon-ai/po-core').PoFederationClient;\n /** The team this host admits right now: undefined on a personal host, `loading` until it has been read once. */\n team(): import('@agimon-ai/po-core/headlessServer').HostTeam | 'loading' | undefined;\n /** What a paired device is on this host: undefined on a personal host, `refused` when a team host cannot name it. */\n callerAccess(deviceId: string): CallerAccess;\n readonly remote: RemoteAccess;\n /** Short-lived public links served by the tunnel listener itself, never forwarded to the hub. */\n readonly fileShares: PublicFileShares;\n fetchLocal(request: Request): Promise<Response>;\n requestNetwork?(request: Request): Promise<Response | undefined>;\n networkComposition?(): Promise<{\n network?: { hostId: string; networkId: string; enrollmentGeneration?: number; team?: string };\n }>;\n workspaceProviders?(workspaceId: string): Promise<{ providers?: import('@agimon-ai/po-core').FederationProvider[] }>;\n startNetwork?(): Promise<void>;\n networkPeer?(): Promise<unknown>;\n hostRequests?(): Promise<Omit<import('@agimon-ai/po-core/modelGateway').HostRequests, 'machineName'> | undefined>;\n /** One signed call to the account's cloud host, such as the shared vault; `undefined` when not enrolled. */\n accountCall?(operation: string, input: unknown): Promise<unknown>;\n acceptNetworkRelay?(socket: import('@agimon-ai/po-core/packageApi').PoApiSocket, url: URL): Promise<void>;\n /** Automatically restores only a valid, unchanged named hostname and unexpired deadline. */\n restoreTunnel(intent: TunnelIntent): Promise<{ ok: true } | { ok: false; error: string }>;\n tunnelIntent(): TunnelIntent | undefined;\n close(): Promise<void>;\n}\n\nasync function readBody(request: IncomingMessage): Promise<Buffer> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n size += bytes.byteLength;\n if (size > MAX_REQUEST_BYTES) throw new Error('The tunnel request body is too large.');\n chunks.push(bytes);\n }\n return Buffer.concat(chunks);\n}\n\nasync function writeResponse(response: ServerResponse, result: Response): Promise<void> {\n response.writeHead(result.status, Object.fromEntries(result.headers.entries()));\n if (result.body === null) {\n response.end();\n return;\n }\n await pipeline(Readable.fromWeb(result.body as import('node:stream/web').ReadableStream), response);\n}\n\n/** One global control plane and a second socket dedicated to public tunnel traffic. */\nexport function createRemoteRuntime(options: RemoteRuntimeOptions): RemoteRuntime {\n const store = createRemoteAccessStore({\n stateDir: defaultRemoteStateDir(options.homeDirectory),\n onNotice: (message) => options.onNotice(message),\n });\n const defaultFederation =\n options.federationPlatform && store.hubTrust\n ? createDefaultHubFederation({\n ...options.federationPlatform,\n store: store.hubTrust,\n databaseFile: `${store.directory}/federation.sqlite`,\n now: Date.now,\n })\n : undefined;\n const federation = options.federation ?? defaultFederation;\n // A phone that signs back in with its device key holds a new session. The account it enrolled with is pinned\n // to the trusted device behind that session, so that is who gets named.\n const callerAccess = (deviceId: string, verified?: PoFederationCaller): CallerAccess => {\n const account = remote.accountOf(deviceId);\n if (!account) return federation?.callerAccess?.(remote.trustedDeviceOf(deviceId) ?? deviceId, verified);\n const team = federation?.team?.();\n if (\n !team ||\n team === 'loading' ||\n team.issuer !== account.issuer ||\n team.org !== account.org ||\n team.role(account.subject) === undefined\n )\n return 'refused';\n return {\n // Even the owner's account stays a member here. Only the existing owner QR pin grants host authority.\n access: 'member',\n caller: {\n principal: { issuer: account.issuer, subject: account.subject },\n org: account.org,\n // Pairing provenance, not an account-device signing key. Never used for account enrollment or network grants.\n device: { keyId: `pairing:${deviceId}` },\n },\n };\n };\n /** True on a personal host, and on a team host for the owner's own device. */\n const ownerDevice = (deviceId: string): boolean => {\n const access = callerAccess(deviceId);\n return access === undefined || (access !== 'refused' && access.access === 'owner');\n };\n reapStaleTunnel(store.directory, (message) => options.onNotice(message));\n const devProxy = createDevProxyStore({ stateDir: store.directory, onNotice: (message) => options.onNotice(message) });\n const app = new Hono<{ Bindings: ListenerBindings }>();\n let remote: RemoteAccess;\n let closing = false;\n let lastIntent: TunnelIntent | undefined;\n let frontendOrigin: string | undefined;\n const tunnelIntent = (): TunnelIntent | undefined => {\n const state = remote.state();\n const tunnel = remote.settings().tunnel;\n if (state.status !== 'on' || tunnel.kind !== 'named' || state.publicUrl === undefined) return undefined;\n if (new URL(state.publicUrl).hostname !== tunnel.hostname) return undefined;\n return {\n hostname: tunnel.hostname,\n ...(state.closesAt === undefined ? {} : { closesAt: Date.parse(state.closesAt) }),\n };\n };\n const publishIntent = (): void => {\n if (closing) return;\n const intent = tunnelIntent();\n if (intent?.hostname === lastIntent?.hostname && intent?.closesAt === lastIntent?.closesAt) return;\n lastIntent = intent;\n options.onTunnelIntentChanged?.(intent);\n };\n const fileShares = createPublicFileShares({\n publicOrigin: () => remote.publicOrigin(),\n publicOriginRevision: () => remote.publicOriginRevision(),\n onNotice: (message) => options.onNotice(message),\n });\n /** Exact share route on the decoded path, and the raw path must not have needed decoding. */\n const publicFileShareToken = (request: Request, path: string): string | undefined =>\n new URL(request.url).pathname === path ? PUBLIC_FILE_SHARE_ROUTE.exec(path)?.[1] : undefined;\n const inFileShareNamespace = (request: Request, path: string): boolean =>\n path.startsWith(PUBLIC_FILE_SHARE_NAMESPACE) ||\n new URL(request.url).pathname.startsWith(PUBLIC_FILE_SHARE_NAMESPACE);\n app.use('*', async (context, next) => {\n // Match the incoming spelling, not a decoded or URL-normalized path.\n const rawPath = context.env.incoming?.url?.split('?')[0];\n const publicGatewayPeer =\n context.env.listener === 'tunnel' &&\n context.req.header('x-po-host-proof') !== undefined &&\n ((context.req.method === 'GET' && rawPath === '/api/plugins/gateway/catalog') ||\n (context.req.method === 'POST' && rawPath === '/api/plugins/gateway/calls'));\n const computerNetwork =\n context.req.path.startsWith('/api/network/') || /^\\/api\\/networks\\/[^/]+\\/network\\//u.test(context.req.path);\n if (computerNetwork) {\n const result = await defaultFederation?.requestNetwork(context.req.raw);\n if (result) return result;\n }\n if (\n !publicGatewayPeer &&\n context.req.header('x-po-federation-envelope') &&\n context.req.path.includes('/plugins/')\n ) {\n const request = context.req.raw;\n if (!(await options.federationPlatform?.resolve(request.clone())))\n return context.json({ status: 'unavailable', reason: 'package-not-mounted' }, 503);\n const caller = await federation?.verify(request.clone());\n if (!caller) return context.json({ error: 'The destination request proof was refused.' }, 401);\n const headers = new Headers(request.headers);\n for (const name of PO_API_CALLER_HEADERS) headers.delete(name);\n headers.delete('x-po-identity-token');\n headers.delete('x-po-federation-envelope');\n headers.delete('x-po-federation-grant');\n headers.set(PO_API_CALLER_FEDERATION_HEADER, JSON.stringify(caller));\n return options.forward(new Request(request, { headers }));\n }\n if (context.env.listener === 'local') return next();\n const path = context.req.path;\n const publicSessionMcp = isPublicSessionMcpRoute(context.req.method, path);\n const publicSessionPeer = context.req.method === 'POST' && SESSION_PEER_ROUTES.has(path);\n const publicVoicePeer = context.req.method === 'POST' && VOICE_PEER_ROUTES.has(path);\n const publicFileShare =\n (context.req.method === 'GET' || context.req.method === 'HEAD') &&\n publicFileShareToken(context.req.raw, path) !== undefined;\n const issuerApi = !computerNetwork && /^\\/api\\/(?:auth|networks|account)\\//u.test(path);\n // The auth package owns native-app CSRF checks. This exception never reaches computer routes.\n const nativeAuth = rawPath === path && issuerApi && context.req.header('origin') === 'po://';\n const verdict = originVerdict({\n listener: 'tunnel',\n // Exact OAuth, MCP, and HMAC-authenticated peer routes authenticate at the\n // application layer. Treat an absent Origin like a server-to-server read.\n method:\n nativeAuth || publicSessionMcp || publicSessionPeer || publicVoicePeer || publicGatewayPeer\n ? 'GET'\n : context.req.method,\n isUpgrade: false,\n origin: nativeAuth ? undefined : context.req.header('origin'),\n host: context.req.header('host'),\n local: localOriginPolicy(0),\n tunnel: remote.tunnelPolicy(),\n });\n if (verdict !== 'allow') return context.json({ error: `Tunnel request refused: ${verdict}.` }, 403);\n if (issuerApi) {\n const origin = remote.publicOrigin();\n const issuer = options.publicAuth?.issuer();\n const from = new URL(context.req.url);\n if (!origin || issuer?.replace(/\\/$/u, '') !== origin || rawPath !== from.pathname || path !== from.pathname)\n return context.json({ error: 'No same-origin sign-in server is available.' }, 404);\n const headers = new Headers(context.req.raw.headers);\n for (const name of [\n ...PO_API_CALLER_HEADERS,\n 'x-po-token',\n 'x-po-desktop',\n 'x-po-web-registration',\n 'x-po-identity-token',\n 'x-po-federation-envelope',\n 'x-po-federation-grant',\n 'x-po-host-proof',\n ])\n headers.delete(name);\n headers.set(PO_API_PEER_ADDRESS_HEADER, context.env.incoming?.socket.remoteAddress ?? '');\n return options.publicAuth!.fetch(\n new Request(new URL(`${from.pathname}${from.search}`, origin), new Request(context.req.raw, { headers })),\n );\n }\n if (publicGatewayPeer) {\n const headers = new Headers(context.req.raw.headers);\n for (const name of PO_API_CALLER_HEADERS) headers.delete(name);\n headers.delete('x-po-identity-token');\n headers.delete('x-po-federation-envelope');\n headers.delete('x-po-federation-grant');\n // The destination verifies the host proof. No local caller authority is assigned here.\n return options.forward(new Request(context.req.raw, { headers }));\n }\n // The token is the credential, so a share needs no device. Near misses never fall through.\n if (publicFileShare) return next();\n if (inFileShareNamespace(context.req.raw, path)) return context.json({ error: 'Not found.' }, 404);\n if (isPublicPairingRoute(context.req.method, path) || publicSessionMcp || publicSessionPeer || publicVoicePeer)\n return next();\n const device = remote.authorize(getCookie(context, DEVICE_COOKIE, 'host'));\n if (device === undefined) return context.json({ error: 'This device is not paired.' }, 401);\n if (context.env.sealedDeviceId === device) return next();\n // A proxied dev site issues its own subresource requests and form posts, none of which can go\n // through a gateway that seals whole JSON responses. The same predicate the proxy route uses\n // refuses dot segments, so a path granted here cannot resolve into /api/.\n // A dev site is the owner's own work in progress, not the team's.\n if (isDevProxyPath(path))\n return ownerDevice(device)\n ? next()\n : context.json({ error: 'Only the owner of this computer can do that.' }, 403);\n if (context.req.method === 'POST' && (path === REMOTE_CHANNEL_ROUTE || path === REMOTE_HTTP_ROUTE)) return next();\n if ((context.req.method === 'GET' || context.req.method === 'HEAD') && !path.startsWith('/api/')) return next();\n return context.json({ error: 'Remote HTTP requests must use the sealed gateway.' }, 401);\n });\n\n remote = createRemoteAccess({\n store,\n broadcastLocal: () => options.onStateChanged?.(),\n broadcastAll: () => {\n options.onStateChanged?.();\n publishIntent();\n },\n onDeviceDropped: options.onDeviceDropped,\n launchTunnel:\n options.launchTunnel ??\n createTunnelLauncher({\n stateDir: store.directory,\n onNotice: (message) => options.onNotice(message),\n onExit: (message) => {\n options.onNotice(`remote access: ${message}`);\n void remote.disable();\n },\n }),\n bindListener: async () => {\n const webSockets = new WebSocketServer({ noServer: true, maxPayload: MAX_REQUEST_BYTES });\n const server = createServer((incoming, outgoing) => {\n void (async () => {\n const abort = new AbortController();\n const disconnected = (): void => abort.abort();\n incoming.once('aborted', disconnected);\n outgoing.once('close', disconnected);\n try {\n const url = new URL(incoming.url ?? '/', `http://${incoming.headers.host ?? 'localhost'}`);\n const headers = new Headers();\n for (const [name, value] of Object.entries(incoming.headers))\n if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(', ') : value);\n const body = incoming.method === 'GET' || incoming.method === 'HEAD' ? undefined : await readBody(incoming);\n const request = new Request(url, {\n method: incoming.method,\n headers,\n signal: abort.signal,\n ...(body === undefined ? {} : { body }),\n });\n await writeResponse(outgoing, await app.fetch(request, { listener: 'tunnel', incoming }));\n } finally {\n incoming.off('aborted', disconnected);\n outgoing.off('close', disconnected);\n }\n })().catch((error: unknown) => {\n options.onNotice(`tunnel request failed: ${String(error)}`);\n if (!outgoing.headersSent) {\n outgoing.writeHead(500, { 'content-type': 'application/json' });\n outgoing.end(JSON.stringify({ error: 'The tunnel request failed.' }));\n } else outgoing.destroy();\n });\n });\n server.on('upgrade', (incoming, socket, head) => {\n const url = new URL(incoming.url ?? '/', `http://${incoming.headers.host ?? 'localhost'}`);\n if (/^\\/api\\/networks\\/[^/]+\\/relay$/.test(url.pathname)) {\n webSockets.handleUpgrade(incoming, socket, head, (client) => {\n const peer: import('@agimon-ai/po-core/packageApi').PoApiSocket = {\n get isOpen() {\n return client.readyState === client.OPEN;\n },\n send: (data) => client.send(data),\n close: () => client.close(),\n onMessage: (listener) => {\n client.on('message', (data) => {\n const bytes = Array.isArray(data)\n ? Buffer.concat(data)\n : Buffer.isBuffer(data)\n ? data\n : Buffer.from(data);\n listener(bytes.toString('utf8'));\n });\n },\n onClose: (listener) => {\n client.on('close', (code, reason) => listener(code, reason.toString('utf8')));\n },\n };\n client.on('error', () => client.close());\n if (!defaultFederation) {\n client.close();\n return;\n }\n void defaultFederation.acceptNetworkRelay(peer, url).catch((error: unknown) => {\n options.onNotice(`network relay failed: ${String(error)}`);\n client.close();\n });\n });\n return;\n }\n const verdict = originVerdict({\n listener: 'tunnel',\n method: incoming.method ?? 'GET',\n isUpgrade: true,\n origin: incoming.headers.origin,\n host: incoming.headers.host,\n local: localOriginPolicy(0),\n tunnel: remote.tunnelPolicy(),\n });\n const cookies = new Map(\n (incoming.headers.cookie ?? '').split(';').map((part) => {\n const at = part.indexOf('=');\n return [part.slice(0, at).trim(), part.slice(at + 1).trim()];\n }),\n );\n const device = remote.authorize(cookies.get(`__Host-${DEVICE_COOKIE}`));\n // Hot module reload: a paired device's dev-site socket goes to the registered target.\n if (isDevProxyPath(url.pathname) && verdict === 'allow' && device !== undefined) {\n const parsed = parseProxyPath(url.pathname);\n const target = parsed.kind === 'match' && ownerDevice(device) ? devProxy.find(parsed.name) : undefined;\n if (parsed.kind !== 'match' || target === undefined) {\n socket.write('HTTP/1.1 404 Not Found\\r\\n\\r\\n');\n socket.destroy();\n return;\n }\n webSockets.handleUpgrade(incoming, socket, head, (client) => {\n const untrack = remote.trackSocket(device, (code, reason) => client.close(code, reason));\n client.once('close', untrack);\n relayDevProxySocket(client, {\n port: target.port,\n upstreamPath: `${parsed.upstreamPath}${url.search}`,\n protocols: incoming.headers['sec-websocket-protocol'],\n onNotice: (message) => options.onNotice(message),\n });\n });\n return;\n }\n const channel = device === undefined ? undefined : remote.channelFor(device, 'protocol');\n // A team host admits no device it cannot name as a teammate.\n const access = device === undefined ? undefined : callerAccess(device);\n if (!parsePoSocketPath(url.pathname) || verdict !== 'allow' || !device || !channel || access === 'refused') {\n socket.write('HTTP/1.1 403 Forbidden\\r\\n\\r\\n');\n socket.destroy();\n return;\n }\n webSockets.handleUpgrade(incoming, socket, head, (client) => {\n const untrack = remote.trackSocket(device, (code, reason) => client.close(code, reason));\n let admitted = false;\n let admissionTimer: ReturnType<typeof setTimeout> | undefined;\n const relay = createTextLink(\n {\n send: (text) => {\n const sealed = channel.seal(Buffer.from(text));\n if (!sealed.ok) {\n relay.ended('seal failed');\n return;\n }\n client.send(Buffer.from(JSON.stringify(sealed.envelope)));\n },\n close: () => {\n clearTimeout(admissionTimer);\n client.removeListener('message', onMessage);\n untrack();\n client.close();\n },\n },\n { waitForPeer: true },\n );\n const onMessage = (raw: RawData) => {\n if (!remote.isDeviceAuthorized(device)) {\n relay.ended('device revoked');\n return;\n }\n const size = Array.isArray(raw) ? raw.reduce((sum, part) => sum + part.byteLength, 0) : raw.byteLength;\n if (!admitted && size > MAX_PROTOCOL_FIRST_FRAME_BYTES) {\n relay.ended('protocol admission frame too large');\n return;\n }\n const bytes = Array.isArray(raw) ? Buffer.concat(raw) : Buffer.from(raw as Buffer);\n let envelope: unknown;\n try {\n envelope = JSON.parse(bytes.toString('utf8')) as unknown;\n } catch {\n relay.ended('invalid envelope');\n return;\n }\n const opened = channel.open(envelope);\n if (!opened.ok) {\n relay.ended('invalid envelope');\n return;\n }\n const text = Buffer.from(opened.plaintext).toString('utf8');\n if (!admitted) {\n let first: unknown;\n try {\n first = JSON.parse(text) as unknown;\n } catch {\n relay.ended('invalid protocol admission frame');\n return;\n }\n const metadata = poClientMetadataFrom({ preface: first });\n if (metadata.status === 'invalid' || metadata.status === 'unsupported') {\n relay.ended('invalid protocol metadata');\n return;\n }\n admitted = true;\n clearTimeout(admissionTimer);\n try {\n if (\n !options.acceptProtocol(\n url.pathname,\n relay.link,\n device,\n metadata.status === 'ok' ? metadata.metadata : undefined,\n access,\n )\n ) {\n relay.ended('protocol unavailable');\n return;\n }\n } catch {\n options.onNotice('remote protocol could not connect');\n relay.ended('protocol unavailable');\n return;\n }\n if (metadata.status === 'ok') return;\n }\n relay.deliver(text);\n };\n admissionTimer = setTimeout(() => relay.ended('protocol admission timed out'), PROTOCOL_ADMISSION_TIMEOUT_MS);\n client.on('message', onMessage);\n client.once('close', () => relay.ended('client closed'));\n client.once('error', () => relay.ended('client error'));\n });\n });\n server.headersTimeout = TUNNEL_HEADERS_TIMEOUT_MS;\n server.requestTimeout = TUNNEL_REQUEST_TIMEOUT_MS;\n server.maxConnections = TUNNEL_CONNECTION_LIMIT;\n server.maxRequestsPerSocket = TUNNEL_REQUESTS_PER_SOCKET;\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', resolve);\n });\n const address = server.address();\n if (!address || typeof address === 'string') throw new Error('The tunnel listener has no TCP address.');\n return {\n port: address.port,\n close: async () => {\n for (const client of webSockets.clients) client.terminate();\n webSockets.close();\n server.closeAllConnections();\n await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));\n },\n };\n },\n bundleTrust: () => options.bundleTrust(),\n attestHost: (fields) => options.attestHost?.(fields),\n onNotice: (message) => options.onNotice(message),\n });\n registerRemoteRoutes(app as unknown as Hono, {\n pairingAccount: options.pairingAccount,\n accountPairing: () => {\n const team = federation?.team?.();\n const origin = remote.publicOrigin();\n return (\n origin !== undefined &&\n options.publicAuth?.issuer()?.replace(/\\/$/u, '') === origin &&\n team !== undefined &&\n (team === 'loading' || team.org !== '')\n );\n },\n federationHost: federation?.federationHost,\n enrollAccount: federation?.enrollAccount,\n claimAccount: federation?.claimAccount,\n unlinkAccount: federation?.unlinkAccount,\n bindAccountDevice: federation?.bindAccountDevice,\n remote,\n listenerOf: (context) => (context.env as ListenerBindings).listener,\n });\n registerDevProxyRoutes(app as unknown as Hono, {\n store: devProxy,\n listenerOf: (context) => (context.env as ListenerBindings).listener,\n // Read per call: the tunnel port exists only while remote access is on, and a target checked\n // against a stale list could end up aimed at the cockpit itself.\n reservedPorts: () => [\n remote.tunnelPort(),\n frontendOrigin === undefined ? undefined : Number(new URL(frontendOrigin).port),\n ...(options.reservedPorts?.() ?? []),\n ],\n onNotice: (message) => options.onNotice(message),\n });\n app.post('/api/remote/frontend', async (context) => {\n if (context.env.listener !== 'local')\n return context.json({ error: 'This action is only available on the host.' }, 403);\n if (context.req.header('x-po-web-registration') !== options.registrationToken)\n return context.json({ error: 'The web presentation server was not authenticated.' }, 403);\n let body: unknown;\n try {\n body = await context.req.json();\n } catch {\n return context.json({ error: 'A loopback web origin is required.' }, 400);\n }\n const origin = typeof body === 'object' && body !== null && 'origin' in body ? body.origin : undefined;\n if (typeof origin !== 'string') return context.json({ error: 'A loopback web origin is required.' }, 400);\n let parsed: URL;\n try {\n parsed = new URL(origin);\n } catch {\n return context.json({ error: 'The web origin is invalid.' }, 400);\n }\n if (\n parsed.protocol !== 'http:' ||\n !['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname) ||\n parsed.pathname !== '/' ||\n parsed.search !== '' ||\n parsed.hash !== '' ||\n !parsed.port\n )\n return context.json({ error: 'The web origin must be a loopback HTTP listener.' }, 400);\n frontendOrigin = parsed.origin;\n return context.json({ ok: true });\n });\n app.post(REMOTE_HTTP_ROUTE, async (context) => {\n const device = remote.authorize(getCookie(context, DEVICE_COOKIE, 'host'));\n const channel = device === undefined ? undefined : remote.channelFor(device, 'http');\n if (!device || !channel) return context.json({ error: 'A sealed paired device is required.' }, 401);\n let envelope: unknown;\n try {\n envelope = await context.req.json();\n } catch {\n return context.json({ error: 'The sealed request envelope was malformed.' }, 400);\n }\n const startedAt = performance.now();\n const heapBefore = process.memoryUsage().heapUsed;\n const opened = channel.open(envelope);\n if (!opened.ok) return context.json({ error: `The sealed request was refused: ${opened.failure}.` }, 400);\n const openMs = performance.now() - startedAt;\n let decoded: unknown;\n try {\n decoded = JSON.parse(new TextDecoder().decode(opened.plaintext)) as unknown;\n } catch {\n return context.json({ error: 'The sealed HTTP request was malformed.' }, 400);\n }\n const inner = sealedRequest(decoded);\n const body = decodedBody(inner?.body);\n if (!inner || !body) return context.json({ error: 'The sealed HTTP request was invalid.' }, 400);\n const target = new URL(inner.target, 'http://po.local');\n const headers = new Headers();\n for (const [name, value] of inner.headers) {\n const normalized = name.toLowerCase();\n if (FORBIDDEN_HEADERS.has(normalized) || normalized.startsWith('sec-')) continue;\n headers.append(name, value);\n }\n const action = stepUpActionFor(inner.method, target.pathname);\n const stepUpKind = remote.trustKind(device) === 'device-key' ? 'device-key' : 'passkey';\n const peerLinkDenied =\n action === 'peer.link' && isQuickTunnelHost(remote.publicOrigin()) && remote.trustKind(device) !== 'device-key';\n const stepUpNeeded = action !== undefined && (action === 'peer.link' || remote.stepUpRequired(action, device));\n let stepUpDenied = false;\n if (action && stepUpNeeded) {\n const assertion = headers.get(STEP_UP_HEADER);\n let credential: unknown;\n try {\n credential = assertion ? JSON.parse(Buffer.from(assertion, 'base64url').toString('utf8')) : undefined;\n } catch {\n credential = undefined;\n }\n const ceremony = credential as { ceremonyId?: unknown; response?: unknown; signature?: unknown } | undefined;\n if (stepUpKind === 'device-key') {\n // A device-key session proves the gesture with its biometric key, never a passkey.\n stepUpDenied = !remote.finishDeviceStepUp(device, action, ceremony?.ceremonyId, ceremony?.signature);\n } else if (\n typeof ceremony?.ceremonyId !== 'string' ||\n !(await remote.passkeys().finishStepUp(ceremony.ceremonyId, `device:${device}`, action, ceremony.response))\n )\n stepUpDenied = true;\n }\n headers.delete(STEP_UP_HEADER);\n const sealedStepUp = stepUpNeeded && !stepUpDenied ? 'verified' : 'not-required';\n // Caller stamps are assigned after the sealed request is opened. They never\n // originate from browser-controlled sealed headers.\n headers.set(PO_API_CALLER_LOCALITY_HEADER, 'remote');\n headers.set(PO_API_CALLER_DEVICE_ID_HEADER, device);\n headers.set(PO_API_CALLER_STEP_UP_HEADER, sealedStepUp);\n let federationCaller: PoFederationCaller | undefined;\n const hasFederation =\n headers.has('x-po-identity-token') ||\n headers.has('x-po-federation-envelope') ||\n headers.has('x-po-federation-grant');\n // On a team host every request is someone's: the owner's or a teammate's. Anyone else stops here.\n const deviceAccess = callerAccess(device);\n const narrowNetwork = remote.accountOf(device) !== undefined && target.pathname.startsWith('/api/network/');\n // Work between hosts is the owner's, unless the request proves itself and the destination check decides.\n const networkResponse =\n !narrowNetwork && target.pathname.startsWith('/api/network/') && (ownerDevice(device) || hasFederation)\n ? await defaultFederation?.requestNetwork(\n new Request(target, {\n method: inner.method,\n headers,\n ...(inner.method === 'GET' || inner.method === 'HEAD' ? {} : { body }),\n }),\n // A teammate hands over their own settings grant as the device they paired.\n deviceAccess,\n )\n : undefined;\n if (hasFederation && !networkResponse && !narrowNetwork) {\n try {\n federationCaller = await federation?.verify(\n new Request(target, {\n method: inner.method,\n headers,\n ...(inner.method === 'GET' || inner.method === 'HEAD' ? {} : { body }),\n }),\n );\n } catch {\n federationCaller = undefined;\n }\n if (federationCaller) headers.set(PO_API_CALLER_FEDERATION_HEADER, JSON.stringify(federationCaller));\n headers.delete('x-po-identity-token');\n headers.delete('x-po-federation-envelope');\n headers.delete('x-po-federation-grant');\n }\n const access = federationCaller ? callerAccess(device, federationCaller) : deviceAccess;\n const remoteRoute = target.pathname === '/api/remote' || target.pathname.startsWith('/api/remote/');\n if (access !== undefined && access !== 'refused') {\n headers.set(PO_API_CALLER_ACCESS_HEADER, access.access);\n headers.set(PO_API_CALLER_FEDERATION_HEADER, JSON.stringify(access.caller));\n }\n let response: Response;\n if (narrowNetwork) {\n response = context.json(\n { error: 'This pairing authorizes this computer only, not account-device network grants.' },\n 403,\n );\n } else if (networkResponse) {\n response = networkResponse;\n } else if (\n hasFederation &&\n target.pathname.includes('/plugins/') &&\n options.federationPlatform &&\n !(await options.federationPlatform.resolve(new Request(target, { method: inner.method })))\n ) {\n response = context.json({ status: 'unavailable', reason: 'package-not-mounted' }, 503);\n } else if (hasFederation && !federationCaller) {\n response = context.json({ error: 'The destination request proof was refused.' }, 401);\n } else if (access === 'refused' && !(remoteRoute && ownDeviceRemoteRoute(inner.method, target.pathname))) {\n options.audit?.({ device, action: inner.method, resource: target.pathname, outcome: 'denied' });\n response = context.json({ error: 'Sign in to this team on this device first.' }, 401);\n } else if (\n access !== undefined &&\n access !== 'refused' &&\n access.access !== 'owner' &&\n inner.method === 'POST' &&\n target.pathname === `${REMOTE_API_ROUTE}/federation/claim`\n ) {\n // A teammate's app offers to claim every host it pairs. This one is taken, and the device is already theirs here.\n response = context.json({ claimed: false, teammate: true });\n } else if (\n remoteRoute &&\n access !== undefined &&\n access !== 'refused' &&\n access.access !== 'owner' &&\n !ownDeviceRemoteRoute(inner.method, target.pathname)\n ) {\n response = context.json({ error: 'Only the owner of this computer can do that.' }, 403);\n } else if (peerLinkDenied) {\n response = context.json({ error: 'Linking hosts over a quick tunnel needs the Po app.' }, 403);\n } else if (stepUpDenied) {\n const gesture = stepUpKind === 'device-key' ? 'biometric confirmation' : 'passkey gesture';\n response = context.json({ error: `This action needs a fresh ${gesture}.`, action, kind: stepUpKind }, 401);\n } else if (isSessionMcpHostRoute(target.pathname) && !isSessionMcpPhoneRoute(inner.method, target.pathname)) {\n response = context.json({ error: 'Session MCP management is only available on the host.' }, 403);\n } else {\n const internal = new Request(target, {\n method: inner.method,\n headers,\n ...(inner.method === 'GET' || inner.method === 'HEAD' ? {} : { body }),\n });\n if (target.pathname === '/api/remote' || target.pathname.startsWith('/api/remote/')) {\n headers.set('cookie', context.req.header('cookie') ?? '');\n headers.set('host', context.req.header('host') ?? '');\n headers.set('origin', context.req.header('origin') ?? '');\n response = await app.fetch(new Request(internal, { headers }), {\n listener: 'tunnel',\n sealedDeviceId: device,\n sealedStepUp,\n });\n } else response = await options.forward(internal);\n }\n const forwardMs = performance.now() - startedAt - openMs;\n const responseBody = Buffer.from(await response.arrayBuffer());\n const sealStartedAt = performance.now();\n const plaintext = new TextEncoder().encode(\n JSON.stringify({\n v: SEALED_HTTP_VERSION,\n status: response.status,\n headers: [...response.headers.entries()],\n body: responseBody.toString('base64'),\n }),\n );\n const sealed = channel.seal(plaintext);\n const sealMs = performance.now() - sealStartedAt;\n const durationMs = performance.now() - startedAt;\n if (\n options.telemetry &&\n (response.status >= 400 ||\n durationMs >= COMPLETION_SPAN_MIN_DURATION_MS ||\n responseBody.byteLength >= COMPLETION_SPAN_MIN_BYTES ||\n body.byteLength >= COMPLETION_SPAN_MIN_BYTES)\n ) {\n // The plugin name or route family only: a raw path can carry file names and ids. String keys end\n // in a part telemetry allows (`_name`, `_kind`) and avoid parts it drops (`content`, `path`), and\n // values keep to word characters and dots, or the exporter drops or rewrites them.\n const segments = target.pathname.split('/');\n observe(\n options.telemetry.recordEvent('po_server.sealed_http', {\n route_name: segments[2] === 'plugins' ? `plugins.${segments[3] ?? ''}` : (segments[2] ?? ''),\n 'http.operation': inner.method,\n status_code: response.status,\n request_bytes: body.byteLength,\n response_bytes: responseBody.byteLength,\n sealed_plaintext_bytes: plaintext.byteLength,\n response_kind: contentClass(response.headers.get('content-type')),\n open_ms: Math.round(openMs),\n forward_ms: Math.round(forwardMs),\n seal_ms: Math.round(sealMs),\n duration_ms: Math.round(durationMs),\n heap_delta_bytes: process.memoryUsage().heapUsed - heapBefore,\n }),\n (message) => options.onNotice(message),\n );\n }\n return sealed.ok\n ? context.json(sealed.envelope)\n : context.json({ error: `The sealed response failed: ${sealed.failure}.` }, 503);\n });\n app.on(['POST', 'DELETE'], '*', async (context) => {\n if (\n !isPublicSessionMcpRoute(context.req.method, context.req.path) &&\n !(context.req.method === 'POST' && SESSION_PEER_ROUTES.has(context.req.path)) &&\n !(context.req.method === 'POST' && VOICE_PEER_ROUTES.has(context.req.path))\n )\n return context.notFound();\n return options.forward(context.req.raw);\n });\n app.on(['GET', 'HEAD'], '*', async (context) => {\n // Served here and never through forward(), which would attach the host token.\n if (inFileShareNamespace(context.req.raw, context.req.path)) {\n const token = publicFileShareToken(context.req.raw, context.req.path);\n return context.env.listener === 'tunnel' && token !== undefined\n ? fileShares.serve(token, context.req.method)\n : context.json({ error: 'Not found.' }, 404);\n }\n if (isPublicSessionMcpRoute(context.req.method, context.req.path)) return options.forward(context.req.raw);\n if (context.req.path.startsWith('/api/')) return context.json({ error: 'Not found.' }, 404);\n // One domain is one hub: the local cockpit's /hosts proxy to other hubs never answers over the tunnel.\n if (isHostProxyPath(context.req.path)) return context.json({ error: 'Not found.' }, 404);\n if (context.req.path === '/' && remote.authorize(getCookie(context, DEVICE_COOKIE, 'host')) === undefined)\n return context.redirect('/pair');\n if (context.req.path === '/bundle-manifest.json' || context.req.path.startsWith('/bundle-assets/')) {\n const from = new URL(context.req.url);\n return await options.forward(\n new Request(new URL(`${from.pathname}${from.search}`, 'http://po.local'), {\n method: context.req.method,\n }),\n );\n }\n if (!frontendOrigin) return context.json({ error: 'The web presentation server is unavailable.' }, 503);\n const from = new URL(context.req.url);\n const target = new URL(`${from.pathname}${from.search}`, frontendOrigin);\n const result = await fetch(target, { method: context.req.method, redirect: 'manual' });\n const headers = new Headers(result.headers);\n headers.delete('set-cookie');\n return new Response(result.body, { status: result.status, headers });\n });\n\n return {\n remote,\n federationClient: defaultFederation?.client,\n team: () => federation?.team?.(),\n callerAccess: (deviceId) => callerAccess(deviceId),\n fileShares,\n requestNetwork: (request) => defaultFederation?.requestNetwork(request) ?? Promise.resolve(undefined),\n networkComposition: () => defaultFederation?.networkComposition() ?? Promise.resolve({}),\n workspaceProviders: (workspaceId) => defaultFederation?.workspaceProviders(workspaceId) ?? Promise.resolve({}),\n acceptNetworkRelay: async (socket, url) => {\n if (!defaultFederation) {\n socket.close();\n return;\n }\n await defaultFederation.acceptNetworkRelay(socket, url);\n },\n networkPeer: () => defaultFederation?.networkPeer() ?? Promise.resolve(undefined),\n hostRequests: () => defaultFederation?.hostRequests() ?? Promise.resolve(undefined),\n accountCall: (operation, input) => defaultFederation?.accountCall(operation, input) ?? Promise.resolve(undefined),\n startNetwork: () => defaultFederation?.startNetwork() ?? Promise.resolve(),\n fetchLocal: async (request) => app.fetch(request, { listener: 'local' }),\n tunnelIntent,\n restoreTunnel: async (intent) => {\n const parsed = store.settingsForRestore();\n const tunnel = parsed?.settings.tunnel;\n if (\n closing ||\n typeof intent?.hostname !== 'string' ||\n tunnel?.kind !== 'named' ||\n tunnel.hostname !== intent.hostname ||\n parsed?.warnings.length !== 0 ||\n remote.settings().tunnel.kind !== 'named' ||\n (intent.closesAt !== undefined && (!Number.isFinite(intent.closesAt) || intent.closesAt <= Date.now()))\n )\n return { ok: false, error: 'The named tunnel intent is no longer valid for automatic restore.' };\n // Use the validated current file, not the store's potentially stale normalized snapshot.\n remote.updateSettings(parsed.settings);\n return remote.enable(intent.closesAt);\n },\n close: async () => {\n // A runtime shutdown is not a user disable. The owner decides whether to retain intent.\n closing = true;\n await remote.close();\n await defaultFederation?.close();\n },\n };\n}\n","import { PO_API_CALLER_LOCALITY_HEADER, type PoApi } from '@agimon-ai/po-core/packageApi';\nimport type { PoRemoteGateway } from '@agimon-ai/po-core/serverPlugin';\n\n/** Global package mount for the machine's Remote Control service. */\nexport function createRemoteApi(control: PoRemoteGateway): PoApi {\n return {\n basePath: 'remote',\n start(context) {\n if (context.scope !== 'host') throw new Error('Remote Control requires the global headless host.');\n let closed = false;\n return {\n fetch(request) {\n if (closed) return Response.json({ error: 'Remote Control is closed.' }, { status: 503 });\n // Paired devices use /api/remote on the tunnel; this mount drives host-only actions.\n if (request.headers.get(PO_API_CALLER_LOCALITY_HEADER) === 'remote')\n return Response.json({ error: 'Remote Control is local only.' }, { status: 403 });\n const origin = request.headers.get('origin');\n if (origin !== null) {\n let allowed = false;\n try {\n const parsed = new URL(origin);\n allowed = parsed.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname);\n } catch {\n allowed = false;\n }\n if (!allowed) return Response.json({ error: 'That origin may not control this cockpit.' }, { status: 403 });\n }\n const from = new URL(request.url);\n const suffix = from.pathname === '/' ? '' : from.pathname;\n const target = new URL(`/api/remote${suffix}${from.search}`, 'http://po.local');\n return control.fetch(new Request(target, request));\n },\n close() {\n closed = true;\n },\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,kBAAkB;;;;;;;;AAQxB,MAAM,cAAc;AACpB,MAAM,WAAW;AACjB,MAAM,WAAW;AAWjB,SAAgB,mBAAmB,KAA2B;CAC5D,IAAI,OAAO,QAAQ,UAAU,OAAO;EAAE,IAAI;EAAO,QAAQ;CAA8B;CACvF,MAAM,OAAO,IAAI,KAAK,CAAC,CAAC,YAAY;CACpC,IAAI,SAAS,IAAI,OAAO;EAAE,IAAI;EAAO,QAAQ;CAAyB;CACtE,IAAI,KAAK,SAAS,iBAChB,OAAO;EAAE,IAAI;EAAO,QAAQ,4BAA4B,OAAO,eAAe,EAAE;CAAc;CAEhG,IAAI,CAAC,YAAY,KAAK,IAAI,GACxB,OAAO;EACL,IAAI;EACJ,QAAQ;CACV;CAEF,OAAO;EAAE,IAAI;EAAM;CAAK;AAC1B;;;;;;;;;;AAWA,SAAgB,mBAAmB,KAAc,UAAwD;CACvG,MAAM,OAAO,OAAO,QAAQ,WAAW,MAAM,OAAO,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