@mostra/runtime 0.9.0 → 0.10.0

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.
Files changed (65) hide show
  1. package/dist/bin.js +2879 -8
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +2 -2
  4. package/dist/{child-Chiavhdx.js → child-BmNZ4a70.js} +2 -2
  5. package/dist/{child-Chiavhdx.js.map → child-BmNZ4a70.js.map} +1 -1
  6. package/dist/deps/child/install.js +1 -1
  7. package/dist/{directories-mJ1qlVht.js → directories-BLJjeSPD.js} +5 -5
  8. package/dist/directories-BLJjeSPD.js.map +1 -0
  9. package/dist/{files-FygSJIzK.js → files-DGeWuE4I.js} +2 -2
  10. package/dist/{files-FygSJIzK.js.map → files-DGeWuE4I.js.map} +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{instance-EnaZPs14.js → instance-FExcyENK.js} +3341 -396
  15. package/dist/instance-FExcyENK.js.map +1 -0
  16. package/package.json +7 -5
  17. package/src/actions/index.ts +163 -10
  18. package/src/bin.ts +78 -1
  19. package/src/gateway/actions.ts +20 -4
  20. package/src/gateway/browser.ts +118 -95
  21. package/src/gateway/capabilities.ts +15 -6
  22. package/src/gateway/index.ts +112 -15
  23. package/src/gateway/routes.ts +15 -7
  24. package/src/gc/index.ts +14 -0
  25. package/src/instance/index.ts +41 -2
  26. package/src/interaction/ephemeral.ts +32 -23
  27. package/src/interaction/events.ts +21 -1
  28. package/src/interaction/imports.ts +317 -0
  29. package/src/interaction/index.ts +172 -19
  30. package/src/interaction/outbox.ts +9 -0
  31. package/src/interaction/results.ts +8 -1
  32. package/src/interaction/runs.ts +52 -2
  33. package/src/interaction/submissions.ts +17 -1
  34. package/src/interaction/tally.ts +129 -0
  35. package/src/ledger/index.ts +104 -9
  36. package/src/ledger/migrations.ts +183 -0
  37. package/src/ledger/types.ts +8 -0
  38. package/src/link/binding.ts +289 -0
  39. package/src/link/hosted.ts +65 -0
  40. package/src/link/http.ts +136 -0
  41. package/src/link/index.ts +8 -0
  42. package/src/link/manager.ts +1385 -0
  43. package/src/link/relay.ts +512 -0
  44. package/src/live/index.ts +112 -2
  45. package/src/platform/filesystems.ts +78 -0
  46. package/src/platform/index.ts +1 -0
  47. package/src/protocol-server/index.ts +18 -1
  48. package/src/protocol-server/server.ts +38 -7
  49. package/src/protocol-server/websocket.ts +161 -0
  50. package/src/publish/bundle.ts +398 -0
  51. package/src/publish/manifest.ts +9 -0
  52. package/src/publish/methods.ts +12 -1
  53. package/src/publish/publisher.ts +127 -0
  54. package/src/registry/index.ts +35 -14
  55. package/src/server/api.ts +439 -0
  56. package/src/server/auth.ts +613 -0
  57. package/src/server/config.ts +221 -0
  58. package/src/server/data.ts +369 -0
  59. package/src/server/directory.ts +141 -0
  60. package/src/server/hosted.ts +822 -0
  61. package/src/server/index.ts +368 -0
  62. package/src/server/relay.ts +1163 -0
  63. package/src/share/index.ts +110 -6
  64. package/dist/directories-mJ1qlVht.js.map +0 -1
  65. package/dist/instance-EnaZPs14.js.map +0 -1
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { mkdirSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\n/**\n * `mostra-runtime`, the runtime bundle's entry point (D85).\n *\n * mostra-runtime host [--home <dir>] the host protocol over stdio (`mostra host`)\n * mostra-runtime daemon [--home <dir>] [--always-on]\n * the home's daemon on its socket (`mostra daemon start`);\n * it exits after 30 idle minutes unless `--always-on`\n * mostra-runtime service install|uninstall|status [--home <dir>] [--no-start]\n * the home's login service (`mostra daemon install`, D62):\n * one JSON line with the service's file and state\n *\n * Both take `--bind <address>` to serve viewers on an address other than 127.0.0.1, and\n * `--url-host <name>`, the host name links use, which a wildcard address needs (D99). Neither is\n * remembered: every wider start is explicit.\n *\n * `daemon` prints one JSON line on stdout: `{\"status\":\"started\",…}` when it took the home,\n * `{\"status\":\"attached\",…}` when another daemon already owns it (then it exits 0), or\n * `{\"status\":\"failed\",\"diagnostic\":…}` (exit 3). `host` speaks only the protocol on stdout; when it\n * can't start, it answers the host's first request with the diagnostic and exits 3. Logs go to\n * `<home>/logs/supervisor.log`; warnings and errors are mirrored to stderr.\n */\nimport { parseArgs } from \"node:util\";\nimport {\n createDiagnostic,\n type Diagnostic,\n encodeLine,\n LineSplitter,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport { checkPlatform, resolveHomePath } from \"./home/index.ts\";\nimport { type Instance, runtimeVersion, startInstance } from \"./instance/index.ts\";\nimport { realPath } from \"./platform/index.ts\";\nimport { installService, serviceStatus, uninstallService } from \"./service/index.ts\";\n\n/** Exit codes, as INTERFACES §9 defines them for the CLI. */\nconst EXIT = { ok: 0, failure: 1, usage: 2, environment: 3 } as const;\n\nconst USAGE = [\n \"usage: mostra-runtime <host|daemon> [--home <dir>] [--bind <address> [--url-host <name>]] [--always-on]\",\n \" mostra-runtime service <install|uninstall|status> [--home <dir>] [--no-start]\",\n].join(\"\\n\");\n\n// A closed stdout or stderr (a starter that read the ready line and left) must not crash the\n// supervisor.\nprocess.stdout.on(\"error\", () => {});\nprocess.stderr.on(\"error\", () => {});\n\nconst mirror = (line: string): void => {\n process.stderr.write(line);\n};\n\nfunction diagnosticOf(error: unknown): Diagnostic {\n if (error instanceof RpcError) return error.diagnostic;\n return createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: `mostra-runtime failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`,\n });\n}\n\n/**\n * In host mode, a supervisor that can't start still speaks the protocol: it answers the host's\n * requests with the diagnostic, then exits once the first is answered or stdin ends.\n */\nfunction refuseOverStdio(diagnostic: Diagnostic, exitCode: number): void {\n mirror(`${JSON.stringify({ level: \"error\", diagnostic })}\\n`);\n const splitter = new LineSplitter();\n const exit = (): void => {\n process.stdout.write(\"\", () => process.exit(exitCode));\n };\n const peer = new RpcPeer({\n send: (message) => {\n process.stdout.write(encodeLine(message));\n },\n onRequest: () => {\n setImmediate(exit);\n throw new RpcError(diagnostic);\n },\n });\n process.stdin.setEncoding(\"utf8\");\n process.stdin.on(\"data\", (chunk: string) => {\n try {\n for (const line of splitter.push(chunk)) peer.receiveLine(line);\n } catch {\n exit();\n }\n });\n process.stdin.on(\"end\", exit);\n process.stdin.on(\"error\", exit);\n setTimeout(exit, 30_000).unref();\n}\n\nfunction handleSignals(instance: Instance): void {\n // SIGTERM and SIGINT on POSIX; on Windows Ctrl+C and Ctrl+Break reach a console process as\n // SIGINT and SIGBREAK, and everything else stops it over the protocol (`mostra/shutdown`, D87).\n for (const signal of [\"SIGTERM\", \"SIGINT\", \"SIGBREAK\"] as const) {\n process.on(signal, () => void instance.stop(signal, EXIT.ok));\n }\n process.on(\"SIGPIPE\", () => {});\n // Last resort: children never outlive an exiting supervisor (FAILURE_MODEL §2).\n process.on(\"exit\", () => instance.processes.killAll());\n process.on(\"uncaughtException\", (error) => {\n mirror(`${JSON.stringify({ level: \"error\", event: \"uncaught\", message: error.message })}\\n`);\n // The home's log keeps what failed and where, so a failure nobody watched stderr for still\n // names its cause (#35: an instance that ended with only \"uncaught exception\" in its log).\n void instance.stop(\n \"uncaught exception\",\n EXIT.failure,\n createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: (error instanceof Error\n ? (error.stack ?? `${error.name}: ${error.message}`)\n : String(error)\n ).slice(0, 8192),\n }),\n );\n setTimeout(() => process.exit(EXIT.failure), 15_000).unref();\n });\n}\n\nasync function main(argv: readonly string[]): Promise<number> {\n let parsed: ReturnType<typeof parse>;\n try {\n parsed = parse(argv);\n } catch (error) {\n process.stderr.write(`${(error as Error).message}\\n${USAGE}\\n`);\n return EXIT.usage;\n }\n const { values, positionals } = parsed;\n if (values.version) {\n process.stdout.write(`${runtimeVersion()}\\n`);\n return EXIT.ok;\n }\n const [mode, ...rest] = positionals;\n if (mode === \"service\" && !values.help)\n return await service(rest, values.home, values[\"no-start\"] === true);\n if (values.help || (mode !== \"host\" && mode !== \"daemon\") || rest.length > 0) {\n (values.help ? process.stdout : process.stderr).write(`${USAGE}\\n`);\n return values.help ? EXIT.ok : EXIT.usage;\n }\n\n try {\n const started = await startInstance({\n mode,\n home: values.home,\n bind: values.bind,\n urlHost: values[\"url-host\"],\n alwaysOn: values[\"always-on\"] === true,\n mirror,\n ...(mode === \"host\" ? { stdio: { input: process.stdin, output: process.stdout } } : {}),\n });\n if (started.kind === \"attached\") {\n process.stdout.write(\n `${JSON.stringify({\n status: \"attached\",\n pid: started.record.pid,\n home: started.result.instance.home,\n socket: started.record.socket,\n revision: started.result.revision,\n })}\\n`,\n );\n return EXIT.ok;\n }\n const { instance } = started;\n handleSignals(instance);\n if (mode === \"daemon\") {\n process.stdout.write(\n `${JSON.stringify({\n status: \"started\",\n pid: instance.info.pid,\n home: instance.info.home,\n socket: instance.socketPath,\n reaped: instance.reaped.filter((child) => child.signalled.length > 0).length,\n })}\\n`,\n );\n }\n const stop = await instance.stopped;\n return stop.exitCode;\n } catch (error) {\n const diagnostic = diagnosticOf(error);\n const exitCode = error instanceof RpcError ? EXIT.environment : EXIT.failure;\n if (mode === \"host\") {\n refuseOverStdio(diagnostic, exitCode);\n return new Promise<number>(() => {});\n }\n process.stdout.write(`${JSON.stringify({ status: \"failed\", diagnostic })}\\n`);\n mirror(`${JSON.stringify({ level: \"error\", diagnostic })}\\n`);\n return exitCode;\n }\n}\n\n/** `mostra-runtime service …`: the home's login service, as one JSON line (D62, RT-08). */\nasync function service(\n args: readonly string[],\n home: string | undefined,\n noStart: boolean,\n): Promise<number> {\n const [action, ...extra] = args;\n if ((action !== \"install\" && action !== \"uninstall\" && action !== \"status\") || extra.length > 0) {\n process.stderr.write(`${USAGE}\\n`);\n return EXIT.usage;\n }\n const gate = checkPlatform();\n if (gate) {\n process.stdout.write(`${JSON.stringify({ status: \"failed\", diagnostic: gate })}\\n`);\n return EXIT.environment;\n }\n try {\n const resolved = resolveHomePath({ home, env: process.env });\n mkdirSync(resolved, { recursive: true, mode: 0o700 });\n const spec = {\n // As the daemon spells its home, so the service's name and hash are the daemon's (D82).\n home: realPath(resolved),\n node: process.execPath,\n entry: fileURLToPath(import.meta.url),\n };\n // Who asks, should a Windows uninstall stop the daemon over its pipe.\n const client = { name: \"mostra-runtime-service\", version: runtimeVersion() };\n const status =\n action === \"install\"\n ? await installService(spec, { noStart, client })\n : action === \"uninstall\"\n ? await uninstallService(spec, { noStart, client })\n : serviceStatus(spec);\n process.stdout.write(`${JSON.stringify({ status: \"ok\", action, service: status })}\\n`);\n return EXIT.ok;\n } catch (error) {\n const diagnostic = diagnosticOf(error);\n process.stdout.write(`${JSON.stringify({ status: \"failed\", diagnostic })}\\n`);\n return EXIT.environment;\n }\n}\n\nfunction parse(argv: readonly string[]) {\n return parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n home: { type: \"string\" },\n bind: { type: \"string\" },\n \"url-host\": { type: \"string\" },\n \"always-on\": { type: \"boolean\" },\n \"no-start\": { type: \"boolean\" },\n help: { type: \"boolean\", short: \"h\" },\n version: { type: \"boolean\" },\n },\n });\n}\n\nconst code = await main(process.argv.slice(2));\n// Let stdout drain before exiting, so the status line is never cut off.\nprocess.stdout.write(\"\", () => process.exit(code));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,OAAO;CAAE,IAAI;CAAG,SAAS;CAAG,OAAO;CAAG,aAAa;AAAE;AAE3D,MAAM,QAAQ,CACZ,2GACA,sFACF,CAAC,CAAC,KAAK,IAAI;AAIX,QAAQ,OAAO,GAAG,eAAe,CAAC,CAAC;AACnC,QAAQ,OAAO,GAAG,eAAe,CAAC,CAAC;AAEnC,MAAM,UAAU,SAAuB;CACrC,QAAQ,OAAO,MAAM,IAAI;AAC3B;AAEA,SAAS,aAAa,OAA4B;CAChD,IAAI,iBAA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;GAAM,KAAK,QAAQ;EAAI,CAAC;EAC3D,UAAU,UAAU;GAAE,WAAW;GAAM,MAAM;EAAM,CAAC;EACpD,MAAM,OAAO;GAEX,MAAM,SAAS,QAAQ;GACvB,MAAM,QAAQ;GACd,OAAO,cAAc,YAAY,GAAG;EACtC;EAEA,MAAM,SAAS;GAAE,MAAM;GAA0B,SAAS,eAAe;EAAE;EAC3E,MAAM,SACJ,WAAW,YACP,MAAM,eAAe,MAAM;GAAE;GAAS;EAAO,CAAC,IAC9C,WAAW,cACT,MAAM,iBAAiB,MAAM;GAAE;GAAS;EAAO,CAAC,IAChD,cAAc,IAAI;EAC1B,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU;GAAE,QAAQ;GAAM;GAAQ,SAAS;EAAO,CAAC,EAAE,GAAG;EACrF,OAAO,KAAK;CACd,SAAS,OAAO;EACd,MAAM,aAAa,aAAa,KAAK;EACrC,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU;GAAE,QAAQ;GAAU;EAAW,CAAC,EAAE,GAAG;EAC5E,OAAO,KAAK;CACd;AACF;AAEA,SAAS,MAAM,MAAyB;CACtC,OAAO,UAAU;EACf,MAAM,CAAC,GAAG,IAAI;EACd,kBAAkB;EAClB,SAAS;GACP,MAAM,EAAE,MAAM,SAAS;GACvB,MAAM,EAAE,MAAM,SAAS;GACvB,YAAY,EAAE,MAAM,SAAS;GAC7B,aAAa,EAAE,MAAM,UAAU;GAC/B,YAAY,EAAE,MAAM,UAAU;GAC9B,MAAM;IAAE,MAAM;IAAW,OAAO;GAAI;GACpC,SAAS,EAAE,MAAM,UAAU;EAC7B;CACF,CAAC;AACH;AAEA,MAAM,OAAO,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC;AAE7C,QAAQ,OAAO,MAAM,UAAU,QAAQ,KAAK,IAAI,CAAC"}
1
+ {"version":3,"file":"bin.js","names":["refusal","parse"],"sources":["../src/platform/filesystems.ts","../src/server/api.ts","../src/server/auth.ts","../src/server/directory.ts","../src/server/data.ts","../src/server/relay.ts","../src/server/hosted.ts","../src/server/config.ts","../src/server/index.ts","../src/bin.ts"],"sourcesContent":["/**\n * Whether a directory is on a network filesystem (D165 item 0b, DATA_MODEL §7.1): a remote\n * server's data directory never is, since its locks and SQLite's WAL need a local disk, and a\n * lock a network filesystem only pretends to hold would let two servers write one home.\n *\n * - **Linux:** the filesystem's magic number from `statfs(2)`: NFS, SMB, CIFS, SMB2, Ceph,\n * AFS, Coda, 9P and FUSE (a FUSE mount may be sshfs or s3fs; a local FUSE data directory is\n * refused too, rather than guessed at).\n * - **macOS:** the filesystem's name (`stat -f %T`): `nfs`, `smbfs`, `afpfs`, `webdav`,\n * `macfuse`/`osxfuse` and other FUSE names.\n * - **Windows:** a UNC path (`\\\\server\\share`), or a drive Windows reports as remote\n * (`GetDriveTypeW`, through `fsutil fsinfo drivetype`).\n *\n * Answers the filesystem's name when it is a network one, `undefined` when it is local or can't\n * be told (a check that can't run never refuses a disk it can't classify).\n */\nimport { execFileSync } from \"node:child_process\";\nimport { statfsSync } from \"node:fs\";\nimport { parse } from \"node:path\";\n\n/** Linux `statfs` magic numbers of network and user-space filesystems. */\nconst LINUX_NETWORK: ReadonlyMap<number, string> = new Map([\n [0x6969, \"nfs\"],\n [0x517b, \"smb\"],\n [0xff534d42, \"cifs\"],\n [0xfe534d42, \"smb2\"],\n [0x00c36400, \"ceph\"],\n [0x5346414f, \"afs\"],\n [0x73757245, \"coda\"],\n [0x01021997, \"9p\"],\n [0x65735546, \"fuse\"],\n]);\n\nconst MAC_NETWORK = /^(nfs|smbfs|afpfs|webdav|cifs|ftp|macfuse|osxfuse|fuse.*)$/i;\n\n/** The network filesystem `dir` is on, or `undefined` (local, or not knowable). */\nexport function networkFilesystem(dir: string): string | undefined {\n if (process.platform === \"linux\") {\n try {\n // `type` is a signed long on some systems: compare as unsigned 32-bit.\n const type = statfsSync(dir).type >>> 0;\n return LINUX_NETWORK.get(type);\n } catch {\n return undefined;\n }\n }\n if (process.platform === \"darwin\") {\n try {\n const name = execFileSync(\"/usr/bin/stat\", [\"-f\", \"%T\", dir], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n return MAC_NETWORK.test(name) ? name : undefined;\n } catch {\n return undefined;\n }\n }\n if (process.platform === \"win32\") {\n if (/^\\\\\\\\[^\\\\?.]/.test(dir)) return \"unc\";\n const drive = parse(dir).root.replace(/\\\\$/, \"\");\n if (!/^[A-Za-z]:$/.test(drive)) return undefined;\n try {\n const answer = execFileSync(\n `${process.env[\"SystemRoot\"] ?? \"C:\\\\Windows\"}\\\\System32\\\\fsutil.exe`,\n [\"fsinfo\", \"drivetype\", drive],\n {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n windowsHide: true,\n },\n );\n return /remote|network/i.test(answer) ? \"remote\" : undefined;\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n","/**\n * The remote server's API origin (INTERFACES §18.2, §18.5): the authorization server's device\n * grant (`/oauth/device`, `/oauth/token`, `/oauth/revoke`, its metadata and the device page), the\n * network binding (`/host`, JSON-RPC over WebSocket with a bearer token) and version files\n * (`PUT /files/<sha256>`). Never on a user-content domain (D165 item 7).\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { createWriteStream, existsSync, renameSync } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { join } from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport { type WebSocket, WebSocketServer } from \"ws\";\nimport type { Log } from \"../log.ts\";\nimport { BINDING_SUBPROTOCOL, MAX_FRAME_BYTES, serveWebSocket } from \"../protocol-server/index.ts\";\nimport type { Authenticated, Authorization } from \"./auth.ts\";\nimport type { RemoteServerConfig } from \"./config.ts\";\nimport type { HostedHome } from \"./hosted.ts\";\n\n/** How often an open binding's grant is checked again: a revocation closes it within 60 s. */\nconst GRANT_RECHECK_MS = 30_000;\n\n/** The largest version file accepted (per file; an operator's storage limit is WP-30's). */\nconst MAX_FILE_BYTES = 256 * 1024 * 1024;\n\nconst BASE_HEADERS = {\n \"cache-control\": \"no-store\",\n \"cross-origin-resource-policy\": \"same-origin\",\n \"referrer-policy\": \"no-referrer\",\n \"x-content-type-options\": \"nosniff\",\n} as const;\n\nfunction send(\n response: ServerResponse,\n status: number,\n body: unknown,\n headers: Record<string, string> = {},\n): void {\n const text = JSON.stringify(body);\n response.writeHead(status, {\n ...BASE_HEADERS,\n \"content-type\": \"application/json; charset=utf-8\",\n \"content-length\": String(Buffer.byteLength(text)),\n ...headers,\n });\n response.end(text);\n}\n\nfunction page(response: ServerResponse, status: number, html: string): void {\n response.writeHead(status, {\n ...BASE_HEADERS,\n \"content-type\": \"text/html; charset=utf-8\",\n \"content-security-policy\":\n \"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'\",\n \"x-frame-options\": \"DENY\",\n // The device page posts its own form, whose `Origin` the server checks: under `no-referrer`\n // browsers send `Origin: null` for a form's POST, so this page sends origins to itself only.\n \"referrer-policy\": \"same-origin\",\n });\n response.end(html);\n}\n\nasync function readBody(request: IncomingMessage, limit: number): Promise<Buffer | undefined> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n size += (chunk as Buffer).length;\n if (size > limit) return undefined;\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks);\n}\n\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (character) => `&#${character.charCodeAt(0)};`);\n}\n\n/** Options for {@link createApi}. */\nexport interface ApiOptions {\n readonly config: RemoteServerConfig;\n readonly auth: Authorization;\n readonly log: Log;\n readonly filesDir: string;\n /** The hosted home an account's token names, opened on demand. */\n readonly home: (homeId: string) => Promise<HostedHome>;\n /** Notes a home was used, so it isn't closed while used. */\n readonly touch: (homeId: string) => void;\n /** How often an open binding's token and grant are checked; tests shorten it. */\n readonly recheckMs?: number;\n}\n\n/** The API origin's request and upgrade handlers. */\nexport interface Api {\n request(request: IncomingMessage, response: ServerResponse, path: string): Promise<void>;\n upgrade(request: IncomingMessage, socket: Duplex, head: Buffer, path: string): void;\n close(): void;\n}\n\n/** The development identity provider, when the configuration names one (§18.5, WP-29). */\nfunction developmentProvider(\n config: RemoteServerConfig,\n): { id: string; label: string } | undefined {\n const provider = config.identityProviders?.find((candidate) => candidate.kind === \"development\");\n return provider ? { id: provider.id, label: provider.label ?? \"Development sign-in\" } : undefined;\n}\n\n/** The device page: the code, the warning, and the development provider's sign-in. */\nfunction devicePage(options: {\n readonly code: string;\n readonly provider: { id: string; label: string } | undefined;\n readonly message?: string;\n readonly done?: boolean;\n}): string {\n const body = options.done\n ? `<p>${escapeHtml(options.message ?? \"Done.\")}</p><p>You can close this page.</p>`\n : `${options.message ? `<p role=\"alert\">${escapeHtml(options.message)}</p>` : \"\"}\n<p><strong>Approving links a machine to your account.</strong> That machine's Mostra can then host\npages under your account and receives their answers. Continue only if you started this sign-in\nyourself, on that machine.</p>\n${\n options.provider\n ? `<form method=\"post\" action=\"/device\">\n<label>Code <input name=\"user_code\" value=\"${escapeHtml(options.code)}\" autocomplete=\"off\" required></label>\n<p>${escapeHtml(options.provider.label)}: this server signs people in with a development provider,\nwhich trusts the name you type. Use it only on a server you run for yourself or for tests.</p>\n<label>Your name <input name=\"name\" required maxlength=\"64\"></label>\n<input type=\"hidden\" name=\"provider\" value=\"${escapeHtml(options.provider.id)}\">\n<p><button name=\"decision\" value=\"approve\">Approve this machine</button>\n<button name=\"decision\" value=\"deny\">Refuse</button></p>\n</form>`\n : \"<p>This server has no identity provider configured, so nobody can sign in yet.</p>\"\n}`;\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"robots\" content=\"noindex\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Link a machine to Mostra</title>\n<style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}\ninput{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>\n<body><h1>Link a machine to Mostra</h1>${body}</body></html>`;\n}\n\n/** Creates the API origin. */\nexport function createApi(options: ApiOptions): Api {\n const { config, auth, log } = options;\n const apiOrigin = config.apiOrigin;\n const sockets = new WebSocketServer({\n noServer: true,\n maxPayload: MAX_FRAME_BYTES,\n perMessageDeflate: false,\n handleProtocols: (protocols) =>\n protocols.has(BINDING_SUBPROTOCOL) ? BINDING_SUBPROTOCOL : false,\n });\n const bindings = new Set<WebSocket>();\n\n const bearer = (request: IncomingMessage): Authenticated | undefined => {\n const header = request.headers.authorization ?? \"\";\n const match = /^bearer\\s+(\\S+)$/i.exec(header);\n return match ? auth.authenticate(match[1] as string) : undefined;\n };\n\n const unauthorized = (response: ServerResponse, message: string): void =>\n send(\n response,\n 401,\n { code: \"MOSTRA_REMOTE_LOGIN_FAILED\", message },\n {\n \"www-authenticate\": `Bearer resource_metadata=\"${apiOrigin}/.well-known/oauth-protected-resource/host\"`,\n },\n );\n\n const metadata = () => ({\n issuer: apiOrigin,\n token_endpoint: `${apiOrigin}/oauth/token`,\n device_authorization_endpoint: `${apiOrigin}/oauth/device`,\n revocation_endpoint: `${apiOrigin}/oauth/revoke`,\n grant_types_supported: [\"urn:ietf:params:oauth:grant-type:device_code\", \"refresh_token\"],\n token_endpoint_auth_methods_supported: [\"none\"],\n code_challenge_methods_supported: [\"S256\"],\n scopes_supported: [\"mostra\", \"offline_access\"],\n authorization_response_iss_parameter_supported: true,\n });\n\n const form = async (request: IncomingMessage): Promise<URLSearchParams | undefined> => {\n const type = request.headers[\"content-type\"] ?? \"\";\n if (!type.startsWith(\"application/x-www-form-urlencoded\")) return undefined;\n const body = await readBody(request, 64 * 1024);\n return body === undefined ? undefined : new URLSearchParams(body.toString(\"utf8\"));\n };\n\n const upload = async (\n request: IncomingMessage,\n response: ServerResponse,\n sha: string,\n ): Promise<void> => {\n const who = bearer(request);\n if (!who) {\n unauthorized(response, \"Version files need the binding's access token.\");\n return;\n }\n const home = await options.home(who.homeId);\n options.touch(who.homeId);\n // A file is accepted only for a pending push of this home that names it as missing, so no\n // home stores bytes nobody asked for, nor learns what another home holds (§18.2).\n if (!home.wanted(sha)) {\n send(response, 409, {\n code: \"MOSTRA_HOME_INTEGRITY\",\n message: \"No pending push of this home names that file as missing.\",\n });\n return;\n }\n const target = join(options.filesDir, sha);\n const scratch = join(options.filesDir, `.upload-${randomBytes(8).toString(\"hex\")}`);\n const hash = createHash(\"sha256\");\n let size = 0;\n let tooLarge = false;\n await new Promise<void>((resolve, reject) => {\n const out = createWriteStream(scratch, { mode: 0o600 });\n request.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (size > MAX_FILE_BYTES) {\n tooLarge = true;\n request.destroy();\n return;\n }\n hash.update(chunk);\n out.write(chunk);\n });\n request.on(\"end\", () => out.end(() => resolve()));\n request.on(\"error\", reject);\n request.on(\"close\", () => {\n if (tooLarge) out.end(() => resolve());\n });\n }).catch(() => undefined);\n if (tooLarge || hash.digest(\"hex\") !== sha) {\n await rm(scratch, { force: true });\n send(response, tooLarge ? 413 : 400, {\n code: \"MOSTRA_HOME_INTEGRITY\",\n message: tooLarge ? \"The file is too large.\" : \"The bytes don't hash to the file's name.\",\n });\n return;\n }\n if (existsSync(target)) await rm(scratch, { force: true });\n else renameSync(scratch, target);\n home.uploaded(sha);\n send(response, 201, { sha256: sha, size });\n };\n\n return {\n async request(request, response, path) {\n const method = request.method ?? \"GET\";\n if (method === \"GET\" && path === \"/.well-known/oauth-authorization-server\") {\n send(response, 200, metadata());\n return;\n }\n if (method === \"GET\" && path === \"/.well-known/oauth-protected-resource/host\") {\n send(response, 200, {\n resource: `${apiOrigin}/host`,\n authorization_servers: [apiOrigin],\n scopes_supported: [\"mostra\"],\n });\n return;\n }\n if (method === \"POST\" && path === \"/oauth/device\") {\n const body = await form(request);\n if (!body) {\n send(response, 400, { error: \"invalid_request\", error_description: \"Send a form.\" });\n return;\n }\n const answer = auth.device(body);\n if (\"error\" in answer && typeof answer[\"status\"] === \"number\") {\n const failed = answer as unknown as {\n status: number;\n error: string;\n description: string;\n };\n send(response, failed.status, {\n error: failed.error,\n error_description: failed.description,\n });\n return;\n }\n send(response, 200, answer);\n return;\n }\n if (method === \"POST\" && path === \"/oauth/token\") {\n const body = await form(request);\n if (!body) {\n send(response, 400, { error: \"invalid_request\", error_description: \"Send a form.\" });\n return;\n }\n const answer = auth.token(body);\n if (\"error\" in answer) {\n send(response, answer.status, {\n error: answer.error,\n error_description: answer.description,\n });\n return;\n }\n send(response, 200, answer);\n return;\n }\n if (method === \"POST\" && path === \"/oauth/revoke\") {\n const body = await form(request);\n if (body) auth.revoke(body);\n send(response, 200, {});\n return;\n }\n if (path === \"/device\") {\n const provider = developmentProvider(config);\n if (method === \"GET\") {\n const code = new URL(request.url ?? \"/\", apiOrigin).searchParams.get(\"user_code\") ?? \"\";\n page(response, 200, devicePage({ code, provider }));\n return;\n }\n if (method === \"POST\") {\n // The page's own form only: a cross-site form post approves nothing.\n if (request.headers.origin !== apiOrigin) {\n page(\n response,\n 403,\n devicePage({ code: \"\", provider, message: \"This form must be sent from this page.\" }),\n );\n return;\n }\n const body = await form(request);\n const code = body?.get(\"user_code\") ?? \"\";\n const name = (body?.get(\"name\") ?? \"\").trim().slice(0, 64);\n if (!body || !provider || body.get(\"provider\") !== provider.id || name === \"\") {\n page(\n response,\n 400,\n devicePage({ code, provider, message: \"Enter the code and your name.\" }),\n );\n return;\n }\n const approve = body.get(\"decision\") === \"approve\";\n const decided = auth.decide({\n code,\n approve,\n identity: { provider: provider.id, subject: name.toLowerCase(), name },\n });\n if (!decided.ok) {\n page(response, 400, devicePage({ code, provider, message: decided.reason }));\n return;\n }\n page(\n response,\n 200,\n devicePage({\n code,\n provider,\n done: true,\n message: approve\n ? \"The machine is linked to your account.\"\n : \"The sign-in was refused.\",\n }),\n );\n return;\n }\n }\n const file = /^\\/files\\/([0-9a-f]{64})$/.exec(path);\n if (file && method === \"PUT\") {\n await upload(request, response, file[1] as string);\n return;\n }\n send(response, 404, {\n code: \"MOSTRA_HYGIENE_NOT_SERVED\",\n message: \"Nothing is served at this path.\",\n });\n },\n\n upgrade(request, socket, head, path) {\n const refuse = (status: number, text: string, extra = \"\"): void => {\n socket.end(\n `HTTP/1.1 ${status} ${text}\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n${extra}\\r\\n`,\n );\n };\n if (path !== \"/host\") {\n refuse(404, \"Not Found\");\n return;\n }\n const who = bearer(request);\n if (!who) {\n refuse(\n 401,\n \"Unauthorized\",\n `www-authenticate: Bearer resource_metadata=\"${apiOrigin}/.well-known/oauth-protected-resource/host\"\\r\\n`,\n );\n return;\n }\n void options.home(who.homeId).then(\n (home) => {\n sockets.handleUpgrade(request, socket, head, (ws) => {\n bindings.add(ws);\n let expiresAt = who.expiresAt;\n const attributes = {\n accountId: who.accountId,\n grantId: who.grantId,\n homeId: who.homeId,\n linkId: who.linkId,\n replaceToken: (next: number) => {\n expiresAt = next;\n },\n };\n // The binding ends at its token's expiry unless refreshed in band (`remote/token`), and\n // within 60 s of the grant's revocation or the account's suspension (§18.2).\n const watch = setInterval(\n () => {\n if (Date.now() >= expiresAt) {\n log.info(\"binding.token_expired\", { home: who.homeId });\n ws.close(4401, \"token expired\");\n } else if (!auth.grantLive(who.grantId)) {\n log.info(\"binding.grant_revoked\", { home: who.homeId });\n ws.close(4403, \"grant revoked\");\n }\n },\n Math.min(GRANT_RECHECK_MS, options.recheckMs ?? GRANT_RECHECK_MS),\n );\n watch.unref();\n ws.once(\"close\", () => {\n clearInterval(watch);\n bindings.delete(ws);\n });\n ws.on(\"message\", () => options.touch(who.homeId));\n serveWebSocket(home.protocol, ws, { attributes, log });\n log.info(\"binding.opened\", { home: who.homeId, link: who.linkId });\n });\n },\n (error: unknown) => {\n log.error(\"binding.home_failed\", { home: who.homeId, error });\n refuse(503, \"Service Unavailable\");\n },\n );\n },\n\n close() {\n for (const ws of bindings) ws.terminate();\n sockets.close();\n },\n };\n}\n","/**\n * The remote server's authorization server, as far as WP-29 builds it (INTERFACES §18.5, D165\n * items 2, 8): the OAuth 2.0 device authorization grant (RFC 8628) behind `mostra login`, with\n * rotating refresh tokens and revocation, and a development identity provider for tests and a\n * self-hoster's first run. WP-30 adds the real identity providers, viewer sign-in and the MCP\n * clients' flows on the same tables.\n *\n * Every token is an opaque random secret, stored only as its SHA-256 (DATA_MODEL §7.1): a copy of\n * the directory grants nothing. Access tokens last an hour; a refresh token rotates on every use,\n * returns the same successor for 30 s after it was used, so parallel refreshes don't collide, and a\n * use after that revokes its grant. The device page says that approving links a machine to the\n * account, and a new link is the hosted event `instance.linked`.\n */\nimport { createHash, randomBytes, randomInt, timingSafeEqual } from \"node:crypto\";\nimport { AccountId, HomeId, LinkId } from \"@mostra/protocol\";\nimport type { Ledger, LedgerDb } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport type { RemoteServerConfig } from \"./config.ts\";\n\n/** The CLI's client ID: a first-party public client (§18.5). */\nexport const CLI_CLIENT_ID = \"mostra-cli\";\n\n/** The device grant's type (RFC 8628 §3.4). */\nexport const DEVICE_GRANT = \"urn:ietf:params:oauth:grant-type:device_code\";\n\nconst ACCESS_TTL_MS = 60 * 60 * 1000;\nconst REFRESH_TTL_MS = 90 * 24 * 60 * 60 * 1000;\nconst DEVICE_TTL_MS = 10 * 60 * 1000;\nconst DEVICE_INTERVAL_S = 5;\nconst ROTATION_GRACE_MS = 30_000;\n\n/** User codes: eight letters a person can't confuse (RFC 8628 §6.1), shown as `ABCD-EFGH`. */\nconst USER_CODE_LETTERS = \"BCDFGHJKLMNPQRSTVWXZ\";\n\n/** What a valid access token names. */\nexport interface Authenticated {\n readonly accountId: string;\n readonly accountName: string | undefined;\n readonly grantId: string;\n readonly homeId: string;\n readonly linkId: string | undefined;\n readonly expiresAt: number;\n}\n\n/** An OAuth error answer (RFC 6749 §5.2, RFC 8628 §3.5). */\nexport interface OAuthError {\n readonly status: number;\n readonly error: string;\n readonly description: string;\n}\n\n/** The token endpoint's success answer. */\nexport interface TokenAnswer {\n readonly access_token: string;\n readonly token_type: \"Bearer\";\n readonly expires_in: number;\n readonly refresh_token: string;\n readonly scope: string;\n readonly mostra_account: { readonly id: string; readonly name?: string };\n readonly mostra_instance: string;\n /** Whether this instance is the account's default instance (D165 item 1b). */\n readonly mostra_default: boolean;\n /** The account's hosted home. */\n readonly mostra_home: string;\n}\n\n/** The SHA-256 of a secret, as the directory stores it. */\nexport function hashSecret(secret: string): string {\n return createHash(\"sha256\").update(secret).digest(\"hex\");\n}\n\nfunction secret(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\nfunction userCode(): string {\n let code = \"\";\n for (let index = 0; index < 8; index++)\n code += USER_CODE_LETTERS[randomInt(USER_CODE_LETTERS.length)];\n return code;\n}\n\n/** `abcd-efgh`, `ABCDEFGH` → `ABCDEFGH`. */\nfunction normalizeUserCode(input: string): string {\n return input.toUpperCase().replace(/[^A-Z]/g, \"\");\n}\n\n/** The device grant's state, kept in its `token` row's `data_json`. */\ninterface DeviceState {\n readonly userCode: string;\n readonly status: \"pending\" | \"approved\" | \"denied\";\n readonly accountId?: string;\n readonly instance?: string;\n readonly name?: string;\n readonly lastPollAt?: number;\n /** The instance asked to become the account's default (`mostra login --default`). */\n readonly makeDefault?: boolean;\n}\n\n/** Options for {@link createAuthorization}. */\nexport interface AuthorizationOptions {\n readonly directory: Ledger;\n readonly config: RemoteServerConfig;\n readonly log: Log;\n readonly now?: () => number;\n /** How long an access token lasts; an hour unless tests shorten it. */\n readonly accessTtlMs?: number;\n /**\n * Called when an instance link was made or bound again (`instance.linked`, §18.5): the server\n * appends the event in the hosted home.\n */\n readonly linked?: (event: {\n readonly homeId: string;\n readonly linkId: string;\n readonly name: string;\n }) => void;\n}\n\n/** The authorization server. */\nexport interface Authorization {\n /** `POST /oauth/device`. */\n device(form: URLSearchParams): Record<string, unknown> | OAuthError;\n /** `POST /oauth/token`. */\n token(form: URLSearchParams): TokenAnswer | OAuthError;\n /** `POST /oauth/revoke` (RFC 7009): revokes the grant a token belongs to. */\n revoke(form: URLSearchParams): void;\n /** What a bearer token names, or `undefined` when it is unknown, expired or revoked. */\n authenticate(bearer: string): Authenticated | undefined;\n /** Whether a grant is still live (not revoked, its account active). */\n grantLive(grantId: string): boolean;\n /** The device page's state for a user code: pending, or why it can't be approved. */\n pendingCode(\n code: string,\n ): { readonly ok: true } | { readonly ok: false; readonly reason: string };\n /**\n * Approves or denies a device code as `person` (the development provider's name, or WP-30's\n * signed-in identity), recording the account's consent for the CLI.\n */\n decide(input: {\n readonly code: string;\n readonly approve: boolean;\n readonly identity: {\n readonly provider: string;\n readonly subject: string;\n readonly name?: string;\n };\n }): { readonly ok: true } | { readonly ok: false; readonly reason: string };\n /** The verification address people open. */\n readonly verificationUri: string;\n}\n\nfunction oauthError(status: number, error: string, description: string): OAuthError {\n return { status, error, description };\n}\n\n/** Creates the authorization server over the server's directory. */\nexport function createAuthorization(options: AuthorizationOptions): Authorization {\n const { directory, config, log } = options;\n const now = options.now ?? (() => Date.now());\n const accessTtlMs = options.accessTtlMs ?? ACCESS_TTL_MS;\n const iso = (ms: number): string => new Date(ms).toISOString();\n const verificationUri = `${config.apiOrigin}/device`;\n\n directory.write((db) => {\n db.run(\n \"INSERT OR IGNORE INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'cli', ?, ?)\",\n CLI_CLIENT_ID,\n JSON.stringify({ client_name: \"Mostra CLI\" }),\n iso(now()),\n );\n });\n\n const deviceRow = (db: LedgerDb, hash: string) =>\n db.get<{ data_json: string; expires_at: string }>(\n \"SELECT data_json, expires_at FROM token WHERE hash = ? AND kind = 'device'\",\n hash,\n );\n\n /** The account for a sign-in identity, made on the first sign-in. */\n const accountFor = (\n db: LedgerDb,\n identity: { provider: string; subject: string; name?: string },\n ): string => {\n const found = db.get<{ account_id: string }>(\n \"SELECT account_id FROM identity WHERE provider = ? AND subject = ?\",\n identity.provider,\n identity.subject,\n );\n if (found) return found.account_id;\n const account = AccountId.create();\n db.run(\n \"INSERT INTO account (id, name, status, created_at) VALUES (?, ?, 'active', ?)\",\n account,\n identity.name ?? null,\n iso(now()),\n );\n db.run(\n \"INSERT INTO identity (provider, subject, account_id, name, linked_at) VALUES (?, ?, ?, ?, ?)\",\n identity.provider,\n identity.subject,\n account,\n identity.name ?? null,\n iso(now()),\n );\n return account;\n };\n\n /** The account's hosted home, made on its first link (one home per owner per server). */\n const homeFor = (db: LedgerDb, account: string): string => {\n const found = db.get<{ id: string }>(\"SELECT id FROM home WHERE owner_account_id = ?\", account);\n if (found) return found.id;\n const home = HomeId.create();\n db.run(\n \"INSERT INTO home (id, owner_account_id, data_path, created_at) VALUES (?, ?, ?, ?)\",\n home,\n account,\n `homes/${home}`,\n iso(now()),\n );\n return home;\n };\n\n /** Makes or binds again the instance link a sign-in names. */\n const linkFor = (\n db: LedgerDb,\n account: string,\n home: string,\n wanted: string | undefined,\n name: string,\n ): string => {\n if (wanted !== undefined && LinkId.is(wanted)) {\n const row = db.get<{ account_id: string }>(\n \"SELECT account_id FROM instance_link WHERE id = ?\",\n wanted,\n );\n // A link is rebound only for its own account: another account's ID names nothing here.\n if (row?.account_id === account) {\n db.run(\"UPDATE instance_link SET revoked_at = NULL, name = ? WHERE id = ?\", name, wanted);\n return wanted;\n }\n }\n const link = LinkId.create();\n const first =\n db.get<{ n: number }>(\"SELECT COUNT(*) AS n FROM instance_link WHERE account_id = ?\", account)\n ?.n === 0;\n db.run(\n \"INSERT INTO instance_link (id, account_id, home_id, name, is_default, relay_high, linked_at) VALUES (?, ?, ?, ?, ?, 0, ?)\",\n link,\n account,\n home,\n name,\n first ? 1 : 0,\n iso(now()),\n );\n return link;\n };\n\n /** Issues an access and a refresh token for a grant. */\n const issue = (db: LedgerDb, grantId: string): { access: string; refresh: string } => {\n const access = secret();\n const refresh = secret();\n db.run(\n \"INSERT INTO token (hash, grant_id, kind, expires_at) VALUES (?, ?, 'access', ?)\",\n hashSecret(access),\n grantId,\n iso(now() + accessTtlMs),\n );\n db.run(\n \"INSERT INTO token (hash, grant_id, kind, expires_at) VALUES (?, ?, 'refresh', ?)\",\n hashSecret(refresh),\n grantId,\n iso(now() + REFRESH_TTL_MS),\n );\n return { access, refresh };\n };\n\n const answer = (\n db: LedgerDb,\n grantId: string,\n tokens: { access: string; refresh: string },\n ): TokenAnswer => {\n const row = db.get<{\n account_id: string;\n link_id: string | null;\n name: string | null;\n is_default: number | null;\n home_id: string | null;\n }>(\n `SELECT g.account_id, g.link_id, a.name, l.is_default, l.home_id\n FROM \"grant\" g JOIN account a ON a.id = g.account_id\n LEFT JOIN instance_link l ON l.id = g.link_id WHERE g.id = ?`,\n grantId,\n );\n if (!row) throw new Error(\"grant vanished\");\n return {\n access_token: tokens.access,\n token_type: \"Bearer\",\n expires_in: Math.max(1, Math.floor(accessTtlMs / 1000)),\n refresh_token: tokens.refresh,\n scope: \"mostra\",\n mostra_account: { id: row.account_id, ...(row.name !== null ? { name: row.name } : {}) },\n mostra_instance: row.link_id ?? \"\",\n mostra_default: row.is_default === 1,\n mostra_home: row.home_id ?? \"\",\n };\n };\n\n /**\n * The successors of refresh tokens used in the last 30 s, by the used token's hash: kept in\n * memory only, so the directory never holds a usable secret. After a restart inside the grace, a\n * repeated refresh is refused without revoking anything; the client still holds its successor.\n */\n const recent = new Map<\n string,\n { readonly tokens: { access: string; refresh: string }; readonly at: number }\n >();\n const forgetOld = (): void => {\n for (const [hash, entry] of recent)\n if (now() - entry.at > ROTATION_GRACE_MS) recent.delete(hash);\n };\n\n const grantLiveIn = (db: LedgerDb, grantId: string): boolean => {\n const row = db.get<{ revoked_at: string | null; status: string }>(\n 'SELECT g.revoked_at, a.status FROM \"grant\" g JOIN account a ON a.id = g.account_id WHERE g.id = ?',\n grantId,\n );\n return row !== undefined && row.revoked_at === null && row.status === \"active\";\n };\n\n return {\n verificationUri,\n\n device(form) {\n if (form.get(\"client_id\") !== CLI_CLIENT_ID) {\n return oauthError(401, \"invalid_client\", \"Only the Mostra CLI uses the device grant here.\");\n }\n const scope = form.get(\"scope\") ?? \"mostra\";\n if (!scope.split(\" \").every((part) => part === \"mostra\" || part === \"offline_access\")) {\n return oauthError(400, \"invalid_scope\", \"The only scope is mostra.\");\n }\n const deviceCode = secret();\n const code = userCode();\n const instance = form.get(\"mostra_instance\") ?? undefined;\n const name = (form.get(\"mostra_name\") ?? \"\").slice(0, 128) || \"Mostra instance\";\n const state: DeviceState = {\n userCode: code,\n status: \"pending\",\n name,\n ...(instance !== undefined ? { instance } : {}),\n ...(form.get(\"mostra_default\") === \"1\" ? { makeDefault: true } : {}),\n };\n directory.write((db) =>\n db.run(\n \"INSERT INTO token (hash, kind, expires_at, data_json) VALUES (?, 'device', ?, ?)\",\n hashSecret(deviceCode),\n iso(now() + DEVICE_TTL_MS),\n JSON.stringify(state),\n ),\n );\n const shown = `${code.slice(0, 4)}-${code.slice(4)}`;\n log.info(\"auth.device_started\", {});\n return {\n device_code: deviceCode,\n user_code: shown,\n verification_uri: verificationUri,\n verification_uri_complete: `${verificationUri}?user_code=${shown}`,\n expires_in: Math.floor(DEVICE_TTL_MS / 1000),\n interval: DEVICE_INTERVAL_S,\n };\n },\n\n token(form) {\n const grantType = form.get(\"grant_type\");\n if (form.get(\"client_id\") !== CLI_CLIENT_ID) {\n return oauthError(401, \"invalid_client\", \"Unknown client.\");\n }\n if (grantType === DEVICE_GRANT) {\n const deviceCode = form.get(\"device_code\") ?? \"\";\n const hash = hashSecret(deviceCode);\n return directory.write((db): TokenAnswer | OAuthError => {\n const row = deviceRow(db, hash);\n if (!row) return oauthError(400, \"invalid_grant\", \"Unknown device code.\");\n if (Date.parse(row.expires_at) <= now()) {\n return oauthError(400, \"expired_token\", \"The code expired; sign in again.\");\n }\n const state = JSON.parse(row.data_json) as DeviceState;\n if (state.status === \"denied\") {\n return oauthError(400, \"access_denied\", \"The sign-in was refused.\");\n }\n if (state.status === \"pending\") {\n const tooSoon =\n state.lastPollAt !== undefined &&\n now() - state.lastPollAt < DEVICE_INTERVAL_S * 1000 - 250;\n db.run(\n \"UPDATE token SET data_json = ? WHERE hash = ?\",\n JSON.stringify({ ...state, lastPollAt: now() }),\n hash,\n );\n return tooSoon\n ? oauthError(400, \"slow_down\", \"Poll less often.\")\n : oauthError(400, \"authorization_pending\", \"Waiting for the person to approve.\");\n }\n // Approved: one grant, once. The device code is spent here.\n const account = state.accountId as string;\n const home = homeFor(db, account);\n const link = linkFor(db, account, home, state.instance, state.name ?? \"Mostra instance\");\n // `mostra login --default` makes this instance the account's default (D165 item 1b):\n // chat-host authoring goes to it. One default per account (a unique index).\n if (state.makeDefault === true) {\n db.run(\n \"UPDATE instance_link SET is_default = 0 WHERE account_id = ? AND id != ?\",\n account,\n link,\n );\n db.run(\"UPDATE instance_link SET is_default = 1 WHERE id = ?\", link);\n }\n const grantId = `grt_${randomBytes(16).toString(\"hex\")}`;\n db.run(\n 'INSERT INTO \"grant\" (id, account_id, client_id, scope, resource, link_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',\n grantId,\n account,\n CLI_CLIENT_ID,\n \"mostra\",\n `${config.apiOrigin}/host`,\n link,\n iso(now()),\n );\n db.run(\"DELETE FROM token WHERE hash = ?\", hash);\n const tokens = issue(db, grantId);\n setImmediate(() =>\n options.linked?.({ homeId: home, linkId: link, name: state.name ?? \"\" }),\n );\n log.info(\"auth.linked\", { account, home, link });\n return answer(db, grantId, tokens);\n });\n }\n if (grantType === \"refresh_token\") {\n const presented = form.get(\"refresh_token\") ?? \"\";\n const hash = hashSecret(presented);\n return directory.write((db): TokenAnswer | OAuthError => {\n const row = db.get<{\n grant_id: string;\n expires_at: string;\n used_at: string | null;\n }>(\n \"SELECT grant_id, expires_at, used_at FROM token WHERE hash = ? AND kind = 'refresh'\",\n hash,\n );\n if (!row || !grantLiveIn(db, row.grant_id)) {\n return oauthError(\n 400,\n \"invalid_grant\",\n \"The refresh token isn't valid; sign in again.\",\n );\n }\n if (Date.parse(row.expires_at) <= now()) {\n return oauthError(400, \"invalid_grant\", \"The refresh token expired; sign in again.\");\n }\n if (row.used_at !== null) {\n const used = Date.parse(row.used_at);\n forgetOld();\n if (now() - used <= ROTATION_GRACE_MS) {\n // A parallel refresh within the grace: the same successor (§18.5).\n const kept = recent.get(hash);\n if (kept) return answer(db, row.grant_id, kept.tokens);\n return oauthError(\n 400,\n \"invalid_grant\",\n \"This refresh token was just used; use its successor.\",\n );\n }\n // A refresh token used again after its grace: someone else holds it. The grant goes.\n db.run('UPDATE \"grant\" SET revoked_at = ? WHERE id = ?', iso(now()), row.grant_id);\n log.warn(\"auth.refresh_reused\", { grant: row.grant_id });\n return oauthError(\n 400,\n \"invalid_grant\",\n \"The refresh token was used before; sign in again.\",\n );\n }\n const tokens = issue(db, row.grant_id);\n db.run(\n \"UPDATE token SET used_at = ?, successor_hash = ? WHERE hash = ?\",\n iso(now()),\n hashSecret(tokens.refresh),\n hash,\n );\n forgetOld();\n recent.set(hash, { tokens, at: now() });\n return answer(db, row.grant_id, tokens);\n });\n }\n return oauthError(400, \"unsupported_grant_type\", \"Use the device grant or a refresh token.\");\n },\n\n revoke(form) {\n const presented = form.get(\"token\") ?? \"\";\n const hash = hashSecret(presented);\n directory.write((db) => {\n const row = db.get<{ grant_id: string | null }>(\n \"SELECT grant_id FROM token WHERE hash = ?\",\n hash,\n );\n if (row?.grant_id) {\n db.run(\n 'UPDATE \"grant\" SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL',\n iso(now()),\n row.grant_id,\n );\n log.info(\"auth.revoked\", { grant: row.grant_id });\n }\n });\n },\n\n authenticate(bearer) {\n if (bearer.length < 20 || bearer.length > 200) return undefined;\n const hash = hashSecret(bearer);\n return directory.read((db) => {\n const row = db.get<{\n hash: string;\n expires_at: string;\n grant_id: string;\n account_id: string;\n link_id: string | null;\n name: string | null;\n }>(\n `SELECT t.hash, t.expires_at, t.grant_id, g.account_id, g.link_id, a.name\n FROM token t JOIN \"grant\" g ON g.id = t.grant_id JOIN account a ON a.id = g.account_id\n WHERE t.hash = ? AND t.kind = 'access'`,\n hash,\n );\n if (!row) return undefined;\n // Constant-time on what was found, though the lookup was by hash already.\n if (!timingSafeEqual(Buffer.from(row.hash), Buffer.from(hash))) return undefined;\n const expiresAt = Date.parse(row.expires_at);\n if (expiresAt <= now() || !grantLiveIn(db, row.grant_id)) return undefined;\n const home = db.get<{ id: string }>(\n \"SELECT id FROM home WHERE owner_account_id = ?\",\n row.account_id,\n );\n if (!home) return undefined;\n return {\n accountId: row.account_id,\n accountName: row.name ?? undefined,\n grantId: row.grant_id,\n homeId: home.id,\n linkId: row.link_id ?? undefined,\n expiresAt,\n };\n });\n },\n\n grantLive(grantId) {\n return directory.read((db) => grantLiveIn(db, grantId));\n },\n\n pendingCode(code) {\n const wanted = normalizeUserCode(code);\n return directory.read((db) => {\n const rows = db.all<{ data_json: string; expires_at: string }>(\n \"SELECT data_json, expires_at FROM token WHERE kind = 'device' AND expires_at > ?\",\n iso(now()),\n );\n const row = rows.find(\n (candidate) => (JSON.parse(candidate.data_json) as DeviceState).userCode === wanted,\n );\n if (!row) return { ok: false as const, reason: \"That code is unknown or has expired.\" };\n const state = JSON.parse(row.data_json) as DeviceState;\n return state.status === \"pending\"\n ? { ok: true as const }\n : { ok: false as const, reason: \"That code was already used.\" };\n });\n },\n\n decide(input) {\n const wanted = normalizeUserCode(input.code);\n return directory.write((db) => {\n const rows = db.all<{ hash: string; data_json: string }>(\n \"SELECT hash, data_json FROM token WHERE kind = 'device' AND expires_at > ?\",\n iso(now()),\n );\n const row = rows.find(\n (candidate) => (JSON.parse(candidate.data_json) as DeviceState).userCode === wanted,\n );\n if (!row) return { ok: false as const, reason: \"That code is unknown or has expired.\" };\n const state = JSON.parse(row.data_json) as DeviceState;\n if (state.status !== \"pending\")\n return { ok: false as const, reason: \"That code was already used.\" };\n if (!input.approve) {\n db.run(\n \"UPDATE token SET data_json = ? WHERE hash = ?\",\n JSON.stringify({ ...state, status: \"denied\" }),\n row.hash,\n );\n return { ok: true as const };\n }\n const account = accountFor(db, input.identity);\n db.run(\n \"INSERT INTO consent (account_id, client_id, granted_at) VALUES (?, ?, ?) ON CONFLICT (account_id, client_id) DO UPDATE SET revoked_at = NULL\",\n account,\n CLI_CLIENT_ID,\n iso(now()),\n );\n db.run(\n \"UPDATE token SET data_json = ? WHERE hash = ?\",\n JSON.stringify({ ...state, status: \"approved\", accountId: account }),\n row.hash,\n );\n return { ok: true as const };\n });\n },\n };\n}\n","/**\n * A remote server's directory ledger, `server.sqlite` (DATA_MODEL §7.1): what spans hosted homes,\n * and only that. Accounts and their sign-in identities, the homes and the instances linked to\n * them, the hosted routes and every label ever issued, which home holds which version file, and\n * the authorization server's clients, grants and tokens (stored only as SHA-256 hashes).\n */\nimport type { Migration } from \"../ledger/index.ts\";\n\n/** The server directory's migrations: their own list, apart from a home's. */\nexport const SERVER_MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n name: \"server directory\",\n up(db) {\n db.exec(`\n CREATE TABLE account (\n id TEXT PRIMARY KEY,\n name TEXT,\n status TEXT NOT NULL CHECK (status IN ('active', 'suspended')),\n created_at TEXT NOT NULL\n );\n CREATE TABLE identity (\n provider TEXT NOT NULL,\n subject TEXT NOT NULL,\n account_id TEXT NOT NULL REFERENCES account(id),\n email TEXT,\n name TEXT,\n linked_at TEXT NOT NULL,\n PRIMARY KEY (provider, subject)\n );\n CREATE TABLE home (\n id TEXT PRIMARY KEY,\n owner_account_id TEXT NOT NULL UNIQUE REFERENCES account(id),\n data_path TEXT NOT NULL,\n created_at TEXT NOT NULL,\n suspended_at TEXT\n );\n CREATE TABLE instance_link (\n id TEXT PRIMARY KEY,\n account_id TEXT NOT NULL REFERENCES account(id),\n home_id TEXT NOT NULL REFERENCES home(id),\n name TEXT NOT NULL,\n is_default INTEGER NOT NULL DEFAULT 0,\n relay_high INTEGER NOT NULL DEFAULT 0,\n linked_at TEXT NOT NULL,\n revoked_at TEXT\n );\n CREATE UNIQUE INDEX instance_link_default ON instance_link(account_id) WHERE is_default = 1;\n CREATE TABLE home_cursor (\n home_id TEXT PRIMARY KEY REFERENCES home(id),\n incarnation TEXT NOT NULL,\n high_cursor INTEGER NOT NULL,\n relay_high INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE artifact_route (\n id TEXT PRIMARY KEY,\n home_id TEXT NOT NULL REFERENCES home(id),\n artifact_id TEXT NOT NULL,\n owner_link_id TEXT NOT NULL REFERENCES instance_link(id),\n label TEXT NOT NULL UNIQUE,\n created_at TEXT NOT NULL,\n UNIQUE (home_id, artifact_id)\n );\n CREATE TABLE label_issued (\n label TEXT PRIMARY KEY,\n home_id TEXT NOT NULL,\n route_id TEXT,\n kind TEXT NOT NULL CHECK (kind IN ('server', 'operator')),\n issued_at TEXT NOT NULL\n );\n -- A label is issued once, forever: never deleted, never moved to another home.\n CREATE TRIGGER label_issued_kept BEFORE DELETE ON label_issued\n BEGIN\n SELECT RAISE(ABORT, 'an issued label is kept forever');\n END;\n CREATE TRIGGER label_issued_fixed BEFORE UPDATE ON label_issued\n WHEN NEW.label IS NOT OLD.label OR NEW.home_id IS NOT OLD.home_id\n BEGIN\n SELECT RAISE(ABORT, 'an issued label never moves');\n END;\n CREATE TABLE home_file (\n home_id TEXT NOT NULL REFERENCES home(id),\n sha256 TEXT NOT NULL,\n PRIMARY KEY (home_id, sha256)\n );\n CREATE TABLE file_ref (\n sha256 TEXT PRIMARY KEY,\n homes INTEGER NOT NULL CHECK (homes >= 0),\n unreferenced_at TEXT\n );\n CREATE TABLE oauth_client (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL CHECK (kind IN ('metadata', 'registered', 'shell', 'cli')),\n metadata_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n last_used_at TEXT\n );\n CREATE TABLE consent (\n account_id TEXT NOT NULL REFERENCES account(id),\n client_id TEXT NOT NULL REFERENCES oauth_client(id),\n granted_at TEXT NOT NULL,\n revoked_at TEXT,\n PRIMARY KEY (account_id, client_id)\n );\n CREATE TABLE sender_shown (\n account_id TEXT NOT NULL,\n home_id TEXT NOT NULL,\n at TEXT NOT NULL,\n PRIMARY KEY (account_id, home_id)\n );\n CREATE TABLE \"grant\" (\n id TEXT PRIMARY KEY,\n account_id TEXT NOT NULL REFERENCES account(id),\n client_id TEXT NOT NULL REFERENCES oauth_client(id),\n scope TEXT NOT NULL,\n resource TEXT NOT NULL,\n link_id TEXT REFERENCES instance_link(id),\n created_at TEXT NOT NULL,\n revoked_at TEXT\n );\n CREATE TABLE token (\n hash TEXT PRIMARY KEY,\n grant_id TEXT REFERENCES \"grant\"(id),\n kind TEXT NOT NULL CHECK (kind IN ('access', 'refresh', 'device', 'code')),\n expires_at TEXT NOT NULL,\n used_at TEXT,\n successor_hash TEXT,\n data_json TEXT\n );\n CREATE TABLE outbound (\n id TEXT PRIMARY KEY,\n port TEXT NOT NULL CHECK (port IN ('metering', 'events')),\n payload_json TEXT NOT NULL,\n attempts INTEGER NOT NULL DEFAULT 0,\n next_attempt_at TEXT NOT NULL\n );\n `);\n },\n },\n];\n","/**\n * A remote server's data directory (DATA_MODEL §7.1) and its hosted homes (§7.2, D165 items 0b,\n * 6): the directory is refused on a network filesystem, held by `server.lock` so a second server\n * refuses it, and its directory ledger `server.sqlite` opens in WAL with normal locking. Each\n * hosted home opens on its first request (its own `home.lock`, its ledger in normal locking, so a\n * backup replicator can read it) and closes after it has been idle a while. Opening and closing one\n * home are serialized, so a home never has two writers in one process, and a request that meets a\n * home being closed waits for the close and opens it again (FAILURE_MODEL §11.2).\n */\nimport { randomBytes } from \"node:crypto\";\nimport { mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport {\n type HeldLock,\n holdLock,\n type Ledger,\n type LedgerOwner,\n openLedger,\n} from \"../ledger/index.ts\";\nimport type { Environment, Log } from \"../log.ts\";\nimport { networkFilesystem, ownedDirectory } from \"../platform/index.ts\";\nimport { SERVER_MIGRATIONS } from \"./directory.ts\";\n\n/** An open hosted home: its ledger, its lock, and whatever the server assembled over them. */\nexport interface OpenedHome<T> {\n readonly id: string;\n readonly dir: string;\n readonly ledger: Ledger;\n readonly incarnation: string;\n /** What the server built over the ledger (interaction, gateway routes, sessions). */\n readonly assembled: T;\n}\n\n/** What opens and closes the parts of a hosted home that live above its ledger. */\nexport interface HomeAssembler<T> {\n /** Builds a home's parts over its ledger, once it is open. */\n assemble(home: {\n readonly id: string;\n readonly dir: string;\n readonly ledger: Ledger;\n readonly incarnation: string;\n }): Promise<T>;\n /** Stops them, before the ledger closes. */\n disassemble(assembled: T): Promise<void>;\n /** Whether a home is in use now: a connection, a stream, a poll, a pending delivery, a waiting run. */\n busy(assembled: T): boolean;\n /** The home's incarnation now: a hosted home rotates it when its owner shows it was restored. */\n incarnation?(assembled: T): string;\n}\n\n/** The data directory, held. */\nexport interface DataDirectory<T> {\n readonly dir: string;\n readonly directory: Ledger;\n /** Opens a hosted home, or returns it when open; a request waits for a close in progress. */\n home(id: string): Promise<OpenedHome<T>>;\n /** The homes open now. */\n open(): readonly string[];\n /** Notes that a home was used now, so it isn't closed while used. */\n touch(id: string): void;\n /** Closes every home, then the directory, then releases the lock. */\n close(): Promise<void>;\n}\n\n/** Options for {@link openDataDirectory}. */\nexport interface DataDirectoryOptions<T> {\n readonly dir: string;\n readonly runtimeVersion: string;\n readonly owner: LedgerOwner;\n readonly log: Log;\n readonly env: Environment;\n readonly assembler: HomeAssembler<T>;\n /** Close a home this long after it was last used and nothing is busy. Default 10 minutes. */\n readonly idleCloseMs?: number;\n readonly walAutocheckpoint?: number;\n /**\n * Homes restored from a backup by hand (`--restored <homeId|all>`): each rotates its incarnation\n * when it first opens (INTERFACES §18.2).\n */\n readonly restored?: readonly string[];\n}\n\n/** A home's head and relay high-water mark, as `home_cursor` records them (DATA_MODEL §7.1). */\nfunction marksOf(ledger: Ledger): { readonly head: number; readonly relayHigh: number } {\n return ledger.read((db) => ({\n head: db.get<{ head: number | null }>(\"SELECT MAX(cursor) AS head FROM event\")?.head ?? 0,\n relayHigh:\n db.get<{ high: number | null }>(\"SELECT MAX(relay_seq) AS high FROM relay_run\")?.high ?? 0,\n }));\n}\n\n/** A fresh incarnation, written in the one transaction that rotates it (DATA_MODEL §7.2). */\nexport function rotateIncarnation(ledger: Ledger): string {\n const fresh = randomBytes(16).toString(\"hex\");\n ledger.write((db) => db.run(\"UPDATE home_meta SET incarnation = ? WHERE id = 1\", fresh));\n return fresh;\n}\n\nfunction locked(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_HOME_LOCKED\", { message }));\n}\n\n/**\n * Refuses a data directory on a network filesystem (`MOSTRA_HOME_NETWORK_FILESYSTEM`), before\n * anything in it is opened. `MOSTRA_TEST_NETWORK_FILESYSTEM` names a directory tests treat as one,\n * since no test machine mounts NFS.\n */\nfunction refuseNetworkFilesystem(dir: string, env: Environment): void {\n const testing = env[\"MOSTRA_TEST_NETWORK_FILESYSTEM\"];\n const found =\n testing !== undefined && testing !== \"\" && dir.startsWith(testing)\n ? \"nfs (test)\"\n : networkFilesystem(dir);\n if (found !== undefined) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOME_NETWORK_FILESYSTEM\", {\n message: `The data directory ${dir} is on a network filesystem (${found}); a remote server's homes need a local disk.`,\n }),\n );\n }\n}\n\n/** Opens and holds a server's data directory. Throws `MOSTRA_HOME_LOCKED` when another server holds it. */\nexport async function openDataDirectory<T>(\n options: DataDirectoryOptions<T>,\n): Promise<DataDirectory<T>> {\n const { dir, log } = options;\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n ownedDirectory(dir);\n refuseNetworkFilesystem(dir, options.env);\n const serverLock = holdLock(join(dir, \"server.lock\"), options.owner);\n if (!serverLock) {\n throw locked(`Another server process holds the data directory ${dir} (server.lock).`);\n }\n let directory: Ledger;\n try {\n const opening = openLedger({\n storeDir: dir,\n fileName: \"server.sqlite\",\n runtimeVersion: options.runtimeVersion,\n owner: options.owner,\n log,\n migrations: SERVER_MIGRATIONS,\n locking: \"normal\",\n ...(options.walAutocheckpoint !== undefined\n ? { walAutocheckpoint: options.walAutocheckpoint }\n : {}),\n });\n if (!opening.ok) throw locked(`server.sqlite in ${dir} is locked by another process.`);\n directory = opening.ledger;\n } catch (error) {\n serverLock.release();\n throw error;\n }\n mkdirSync(join(dir, \"homes\"), { recursive: true, mode: 0o700 });\n mkdirSync(join(dir, \"files\"), { recursive: true, mode: 0o700 });\n mkdirSync(join(dir, \"keys\"), { recursive: true, mode: 0o700 });\n\n interface Entry {\n opening: Promise<OpenedHome<T>>;\n lock?: HeldLock;\n ledger?: Ledger;\n incarnation?: () => string;\n lastUsed: number;\n closing?: Promise<void>;\n }\n const entries = new Map<string, Entry>();\n /** `--restored`'s homes not opened since this server started. */\n const restores = new Set(options.restored ?? []);\n\n /** Writes a home's high-water marks, which a home opened below them was restored. */\n const recordCursor = (id: string, ledger: Ledger, incarnation: string): void => {\n const { head, relayHigh } = marksOf(ledger);\n directory.write((db) =>\n db.run(\n `INSERT INTO home_cursor (home_id, incarnation, high_cursor, relay_high, updated_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(home_id) DO UPDATE SET incarnation = excluded.incarnation,\n high_cursor = excluded.high_cursor, relay_high = excluded.relay_high,\n updated_at = excluded.updated_at`,\n id,\n incarnation,\n head,\n relayHigh,\n new Date().toISOString(),\n ),\n );\n };\n const idleCloseMs = options.idleCloseMs ?? 10 * 60_000;\n let closed = false;\n\n const openHome = async (id: string): Promise<OpenedHome<T>> => {\n const row = directory.read((db) =>\n db.get<{ data_path: string }>(\"SELECT data_path FROM home WHERE id = ?\", id),\n );\n if (!row) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", { message: `No hosted home ${id}.` }),\n );\n }\n const homeDir = join(dir, row.data_path);\n mkdirSync(homeDir, { recursive: true, mode: 0o700 });\n const lock = holdLock(join(homeDir, \"home.lock\"), options.owner);\n if (!lock) throw locked(`Another process holds the hosted home ${id} (home.lock).`);\n try {\n const opening = openLedger({\n storeDir: join(homeDir, \"store\"),\n runtimeVersion: options.runtimeVersion,\n owner: options.owner,\n log,\n locking: \"normal\",\n ...(options.walAutocheckpoint !== undefined\n ? { walAutocheckpoint: options.walAutocheckpoint }\n : {}),\n });\n if (!opening.ok) throw locked(`The hosted home ${id}'s ledger is locked by another process.`);\n const ledger = opening.ledger;\n const stored = ledger.write((db) => {\n const meta = db.get<{ incarnation: string }>(\n \"SELECT incarnation FROM home_meta WHERE id = 1\",\n );\n if (meta) return meta.incarnation;\n const fresh = randomBytes(16).toString(\"hex\");\n db.run(\n \"INSERT INTO home_meta (id, incarnation, created_at) VALUES (1, ?, ?)\",\n fresh,\n new Date().toISOString(),\n );\n return fresh;\n });\n // A home restored from a backup reuses cursors its owner may have copied: it rotates its\n // incarnation before it answers anyone, when restored by hand or when it opens below the\n // marks it reached (INTERFACES §18.2, FAILURE_MODEL §11.2).\n const recorded = directory.read((db) =>\n db.get<{ high_cursor: number; relay_high: number }>(\n \"SELECT high_cursor, relay_high FROM home_cursor WHERE home_id = ?\",\n id,\n ),\n );\n const marks = marksOf(ledger);\n const byHand = restores.has(id) || restores.has(\"all\");\n restores.delete(id);\n const below =\n recorded !== undefined &&\n (marks.head < recorded.high_cursor || marks.relayHigh < recorded.relay_high);\n const incarnation = byHand || below ? rotateIncarnation(ledger) : stored;\n if (incarnation !== stored) {\n log.warn(\"server.home_rotated\", { home: id, why: byHand ? \"restored\" : \"below-mark\" });\n }\n recordCursor(id, ledger, incarnation);\n try {\n const assembled = await options.assembler.assemble({\n id,\n dir: homeDir,\n ledger,\n incarnation,\n });\n const entry = entries.get(id);\n if (entry) {\n entry.lock = lock;\n entry.ledger = ledger;\n entry.incarnation = () => options.assembler.incarnation?.(assembled) ?? incarnation;\n }\n log.info(\"server.home_opened\", { home: id });\n return { id, dir: homeDir, ledger, incarnation, assembled };\n } catch (error) {\n ledger.close();\n throw error;\n }\n } catch (error) {\n lock.release();\n throw error;\n }\n };\n\n const closeHome = async (id: string, entry: Entry): Promise<void> => {\n const opened = await entry.opening.catch(() => undefined);\n if (opened) {\n try {\n recordCursor(id, opened.ledger, entry.incarnation?.() ?? opened.incarnation);\n } catch (error) {\n log.warn(\"server.home_cursor_failed\", { home: id, error });\n }\n await options.assembler\n .disassemble(opened.assembled)\n .catch((error: unknown) => log.warn(\"server.home_disassemble_failed\", { home: id, error }));\n opened.ledger.close();\n }\n entry.lock?.release();\n entries.delete(id);\n log.info(\"server.home_closed\", { home: id });\n };\n\n const sweep = setInterval(\n () => {\n const now = Date.now();\n for (const [id, entry] of entries) {\n if (entry.closing || now - entry.lastUsed < idleCloseMs) continue;\n void entry.opening.then(\n (opened) => {\n if (options.assembler.busy(opened.assembled) || entry.closing) return;\n if (Date.now() - entry.lastUsed < idleCloseMs) return;\n entry.closing = closeHome(id, entry);\n },\n () => {\n entries.delete(id);\n },\n );\n }\n },\n Math.min(30_000, Math.max(50, idleCloseMs / 4)),\n );\n sweep.unref();\n // At least every 10 s while a home is open (DATA_MODEL §7.1).\n const marker = setInterval(() => {\n for (const [id, entry] of entries) {\n if (!entry.ledger || entry.closing) continue;\n try {\n recordCursor(id, entry.ledger, entry.incarnation?.() ?? \"\");\n } catch (error) {\n log.warn(\"server.home_cursor_failed\", { home: id, error });\n }\n }\n }, 10_000);\n marker.unref();\n\n return {\n dir,\n directory,\n async home(id) {\n if (closed) throw locked(\"The server is stopping.\");\n for (;;) {\n const entry = entries.get(id);\n if (entry?.closing) {\n await entry.closing;\n continue;\n }\n if (entry) {\n entry.lastUsed = Date.now();\n return entry.opening;\n }\n const fresh: Entry = { opening: openHome(id), lastUsed: Date.now() };\n entries.set(id, fresh);\n fresh.opening.catch(() => {\n if (entries.get(id) === fresh) entries.delete(id);\n });\n return fresh.opening;\n }\n },\n open: () => [...entries.keys()],\n touch(id) {\n const entry = entries.get(id);\n if (entry) entry.lastUsed = Date.now();\n },\n async close() {\n if (closed) return;\n closed = true;\n clearInterval(sweep);\n clearInterval(marker);\n for (const [id, entry] of [...entries]) {\n entry.closing ??= closeHome(id, entry);\n await entry.closing;\n }\n directory.close();\n serverLock.release();\n },\n };\n}\n","/**\n * The relay on a hosted home (D117, D165 item 4; ARCHITECTURE §15.5, INTERFACES §18.3, FAILURE_MODEL\n * §11.1): a hosted page's runs and plain calls run on the artifact's owner instance, over that\n * instance's binding. The hosted home records each run as a local instance does, then sends it to\n * the owner, which records it under the same ID, runs it in its own pool with its own secrets and\n * reports its progress, log, result and end back (`relay/run.update`). While the owner is away a\n * run waits (`waiting`), as the artifact's offline policy says, in a capped queue that drains in\n * order at a bounded rate when the owner returns; after every reconnect, before anything drains,\n * the runs the owner accepted and hasn't finished are reconciled with it. A run whose end the owner\n * never reported within the offline limit becomes `unknown`, never `failed`, since it may have\n * taken effect; the owner's later report replaces it once.\n *\n * Plain calls aren't durable: they go out only while the owner is connected.\n */\nimport {\n ACTION_ARGS_MAX,\n ArtifactManifest,\n type Batches,\n type CallLine,\n checkArgumentFrames,\n createDiagnostic,\n durationMs,\n HOSTED_OFFLINE_LIMIT_DEFAULT,\n isFinalRunStatus,\n type JsonRpcParams,\n type PortRelayReconcileResult,\n portRelayCallMethod,\n portRelayCancelMethod,\n portRelayLiveMethod,\n portRelayReconcileMethod,\n portRelayRunMethod,\n RpcError,\n type RunState,\n relayCallBatchMethod,\n relayEffectMethod,\n relayLiveValueMethod,\n relayRunUpdateMethod,\n type ServerLiveValueParams,\n TALLY_LIVE_PREFIX,\n} from \"@mostra/protocol\";\nimport type { Actions } from \"../actions/index.ts\";\nimport {\n appendRunOutput,\n type EphemeralBus,\n finishRun,\n type Interaction,\n markRunning,\n markUnknown,\n markWaiting,\n type RunRow,\n runState,\n} from \"../interaction/index.ts\";\nimport type { Ledger, LedgerDb } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { handler, type MethodHandler, type Session } from \"../protocol-server/index.ts\";\n\n/** How long a relay port call may take: the owner answers once it recorded the run. */\nconst PORT_CALL_MS = 30_000;\n/** How long a run its connected owner never acknowledged waits before it is sent again. */\nconst RESEND_MS = PORT_CALL_MS + 5_000;\n/** Failures of the connection rather than answers of the owner: the run may yet be recorded. */\nconst TRANSPORT_FAILURES: ReadonlySet<string> = new Set([\n \"MOSTRA_HOST_CONNECTION_CLOSED\",\n \"MOSTRA_HOST_TIMEOUT\",\n]);\n/** The most waiting runs per artifact, by default (a server setting, D165 item 4). */\nexport const WAITING_RUNS_DEFAULT = 100;\n/** How many waiting runs go out per second per artifact when the owner returns, by default. */\nexport const DRAIN_PER_SECOND_DEFAULT = 2;\n\n/** A version's relay facts: its server functions and its offline policy (`hosted.offline`). */\ninterface RelayVersion {\n readonly functions: ReadonlySet<string>;\n readonly policy: \"queue\" | \"fail\";\n readonly limitMs: number;\n /** Who may trigger its relayed actions (`hosted.actions`, D159): default signed-in viewers. */\n readonly who: \"signed-in\" | \"link\";\n}\n\n/** Options for {@link createHostedRelay}. */\nexport interface HostedRelayOptions {\n readonly ledger: Ledger;\n readonly interaction: Interaction;\n readonly bus: EphemeralBus;\n readonly log: Log;\n /** The artifact's owner link (`lnk_`), the one instance its runs go to (D165 item 1b). */\n readonly ownerOf: (artifactId: string) => string | undefined;\n /** The open session of an owner link that registered `relay`, if one is open. */\n readonly sessionOf: (linkId: string) => number | undefined;\n /** Calls a port method on one session. */\n readonly call: (\n session: number,\n method: string,\n params: JsonRpcParams,\n timeoutMs: number,\n ) => Promise<unknown>;\n /** The server functions a version's registry lists. */\n readonly functions: (versionId: string) => ReadonlySet<string>;\n readonly waitingRunsPerArtifact?: number;\n readonly drainPerSecond?: number;\n /**\n * Relayed runs and calls per link (`rateLimits.perLink.relayedRuns`, D159): past it a page is\n * refused before anything is recorded or relayed.\n */\n readonly perLink?: { readonly count: number; readonly perMs: number } | undefined;\n /** How often waiting and unacknowledged runs are checked against their limits; default 1 s. */\n readonly sweepMs?: number;\n /** An artifact's latest version here, whose producers its viewers want. */\n readonly latestVersion?: (artifactId: string) => string | undefined;\n /** Keeps a value an owner's producer made (`relay/live.value`). */\n readonly storeLive?: (\n artifactId: string,\n versionId: string,\n produced: ServerLiveValueParams,\n ) => { readonly revision?: string };\n /** How often viewers' interest in live sources is renewed with the owner; default 20 s. */\n readonly liveRenewMs?: number;\n readonly now?: () => number;\n}\n\n/** The relay: the gateway's actions on a hosted home, and the owner's methods. */\nexport interface HostedRelay extends Pick<Actions, \"call\" | \"startRun\" | \"attach\" | \"cancel\"> {\n /** `relay/run.update` and `relay/call.batch`, for the hosted home's protocol server. */\n methods(): MethodHandler[];\n /** An owner session opened: reconcile its accepted runs, then resend and drain (§18.3). */\n connected(session: Session): void;\n /** A session closed: its calls end, its runs show their owner unreachable. */\n disconnected(session: Session): void;\n /** Whether runs wait or calls run: the home stays open while they do. */\n busy(): boolean;\n /** A page read live sources: their producers are asked for on the owner now. */\n liveWanted(artifactId: string): void;\n /** Whether an artifact's owner is out of reach, so its live values can't be refreshed. */\n ownerOffline(artifactId: string): boolean;\n stop(): void;\n}\n\n/** A `relay_run` row. */\ninterface RelayRow {\n readonly run_id: string;\n readonly owner_link_id: string;\n readonly relay_seq: number;\n readonly attempt: number;\n readonly sent_at: string | null;\n readonly accepted_at: string | null;\n readonly owner_heard_at: string | null;\n readonly offline_limit_at: string;\n readonly last_seq: number;\n readonly cancel_requested_at: string | null;\n}\n\n/** A relayed plain call in flight: its lines as they come. */\ninterface PendingCall {\n readonly session: number;\n readonly lines: CallLine[];\n wake?: () => void;\n ended: boolean;\n lastSeq: number;\n}\n\nfunction failed(code: string, message: string): RpcError {\n return new RpcError(createDiagnostic(code as never, { message }));\n}\n\nconst iso = (ms: number): string => new Date(ms).toISOString();\n\n/** Creates a hosted home's relay. */\nexport function createHostedRelay(options: HostedRelayOptions): HostedRelay {\n const { ledger, interaction, bus, log } = options;\n const now = options.now ?? Date.now;\n const cap = options.waitingRunsPerArtifact ?? WAITING_RUNS_DEFAULT;\n const drainPerSecond = Math.max(1, options.drainPerSecond ?? DRAIN_PER_SECOND_DEFAULT);\n const calls = new Map<string, PendingCall>();\n /** Owner links whose reconcile finished on their current session: only then may runs go out. */\n const ready = new Map<string, number>();\n /** Runs being sent now, so a sweep or a second drain never sends one twice at once. */\n const sending = new Set<string>();\n /** When each run was last sent, for the sweep's resend while the owner stays connected. */\n const lastTry = new Map<string, number>();\n const draining = new Set<string>();\n const versions = new Map<string, RelayVersion>();\n /**\n * The highest relay sequence each owner link's ledger has accepted, as its sessions report it\n * (`relayMark`): a home restored from a backup continues above it, so no sequence is reused.\n */\n const marks = new Map<string, number>();\n /** The relay mark each open owner session reported, for a resume run again for it. */\n const sessionMarks = new Map<number, number>();\n /** A resume that failed is tried again for its session, with backoff (Opus review of WP-29, 1). */\n const retries = new Map<number, { timer: ReturnType<typeof setTimeout>; attempt: number }>();\n let stopped = false;\n\n const versionOf = (versionId: string): RelayVersion => {\n const known = versions.get(versionId);\n if (known) return known;\n const manifestJson = ledger.read(\n (db) =>\n db.get<{ manifest_json: string }>(\n \"SELECT manifest_json FROM version WHERE id = ?\",\n versionId,\n )?.manifest_json,\n );\n const manifest = manifestJson\n ? ArtifactManifest.safeParse(JSON.parse(manifestJson)).data\n : undefined;\n const offline = manifest?.hosted?.offline;\n const version: RelayVersion = {\n functions: options.functions(versionId),\n policy: offline?.actions ?? \"queue\",\n limitMs: durationMs(offline?.limit ?? HOSTED_OFFLINE_LIMIT_DEFAULT),\n who: manifest?.hosted?.actions ?? \"signed-in\",\n };\n versions.set(versionId, version);\n return version;\n };\n\n const functionOf = (versionId: string, fnId: string): RelayVersion => {\n const version = versionOf(versionId);\n if (!version.functions.has(fnId)) {\n throw failed(\n \"MOSTRA_ACTION_UNKNOWN_FUNCTION\",\n `This version has no server function ${fnId.slice(0, 200)}.`,\n );\n }\n return version;\n };\n\n /**\n * D159: a relayed action runs on its owner's machine with its owner's secrets, so by default\n * only a signed-in viewer or an expected respondent (a link minted for a named person) may\n * trigger one; `hosted.actions: \"link\"` opens it to anyone holding a link with the scope.\n * Refused before anything is recorded or relayed.\n */\n const mayTrigger = (viewerId: string, version: RelayVersion): void => {\n if (version.who === \"link\") return;\n const viewer = interaction.viewer(viewerId);\n const named =\n viewer.kind === \"token\" && viewer.ref !== undefined && !viewer.ref.startsWith(\"link:\");\n if (viewer.kind === \"account\" || named) return;\n throw failed(\n \"MOSTRA_REMOTE_SIGN_IN_REQUIRED\",\n \"Only signed-in viewers can run this page's actions; sign in, or ask its owner for a link of your own.\",\n );\n };\n\n /** Each link's recent relayed runs and calls, for the per-link limit. */\n const linkUses = new Map<string, number[]>();\n /**\n * Counts a relayed run or call against its link (D159), refusing it past the limit with\n * `MOSTRA_REMOTE_RATE_LIMITED` and when to try again. A request that joins a run already\n * recorded (its client key, or its key) starts nothing, so it is never counted.\n */\n const limitLink = (\n tokenId: string | undefined,\n artifactId?: string,\n input?: {\n readonly clientKey: string;\n readonly key?: string | undefined;\n readonly fnId: string;\n },\n ): void => {\n const limit = options.perLink;\n if (!limit || tokenId === undefined) return;\n if (artifactId !== undefined && input !== undefined) {\n const joins = ledger.read(\n (db) =>\n db.get(\n \"SELECT 1 FROM action_run WHERE artifact_id = ? AND (client_key = ? OR (key IS NOT NULL AND key = ? AND action = ?))\",\n artifactId,\n input.clientKey,\n input.key ?? null,\n input.fnId,\n ) !== undefined,\n );\n if (joins) return;\n }\n const at = now();\n const recent = (linkUses.get(tokenId) ?? []).filter((used) => at - used < limit.perMs);\n if (recent.length >= limit.count) {\n const retryAfter = Math.max(1, Math.ceil(((recent[0] as number) + limit.perMs - at) / 1000));\n const error = failed(\n \"MOSTRA_REMOTE_RATE_LIMITED\",\n `This link ran ${limit.count} actions recently; try again in ${retryAfter} s.`,\n ) as RpcError & { retryAfter?: number };\n error.retryAfter = retryAfter;\n linkUses.set(tokenId, recent);\n throw error;\n }\n recent.push(at);\n linkUses.set(tokenId, recent);\n };\n\n const checkArgs = (args: Batches): void => {\n if (JSON.stringify(args).length > ACTION_ARGS_MAX) {\n throw failed(\n \"MOSTRA_ACTION_TOO_LARGE\",\n \"The serialized arguments are larger than 16 MiB; pass less data, such as identifiers.\",\n );\n }\n try {\n checkArgumentFrames(args);\n } catch (error) {\n throw failed(\"MOSTRA_ACTION_UNSERIALIZABLE\", (error as Error).message);\n }\n };\n\n /** Tells a run's views what changed: the state as a delta from nothing held. */\n const publish = (state: RunState, artifactId: string): void =>\n bus.publishRun(artifactId, {\n kind: \"run\",\n run: {\n runId: state.runId,\n status: state.status,\n ...(state.reason !== undefined ? { reason: state.reason } : {}),\n ...(state.progress ? { progress: state.progress } : {}),\n logFrom: state.logFrom ?? 0,\n log: state.log,\n batchFrom: state.batchFrom ?? 0,\n batches: state.batches,\n ...(state.error ? { error: state.error } : {}),\n ...(state.finishedAt ? { finishedAt: state.finishedAt } : {}),\n },\n });\n\n const relayRow = (db: LedgerDb, runId: string): RelayRow | undefined =>\n db.get<RelayRow>(\"SELECT * FROM relay_run WHERE run_id = ?\", runId);\n const runRow = (db: LedgerDb, runId: string): RunRow | undefined =>\n db.get<RunRow>(\"SELECT * FROM action_run WHERE id = ?\", runId);\n\n /** Whether the owner of a run's artifact is connected and reconciled. */\n const sessionFor = (linkId: string): number | undefined => {\n const session = options.sessionOf(linkId);\n return session !== undefined && ready.get(linkId) === session ? session : undefined;\n };\n\n /** The owner never heard the run: it ends `failed` with reason `owner-offline` (never sent). */\n const endOffline = (runId: string): void => {\n const state = ledger.write((db) => {\n const row = runRow(db, runId);\n if (!row || isFinalRunStatus(row.status) || row.status === \"unknown\") return undefined;\n const ended = finishRun(db, runId, {\n status: \"failed\",\n reason: \"owner-offline\",\n error: {\n code: \"MOSTRA_REMOTE_OWNER_OFFLINE\",\n message: \"The page's owner was offline, so the action never ran.\",\n },\n });\n return ended ? { state: runState(db, ended), artifactId: ended.artifact_id } : undefined;\n });\n if (state) publish(state.state, state.artifactId);\n };\n\n /** Sends one run to its owner; the answer records that the owner holds it. */\n const send = async (runId: string, session: number): Promise<void> => {\n if (sending.has(runId)) return;\n const prepared = ledger.write((db) => {\n const relay = relayRow(db, runId);\n const row = runRow(db, runId);\n if (!relay || !row || isFinalRunStatus(row.status) || row.status === \"unknown\")\n return undefined;\n // A run never sent whose offline limit passed never happens, however the owner came back\n // (a home closed while it waited ran no sweep): it ends `failed`, `owner-offline` (Opus\n // review of WP-29, 7).\n if (relay.sent_at === null && Date.parse(relay.offline_limit_at) <= now()) return \"expired\";\n db.run(\n \"UPDATE relay_run SET attempt = attempt + 1, sent_at = COALESCE(sent_at, ?) WHERE run_id = ?\",\n iso(now()),\n runId,\n );\n return { relay, row };\n });\n if (!prepared) return;\n if (prepared === \"expired\") {\n endOffline(runId);\n return;\n }\n const { relay, row } = prepared;\n sending.add(runId);\n try {\n const viewer = row.viewer_id ? interaction.viewer(row.viewer_id) : undefined;\n await options.call(\n session,\n portRelayRunMethod.method,\n {\n runId,\n seq: relay.relay_seq,\n artifactId: row.artifact_id,\n versionId: row.version_id,\n fnId: row.action,\n args: JSON.parse(row.args_json) as Batches,\n ...(row.key !== null ? { key: row.key } : {}),\n ...(viewer\n ? { viewer: { id: viewer.id, ...(viewer.name ? { name: viewer.name } : {}) } }\n : {}),\n ...(row.view_id !== null ? { viewId: row.view_id } : {}),\n },\n PORT_CALL_MS,\n );\n const at = iso(now());\n const cancelled = ledger.write((db) => {\n db.run(\n \"UPDATE relay_run SET accepted_at = COALESCE(accepted_at, ?), owner_heard_at = ? WHERE run_id = ?\",\n at,\n at,\n runId,\n );\n return relayRow(db, runId)?.cancel_requested_at ?? null;\n });\n // A cancel pressed before the owner had it, or while its acknowledgement was on its way,\n // reaches the run now (Opus review of WP-29).\n if (cancelled !== null) void cancelOnOwner(runId, session);\n } catch (error) {\n const code = error instanceof RpcError ? error.diagnostic.code : undefined;\n if (code !== undefined && !TRANSPORT_FAILURES.has(code)) {\n // The owner answered and refused the run: it records a run before it answers, so a\n // refusal means the run never started there, and it ends failed with the owner's reason.\n refused(runId, (error as RpcError).diagnostic);\n } else {\n // Sent and not acknowledged: it is sent again (after the next reconnect, or by the sweep\n // while the owner stays connected), which joins it if the owner recorded it (§11.1).\n log.warn(\"relay.send_failed\", { runId, error });\n }\n } finally {\n lastTry.set(runId, now());\n sending.delete(runId);\n }\n };\n\n /** A run its owner refused before recording it ends failed, with the owner's diagnostic. */\n const refused = (runId: string, diagnostic: { code: string; message: string }): void => {\n log.warn(\"relay.run_refused\", { runId, code: diagnostic.code });\n const ended = ledger.write((db) => {\n const row = runRow(db, runId);\n if (!row || isFinalRunStatus(row.status) || row.status === \"unknown\") return undefined;\n const done = finishRun(db, runId, {\n status: \"failed\",\n reason: \"owner-refused\",\n error: { code: diagnostic.code, message: diagnostic.message },\n });\n return done ? { state: runState(db, done), artifactId: done.artifact_id } : undefined;\n });\n if (ended) publish(ended.state, ended.artifactId);\n };\n\n const cancelOnOwner = async (runId: string, session: number): Promise<void> => {\n try {\n await options.call(session, portRelayCancelMethod.method, { runId }, PORT_CALL_MS);\n ledger.write((db) =>\n db.run(\"UPDATE relay_run SET cancel_requested_at = NULL WHERE run_id = ?\", runId),\n );\n } catch (error) {\n log.warn(\"relay.cancel_failed\", { runId, error });\n }\n };\n\n /**\n * Applies a run's state as the owner reports it, from what the hosted home holds on: new log\n * lines and batches by position, `running`, and the end (which replaces `unknown` once).\n */\n const apply = (\n runId: string,\n report: {\n readonly running?: boolean;\n readonly progress?: RunState[\"progress\"];\n readonly log?: readonly string[];\n readonly logFrom?: number;\n readonly batches?: Batches;\n readonly batchFrom?: number;\n readonly end?: {\n readonly status: \"succeeded\" | \"failed\" | \"cancelled\";\n readonly reason?: string;\n readonly error?: { readonly message: string; readonly code?: string };\n };\n },\n ): void => {\n const state = ledger.write((db) => {\n const row = runRow(db, runId);\n if (!row || isFinalRunStatus(row.status)) return undefined;\n db.run(\"UPDATE relay_run SET owner_heard_at = ? WHERE run_id = ?\", iso(now()), runId);\n // An update from past what this home holds means one before it was lost: nothing of it is\n // kept, its end least of all, and the owner is asked for the run from what is held, so a\n // run never ends without its result (Opus review of WP-29, 4).\n if (\n (report.logFrom !== undefined && report.logFrom > row.log_lines) ||\n (report.batchFrom !== undefined && report.batchFrom > row.batches)\n ) {\n return \"gap\" as const;\n }\n if (\n (report.running || report.log || report.batches || report.end) &&\n row.status !== \"unknown\"\n ) {\n markRunning(db, runId);\n }\n // What the hosted home holds already is skipped, so a repeat appends nothing.\n const lines = report.log ?? [];\n const linesFrom = report.logFrom ?? row.log_lines;\n const freshLines = linesFrom <= row.log_lines ? lines.slice(row.log_lines - linesFrom) : [];\n const batches = report.batches ?? [];\n const batchesFrom = report.batchFrom ?? row.batches;\n const freshBatches =\n batchesFrom <= row.batches ? batches.slice(row.batches - batchesFrom) : [];\n if (freshLines.length > 0 || freshBatches.length > 0 || report.progress) {\n appendRunOutput(db, runId, {\n lines: freshLines,\n batches: freshBatches,\n ...(report.progress ? { progress: report.progress } : {}),\n });\n }\n if (report.end) {\n finishRun(db, runId, {\n status: report.end.status,\n ...(report.end.reason !== undefined ? { reason: report.end.reason } : {}),\n ...(report.end.error ? { error: report.end.error } : {}),\n });\n }\n const after = runRow(db, runId);\n return after ? { state: runState(db, after), artifactId: after.artifact_id } : undefined;\n });\n if (state === \"gap\") {\n log.warn(\"relay.update_gap\", { runId });\n void catchUp(runId);\n return;\n }\n if (state) publish(state.state, state.artifactId);\n };\n\n /** Runs being asked for again after a gap, so one gap asks once. */\n const catchingUp = new Set<string>();\n /** Asks the owner for one run's state from what this home holds (a reconcile of that run). */\n const catchUp = async (runId: string): Promise<void> => {\n if (catchingUp.has(runId)) return;\n catchingUp.add(runId);\n try {\n const entry = ledger.read((db) => {\n const relay = relayRow(db, runId);\n const run = runRow(db, runId);\n return relay && run ? { relay, run } : undefined;\n });\n if (!entry) return;\n const session = sessionFor(entry.relay.owner_link_id);\n if (session === undefined) return;\n const answer = (await options.call(\n session,\n portRelayReconcileMethod.method,\n {\n runs: [runId],\n held: [{ runId, log: entry.run.log_lines, batches: entry.run.batches }],\n },\n PORT_CALL_MS,\n )) as PortRelayReconcileResult;\n for (const reconciled of answer.runs) applyReconciled(reconciled);\n } catch (error) {\n // The next reconnect's reconcile asks again.\n log.warn(\"relay.catch_up_failed\", { runId, error });\n } finally {\n catchingUp.delete(runId);\n }\n };\n\n /** Applies the owner's answer for one run of a reconcile. */\n const applyReconciled = (entry: PortRelayReconcileResult[\"runs\"][number]): void => {\n if (entry.state === \"unknown-to-owner\") {\n unknown(entry.runId);\n return;\n }\n const state = entry.state;\n apply(entry.runId, {\n running: state.status !== \"queued\",\n ...(state.progress ? { progress: state.progress } : {}),\n log: state.log,\n logFrom: state.logFrom ?? 0,\n batches: state.batches,\n batchFrom: state.batchFrom ?? 0,\n ...(state.status === \"succeeded\" || state.status === \"failed\" || state.status === \"cancelled\"\n ? {\n end: {\n status: state.status,\n ...(state.reason !== undefined ? { reason: state.reason } : {}),\n ...(state.error ? { error: state.error } : {}),\n },\n }\n : {}),\n });\n };\n\n /** Moves a run to `unknown`, and tells its views. */\n const unknown = (runId: string): void => {\n const state = ledger.write((db) => {\n if (!markUnknown(db, runId)) return undefined;\n const row = runRow(db, runId);\n return row ? { state: runState(db, row), artifactId: row.artifact_id } : undefined;\n });\n if (state) publish(state.state, state.artifactId);\n };\n\n /**\n * The runs of a link the owner accepted and the hosted home holds no end for, and every run sent\n * that became `unknown` (its acknowledgement may have been lost): the owner's report replaces\n * `unknown` once, and asking starts nothing (Opus review of WP-29, 8).\n */\n const acceptedOpen = (linkId: string): { relay: RelayRow; run: RunRow }[] =>\n ledger.read((db) =>\n db\n .all<RelayRow & { status: string }>(\n `SELECT r.*, a.status FROM relay_run r JOIN action_run a ON a.id = r.run_id\n WHERE r.owner_link_id = ?\n AND ((r.accepted_at IS NOT NULL AND a.status IN ('queued', 'running', 'waiting'))\n OR (r.sent_at IS NOT NULL AND a.status = 'unknown'))\n ORDER BY r.relay_seq`,\n linkId,\n )\n .map((relay) => ({ relay, run: runRow(db, relay.run_id) as RunRow })),\n );\n\n /** After a reconnect: reconcile, then resend, then drain the waiting runs in order (§18.3). */\n const resume = async (linkId: string, session: number, relayMark: number): Promise<void> => {\n try {\n // The owner's home was restored to before runs it accepted: they, and every run sent but\n // never acknowledged, become `unknown` and are never sent again.\n const high = ledger.read(\n (db) =>\n db.get<{ high: number | null }>(\n \"SELECT MAX(relay_seq) AS high FROM relay_run WHERE owner_link_id = ? AND accepted_at IS NOT NULL\",\n linkId,\n )?.high ?? 0,\n );\n if (relayMark < high) {\n const lost = ledger.read((db) =>\n db\n .all<{ run_id: string }>(\n `SELECT r.run_id FROM relay_run r JOIN action_run a ON a.id = r.run_id\n WHERE r.owner_link_id = ? AND r.sent_at IS NOT NULL\n AND a.status IN ('queued', 'running', 'waiting')`,\n linkId,\n )\n .map((row) => row.run_id),\n );\n log.warn(\"relay.owner_regressed\", { linkId, relayMark, high, runs: lost.length });\n for (const runId of lost) unknown(runId);\n } else {\n const open = acceptedOpen(linkId);\n if (open.length > 0) {\n const answer = (await options.call(\n session,\n portRelayReconcileMethod.method,\n {\n runs: open.map((entry) => entry.run.id),\n held: open.map((entry) => ({\n runId: entry.run.id,\n log: entry.run.log_lines,\n batches: entry.run.batches,\n })),\n },\n PORT_CALL_MS,\n )) as PortRelayReconcileResult;\n for (const entry of answer.runs) applyReconciled(entry);\n // A cancel made while the owner was away reaches it now.\n for (const entry of open) {\n if (entry.relay.cancel_requested_at !== null) void cancelOnOwner(entry.run.id, session);\n }\n }\n }\n if (options.sessionOf(linkId) !== session) return;\n ready.set(linkId, session);\n // The sources its viewers want start again on the owner that came back.\n asked.clear();\n renewLive();\n // Sent and never acknowledged: sent again, which joins the owner's record if it has one.\n const unacknowledged = ledger.read((db) =>\n db\n .all<{ run_id: string }>(\n `SELECT r.run_id FROM relay_run r JOIN action_run a ON a.id = r.run_id\n WHERE r.owner_link_id = ? AND r.sent_at IS NOT NULL AND r.accepted_at IS NULL\n AND a.status IN ('queued', 'running', 'waiting') ORDER BY r.relay_seq`,\n linkId,\n )\n .map((row) => row.run_id),\n );\n for (const runId of unacknowledged) await send(runId, session);\n retries.delete(session);\n void drain(linkId);\n } catch (error) {\n log.warn(\"relay.resume_failed\", { linkId, error });\n // A reconcile that timed out or failed leaves the owner unready: tried again for the same\n // session, 1 s doubling to 60 s, while it stays its link's session.\n if (stopped || options.sessionOf(linkId) !== session) return;\n const attempt = (retries.get(session)?.attempt ?? 0) + 1;\n const timer = setTimeout(\n () => {\n if (options.sessionOf(linkId) === session && ready.get(linkId) !== session) {\n void resume(linkId, session, relayMark);\n }\n },\n Math.min(60_000, 1000 * 2 ** (attempt - 1)),\n );\n timer.unref();\n retries.set(session, { timer, attempt });\n }\n };\n\n /** Sends a link's waiting runs, oldest first, at most `drainPerSecond` a second per artifact. */\n const drain = async (linkId: string): Promise<void> => {\n if (draining.has(linkId)) return;\n draining.add(linkId);\n try {\n const sentAt = new Map<string, number[]>();\n for (;;) {\n if (stopped) return;\n const session = sessionFor(linkId);\n if (session === undefined) return;\n const next = ledger.read((db) =>\n db.get<{ run_id: string; artifact_id: string }>(\n `SELECT r.run_id, a.artifact_id FROM relay_run r JOIN action_run a ON a.id = r.run_id\n WHERE r.owner_link_id = ? AND r.sent_at IS NULL\n AND a.status IN ('queued', 'waiting') ORDER BY r.relay_seq LIMIT 1`,\n linkId,\n ),\n );\n if (!next) return;\n const times = (sentAt.get(next.artifact_id) ?? []).filter((at) => now() - at < 1000);\n if (times.length >= drainPerSecond) {\n await new Promise((resolve) =>\n setTimeout(resolve, 1000 - (now() - (times[0] as number))),\n );\n continue;\n }\n times.push(now());\n sentAt.set(next.artifact_id, times);\n await send(next.run_id, session);\n }\n } finally {\n draining.delete(linkId);\n }\n };\n\n /** Checks waiting and unacknowledged runs against their offline limit's two clocks. */\n const sweep = (): void => {\n const rows = ledger.read((db) =>\n db.all<RelayRow & { status: string; version_id: string; started_at: string }>(\n `SELECT r.*, a.status, a.version_id, a.started_at FROM relay_run r\n JOIN action_run a ON a.id = r.run_id WHERE a.status IN ('queued', 'running', 'waiting')`,\n ),\n );\n const open = new Set(rows.map((row) => row.run_id));\n for (const id of lastTry.keys()) if (!open.has(id)) lastTry.delete(id);\n for (const row of rows) {\n if (sending.has(row.run_id)) continue;\n if (row.sent_at === null) {\n // Never sent: counted from when it was recorded, and it never happened.\n if (Date.parse(row.offline_limit_at) <= now()) endOffline(row.run_id);\n continue;\n }\n // Sent: counted from when the owner was last heard from, and only while it is away. While\n // it stays connected, a run it never acknowledged (its answer timed out) is sent again.\n const session = sessionFor(row.owner_link_id);\n if (session !== undefined) {\n if (row.accepted_at === null && now() - (lastTry.get(row.run_id) ?? 0) >= RESEND_MS) {\n void send(row.run_id, session);\n }\n continue;\n }\n const heard = Date.parse(row.owner_heard_at ?? row.sent_at);\n if (heard + versionOf(row.version_id).limitMs <= now()) unknown(row.run_id);\n }\n };\n const sweeper = setInterval(sweep, options.sweepMs ?? 1000);\n sweeper.unref();\n\n /** What each artifact's owner was last asked to produce, so a source no one wants is stopped. */\n const asked = new Map<string, ReadonlySet<string>>();\n /** Asks owners for the live sources viewers want now, and stops the ones no one does (§18.3). */\n const renewLive = (only?: string): void => {\n const wanted = new Map<string, Set<string>>();\n for (const entry of bus.liveInterest()) {\n if (entry.key.startsWith(TALLY_LIVE_PREFIX)) continue;\n const keys = wanted.get(entry.artifactId) ?? new Set<string>();\n keys.add(entry.key);\n wanted.set(entry.artifactId, keys);\n }\n const artifacts = new Set([...wanted.keys(), ...asked.keys()]);\n for (const artifactId of artifacts) {\n if (only !== undefined && artifactId !== only) continue;\n const owner = options.ownerOf(artifactId);\n const session = owner === undefined ? undefined : sessionFor(owner);\n const versionId = options.latestVersion?.(artifactId);\n if (session === undefined || versionId === undefined) continue;\n const keys = wanted.get(artifactId) ?? new Set<string>();\n const before = asked.get(artifactId) ?? new Set<string>();\n const stopped = [...before].filter((key) => !keys.has(key));\n const send = (interest: \"start\" | \"renew\" | \"stop\", list: readonly string[]): void => {\n if (list.length === 0) return;\n void options\n .call(\n session,\n portRelayLiveMethod.method,\n { artifactId, versionId, interest, keys: list },\n PORT_CALL_MS,\n )\n .catch((error: unknown) => log.warn(\"relay.live_interest_failed\", { artifactId, error }));\n };\n send(\"renew\", [...keys]);\n send(\"stop\", stopped);\n if (keys.size > 0) asked.set(artifactId, keys);\n else asked.delete(artifactId);\n }\n };\n const liveRenewer = setInterval(() => renewLive(), options.liveRenewMs ?? 20_000);\n liveRenewer.unref();\n\n const decorate = (state: RunState, artifactId: string): RunState => {\n if (state.status !== \"running\") return state;\n const owner = options.ownerOf(artifactId);\n return owner !== undefined && sessionFor(owner) !== undefined\n ? state\n : { ...state, ownerUnreachable: true };\n };\n\n return {\n async call(page, input, signal) {\n checkArgs(input.args);\n const versionId = interaction.viewVersion(page, input.viewId);\n mayTrigger(page.viewerId, functionOf(versionId, input.fnId));\n limitLink(page.tokenId);\n const owner = options.ownerOf(page.artifactId);\n const session = owner === undefined ? undefined : sessionFor(owner);\n if (session === undefined) {\n throw failed(\n \"MOSTRA_REMOTE_OWNER_OFFLINE\",\n \"The page's owner is offline, so its server code can't answer now; try again later.\",\n );\n }\n const callId = `call_${crypto.randomUUID()}`;\n const pending: PendingCall = { session, lines: [], ended: false, lastSeq: 0 };\n calls.set(callId, pending);\n const viewer = interaction.viewer(page.viewerId);\n try {\n await options.call(\n session,\n portRelayCallMethod.method,\n {\n callId,\n artifactId: page.artifactId,\n versionId,\n fnId: input.fnId,\n args: input.args,\n viewer: { id: viewer.id, ...(viewer.name ? { name: viewer.name } : {}) },\n viewId: input.viewId,\n },\n PORT_CALL_MS,\n );\n } catch (error) {\n calls.delete(callId);\n throw error instanceof RpcError\n ? failed(\n \"MOSTRA_REMOTE_OWNER_OFFLINE\",\n `The page's owner couldn't take the call: ${error.diagnostic.message}`,\n )\n : error;\n }\n const lines = async function* (): AsyncGenerator<CallLine> {\n try {\n for (;;) {\n const line = pending.lines.shift();\n if (line) {\n yield line;\n if (\"end\" in line) return;\n continue;\n }\n if (pending.ended || signal.aborted) return;\n await new Promise<void>((resolve) => {\n pending.wake = resolve;\n });\n }\n } finally {\n calls.delete(callId);\n }\n };\n return lines();\n },\n\n startRun(page, input) {\n checkArgs(input.args);\n const versionId = interaction.viewVersion(page, input.viewId);\n const version = functionOf(versionId, input.fnId);\n mayTrigger(page.viewerId, version);\n limitLink(page.tokenId, page.artifactId, input);\n const owner = options.ownerOf(page.artifactId);\n if (owner === undefined) {\n throw failed(\"MOSTRA_REMOTE_OWNER_OFFLINE\", \"This page has no owner instance to run it.\");\n }\n const connected = sessionFor(owner) !== undefined;\n // Past the cap a run is refused before anything is recorded (D165 item 4). A request that\n // joins a run already recorded is never refused.\n if (!connected && version.policy === \"queue\") {\n const waiting = ledger.read(\n (db) =>\n db.get<{ n: number }>(\n \"SELECT COUNT(*) AS n FROM action_run WHERE artifact_id = ? AND status = 'waiting'\",\n page.artifactId,\n )?.n ?? 0,\n );\n const joins = ledger.read(\n (db) =>\n db.get<{ id: string }>(\n `SELECT id FROM action_run WHERE artifact_id = ? AND (client_key = ? OR (key IS NOT NULL AND key = ? AND action = ?))`,\n page.artifactId,\n input.clientKey,\n input.key ?? null,\n input.fnId,\n ) !== undefined,\n );\n if (waiting >= cap && !joins) {\n throw failed(\n \"MOSTRA_REMOTE_QUEUE_FULL\",\n \"Too many actions are waiting for this page's owner; try again once it is back.\",\n );\n }\n }\n const { state, row, started } = interaction.startRun(page, input);\n bus.attachRuns(page.artifactId, input.viewId, [state.runId]);\n if (!started) return decorate(state, page.artifactId);\n // The relay's record, in the order runs were made: its sequence is unique per owner link and\n // continues above the owner's mark after a restore (§18.2).\n const recorded = Date.parse(row.started_at);\n const waitingState = ledger.write((db) => {\n const seq =\n (db.get<{ high: number | null }>(\n \"SELECT MAX(relay_seq) AS high FROM relay_run WHERE owner_link_id = ?\",\n owner,\n )?.high ?? 0) + 1;\n const floor = Math.max(\n marks.get(owner) ?? 0,\n db.get<{ floor: number }>(\"SELECT floor FROM relay_floor WHERE link_id = ?\", owner)\n ?.floor ?? 0,\n );\n db.run(\n \"INSERT INTO relay_run (run_id, owner_link_id, relay_seq, offline_limit_at) VALUES (?, ?, ?, ?)\",\n row.id,\n owner,\n Math.max(seq, floor + 1),\n iso(recorded + version.limitMs),\n );\n if (connected) return undefined;\n markWaiting(db, row.id);\n const after = runRow(db, row.id);\n return after ? runState(db, after) : undefined;\n });\n if (connected) {\n const session = sessionFor(owner);\n if (session !== undefined) void send(row.id, session);\n return state;\n }\n if (version.policy === \"fail\") {\n endOffline(row.id);\n return interaction.runState(row.id) ?? state;\n }\n if (waitingState) publish(waitingState, page.artifactId);\n return waitingState ?? state;\n },\n\n attach(page, input) {\n const states = interaction.runsFor(page, input);\n bus.attachRuns(\n page.artifactId,\n input.viewId,\n states.map((state) => state.runId),\n );\n return states.map((state) => decorate(state, page.artifactId));\n },\n\n cancel(page, viewId, runId) {\n const row = interaction.runFor(page, viewId, runId);\n const relay = ledger.read((db) => relayRow(db, row.id));\n if (!relay || relay.sent_at === null) {\n // Never sent: it ends here without contacting the owner.\n if (!isFinalRunStatus(row.status) && row.status !== \"unknown\") {\n const ended = interaction.endRun(row.id, { status: \"cancelled\", reason: \"cancelled\" });\n if (ended) publish(ended, row.artifact_id);\n }\n return interaction.runState(row.id) as RunState;\n }\n ledger.write((db) =>\n db.run(\"UPDATE relay_run SET cancel_requested_at = ? WHERE run_id = ?\", iso(now()), row.id),\n );\n const session = sessionFor(relay.owner_link_id);\n if (session !== undefined && relay.accepted_at !== null) void cancelOnOwner(row.id, session);\n return decorate(interaction.runState(row.id) as RunState, row.artifact_id);\n },\n\n methods() {\n return [\n handler(relayRunUpdateMethod, (params, session) => {\n const known = ledger.read((db) => relayRow(db, params.runId));\n if (!known || known.owner_link_id !== session.link?.instanceId) {\n // A home restored to before this run: the owner keeps and finishes it locally.\n log.warn(\"relay.update_dropped\", { runId: params.runId });\n return {};\n }\n if (params.seq <= known.last_seq) return {};\n ledger.write((db) =>\n db.run(\"UPDATE relay_run SET last_seq = ? WHERE run_id = ?\", params.seq, params.runId),\n );\n apply(params.runId, params);\n return {};\n }),\n handler(relayLiveValueMethod, (params, session) => {\n if (options.ownerOf(params.artifactId) !== session.link?.instanceId) {\n throw failed(\n \"MOSTRA_REMOTE_NOT_OWNER_INSTANCE\",\n \"This instance doesn't own that artifact here.\",\n );\n }\n return (\n options.storeLive?.(params.artifactId, params.versionId, {\n key: params.key,\n ...(params.value !== undefined ? { value: params.value } : {}),\n ...(params.error !== undefined ? { error: params.error } : {}),\n }) ?? {}\n );\n }),\n handler(relayEffectMethod, (params, session) => {\n // Only the artifact's owner instance speaks for its runs (D165 item 1b).\n if (options.ownerOf(params.artifactId) !== session.link?.instanceId) {\n throw failed(\n \"MOSTRA_REMOTE_NOT_OWNER_INSTANCE\",\n \"This instance doesn't own that artifact here.\",\n );\n }\n const row =\n params.runId !== undefined\n ? ledger.read((db) => runRow(db, params.runId as string))\n : undefined;\n if (params.runId !== undefined && row?.artifact_id !== params.artifactId) {\n throw failed(\"MOSTRA_ACTION_RUN_NOT_FOUND\", \"This home has no such run.\");\n }\n const viewerId = row?.viewer_id ?? undefined;\n const common = {\n ...(params.payload !== undefined ? { payload: params.payload } : {}),\n ...(params.runId !== undefined ? { runId: params.runId } : {}),\n ...(viewerId !== undefined ? { viewerId } : {}),\n };\n if (params.kind === \"signal\") {\n return {\n cursor: interaction.serverSignal(params.artifactId, { name: params.name, ...common }),\n };\n }\n if (!/^host\\.[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(params.name)) {\n throw failed(\n \"MOSTRA_ACTION_EVENT_INVALID\",\n `${params.name.slice(0, 80)} isn't a host event type.`,\n );\n }\n return {\n cursor: interaction.serverEmit(params.artifactId, { type: params.name, ...common }),\n };\n }),\n handler(relayCallBatchMethod, (params, session) => {\n const pending = calls.get(params.callId);\n if (!pending || pending.session !== session.id || params.seq <= pending.lastSeq)\n return {};\n pending.lastSeq = params.seq;\n for (const batch of params.batches ?? []) pending.lines.push({ batch: [...batch] });\n if (params.end) {\n pending.lines.push(\n params.end.status === \"succeeded\"\n ? { end: { status: \"succeeded\" } }\n : {\n end: {\n status: \"failed\",\n error: params.end.error ?? { message: \"The call failed on its owner.\" },\n },\n },\n );\n pending.ended = true;\n }\n pending.wake?.();\n return {};\n }),\n ];\n },\n\n connected(session) {\n const linkId = session.link?.instanceId;\n if (linkId === undefined || !session.ports.has(\"relay\")) return;\n const mark = session.link?.relayMark ?? 0;\n marks.set(linkId, Math.max(marks.get(linkId) ?? 0, mark));\n sessionMarks.set(session.id, mark);\n void resume(linkId, session.id, mark);\n },\n\n disconnected(session) {\n const linkId = session.link?.instanceId;\n sessionMarks.delete(session.id);\n const retry = retries.get(session.id);\n if (retry) clearTimeout(retry.timer);\n retries.delete(session.id);\n if (linkId !== undefined && ready.get(linkId) === session.id) ready.delete(linkId);\n // The link's session now, if it isn't ready (it opened while this one was still the link's,\n // so its resume stopped short), is resumed: nothing else would (Opus review of WP-29, 1).\n if (linkId !== undefined) {\n const live = options.sessionOf(linkId);\n if (live !== undefined && live !== session.id && ready.get(linkId) !== live) {\n void resume(linkId, live, sessionMarks.get(live) ?? marks.get(linkId) ?? 0);\n }\n }\n for (const [callId, pending] of calls) {\n if (pending.session !== session.id) continue;\n pending.lines.push({\n end: {\n status: \"failed\",\n error: {\n code: \"MOSTRA_REMOTE_OWNER_OFFLINE\",\n message: \"The page's owner went offline before the call ended.\",\n },\n },\n });\n pending.ended = true;\n pending.wake?.();\n calls.delete(callId);\n }\n },\n\n busy() {\n return (\n calls.size > 0 ||\n ledger.read(\n (db) =>\n (db.get<{ n: number }>(\n \"SELECT COUNT(*) AS n FROM action_run WHERE status IN ('queued', 'running', 'waiting')\",\n )?.n ?? 0) > 0,\n )\n );\n },\n\n liveWanted(artifactId) {\n const known = asked.get(artifactId);\n const fresh = bus\n .liveInterest()\n .some(\n (entry) =>\n entry.artifactId === artifactId &&\n !entry.key.startsWith(TALLY_LIVE_PREFIX) &&\n !(known?.has(entry.key) ?? false),\n );\n if (fresh) renewLive(artifactId);\n },\n\n ownerOffline(artifactId) {\n const owner = options.ownerOf(artifactId);\n return owner === undefined || sessionFor(owner) === undefined;\n },\n\n stop() {\n stopped = true;\n for (const retry of retries.values()) clearTimeout(retry.timer);\n retries.clear();\n clearInterval(sweeper);\n clearInterval(liveRenewer);\n },\n };\n}\n","/**\n * A hosted home (ARCHITECTURE §15.2, DATA_MODEL §7.2, D165): a Mostra home on a remote server with\n * the same ledger, registry, interaction core and events as a local one, and no sources, builds,\n * verify, workers, dependency store or secrets. Its versions arrive from the owner instance\n * (`hosted/push`): the client files the listing names, checked against `outputDigest`, never the\n * server files; its server code runs on the owner, through the relay.\n *\n * Its host protocol is served by a {@link ProtocolServer} of its own, reached over the network\n * binding (§18.2), so the owner instance is a host of its hosted home as any host is of an\n * instance (invariant 11): it registers `submissions`, and a submission's one delivery owner is its\n * artifact's owner link (D165, after the Opus review).\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { linkSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { copyFile, readFile, rm } from \"node:fs/promises\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { isAbsolute, join, relative } from \"node:path\";\nimport {\n ArtifactManifest,\n artifactGetMethod,\n artifactListMethod,\n createDiagnostic,\n type HostedPushParams,\n type HostedPushResult,\n type HostedRoute,\n hostedPushMethod,\n hostedSubmissionMethod,\n type InstanceInfo,\n RouteId,\n RpcError,\n remoteTokenMethod,\n} from \"@mostra/protocol\";\nimport type { Addressing } from \"../addressing/index.ts\";\nimport { coverageMatcher, readFieldCoverage, readServerFunctions } from \"../builder/index.ts\";\nimport { noFaults } from \"../faults.ts\";\nimport {\n Capabilities,\n capabilityKey,\n createGateway,\n type FaceSpec,\n type Gateway,\n} from \"../gateway/index.ts\";\nimport { platformName } from \"../home/index.ts\";\nimport { createEphemeralBus, createInteraction, type Interaction } from \"../interaction/index.ts\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport { createLive, liveMethods } from \"../live/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { handler, ProtocolServer, type Session } from \"../protocol-server/index.ts\";\nimport { canonicalRef, listingDigest, versionIdFor } from \"../publish/index.ts\";\nimport { openRegistry, type Registry } from \"../registry/index.ts\";\nimport type { Authorization } from \"./auth.ts\";\nimport { rotateIncarnation } from \"./data.ts\";\nimport { createHostedRelay } from \"./relay.ts\";\n\n/** Lower-case Crockford base32, for route labels (one DNS label, 130 bits). */\nconst LABEL_ALPHABET = \"0123456789abcdefghjkmnpqrstvwxyz\";\n\n/** A random route label: 26 lower-case Crockford base32 characters (INTERFACES §18.4). */\n\n/** A character no part of a listing's path may hold: a backslash, a colon, a control character. */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it refuses\nconst UNSAFE_PART = /[\\\\:\\u0000-\\u001f\\u007f]/;\n\n/**\n * Whether a pushed listing's path is one a version can hold on every system the server runs on: `/`\n * between non-empty parts, none `.` or `..`, and no backslash, colon or control character, which\n * Windows reads as separators, drive or stream names, or refuses (Opus review of WP-29, 5); in NFC,\n * as listings are written (DATA_MODEL §2).\n */\nfunction safeListingPath(path: string): boolean {\n if (path.length > 1024 || path.normalize(\"NFC\") !== path) return false;\n return path\n .split(\"/\")\n .every((part) => part !== \"\" && part !== \".\" && part !== \"..\" && !UNSAFE_PART.test(part));\n}\n\nexport function randomLabel(): string {\n const bytes = randomBytes(26);\n let label = \"\";\n for (const byte of bytes) label += LABEL_ALPHABET[byte & 31];\n return label;\n}\n\n/** What the server keeps of one open hosted home. */\nexport interface HostedHome {\n readonly id: string;\n readonly dir: string;\n readonly ledger: Ledger;\n readonly registry: Registry;\n readonly interaction: Interaction;\n /** The home's host protocol, served over the binding. */\n readonly protocol: ProtocolServer;\n /** The home's current incarnation (DATA_MODEL §7.2). */\n incarnation(): string;\n /** The SHA-256s of client files a pending push of this home names as missing. */\n wanted(sha256: string): boolean;\n /** Records a file this home uploaded (`PUT /files/<sha256>`, §18.2). */\n uploaded(sha256: string): void;\n /** Whether a binding is open, a stream or poll is served, or a delivery waits. */\n busy(): boolean;\n /**\n * Serves a request the server's front routed here by its exact `Host` (INTERFACES §18.4): the\n * shell on a user-content domain's apex (`/a/<routeId>…`), or a route's frames on its label.\n */\n serve(request: IncomingMessage, response: ServerResponse, at: HostedAddress): Promise<void>;\n stop(): Promise<void>;\n}\n\n/** Where a hosted request came in: a domain's apex, or a route's label on it. */\nexport type HostedAddress =\n | { readonly kind: \"shell\"; readonly domain: string; readonly routeId: string }\n | { readonly kind: \"frame\"; readonly domain: string; readonly routeId: string };\n\n/** Options for {@link openHostedHome}. */\nexport interface HostedHomeOptions {\n readonly id: string;\n readonly dir: string;\n readonly ledger: Ledger;\n readonly incarnation: string;\n /** The server's directory ledger (routes, files, links). */\n readonly directory: Ledger;\n /** `<data>/files`: version files, content-addressed, stored once for the directory. */\n readonly filesDir: string;\n readonly auth: Authorization;\n readonly runtimeVersion: string;\n readonly log: Log;\n /** `https` behind a TLS terminator; `http` only for loopback tests (§18.1). */\n readonly scheme: \"https\" | \"http\";\n /** The user-content domains: new links on `active`, issued ones keep theirs (D137). */\n readonly domains: { readonly active: string; readonly spares: readonly string[] };\n /** The shell's built files. */\n readonly shellDir: string | undefined;\n /** The relay's server settings (`relay` in the configuration, D165 item 4). */\n readonly relay?: {\n readonly waitingRunsPerArtifact?: number | undefined;\n readonly drainPerSecond?: number | undefined;\n /** How often waiting and unacknowledged runs meet their limits (tests shorten it). */\n readonly sweepMs?: number | undefined;\n /** How often viewers' live interest is renewed with the owner (tests shorten it). */\n readonly liveRenewMs?: number | undefined;\n /** `rateLimits.perLink.relayedRuns`, in milliseconds. */\n readonly perLink?: { readonly count: number; readonly perMs: number } | undefined;\n };\n}\n\nfunction refuse(code: Parameters<typeof createDiagnostic>[0], message: string): RpcError {\n return new RpcError(createDiagnostic(code, { message }));\n}\n\n/** Opens the parts of a hosted home over its ledger. */\nexport async function openHostedHome(options: HostedHomeOptions): Promise<HostedHome> {\n const { id, dir, ledger, directory, log } = options;\n const registry = await openRegistry({ home: dir, ledger });\n /** Pending pushes: version ID → the client files still missing. */\n const pending = new Map<string, Set<string>>();\n let incarnation = options.incarnation;\n\n const ownerLinkOf = (artifactId: string): string | undefined =>\n directory.read(\n (db) =>\n db.get<{ owner_link_id: string }>(\n \"SELECT owner_link_id FROM artifact_route WHERE home_id = ? AND artifact_id = ?\",\n id,\n artifactId,\n )?.owner_link_id,\n );\n\n const coverage = (() => {\n const cache = new Map<string, (fieldId: string) => boolean>();\n return (versionId: string) => {\n let matcher = cache.get(versionId);\n if (!matcher) {\n matcher = coverageMatcher(readFieldCoverage(registry.store.versionDir(versionId)));\n if (cache.size >= 512) cache.delete(cache.keys().next().value as string);\n cache.set(versionId, matcher);\n }\n return matcher;\n };\n })();\n\n let protocol: ProtocolServer;\n const interaction = createInteraction({\n // A respondent on a hosted link learns only that the answer was sent (D165 item 1a).\n sentOnly: true,\n ledger,\n log,\n faults: noFaults,\n hosts: {\n registrants: (port) => protocol.registrants(port),\n call: (session, method, params, timeoutMs) =>\n protocol.callSession(session, method, params as never, timeoutMs),\n notify: (session, method, params) => protocol.notify(session, method, params as never),\n drained: (session) => protocol.drained(session),\n },\n expectedHosts: () => [],\n artifacts: { resolve: (ref) => registry.get(canonicalRef(ref)).id },\n coverage,\n // A submission's one delivery owner is its artifact's owner link, connected or not, so it\n // waits for that instance and no other instance of the account receives it (D165 item 1b).\n deliverSnapshots: true,\n deliveryOwners: (artifactId) => {\n const owner = ownerLinkOf(artifactId);\n return owner === undefined ? undefined : [owner];\n },\n });\n\n /** The route of an artifact on this home, minted on its first push by `link`. */\n const routeFor = (artifactId: string, link: string): HostedRoute =>\n directory.write((db) => {\n const found = db.get<{ id: string; label: string; owner_link_id: string }>(\n \"SELECT id, label, owner_link_id FROM artifact_route WHERE home_id = ? AND artifact_id = ?\",\n id,\n artifactId,\n );\n if (found) {\n if (found.owner_link_id !== link) {\n const owner = db.get<{ name: string }>(\n \"SELECT name FROM instance_link WHERE id = ?\",\n found.owner_link_id,\n );\n throw refuse(\n \"MOSTRA_REMOTE_NOT_OWNER_INSTANCE\",\n `The instance \"${owner?.name ?? found.owner_link_id}\" owns this hosted artifact; push it from there.`,\n );\n }\n return { routeId: found.id, label: found.label };\n }\n const routeId = RouteId.create();\n let label = randomLabel();\n // A label is issued once, forever (label_issued keeps every one): a collision draws again.\n while (db.get(\"SELECT 1 FROM label_issued WHERE label = ?\", label)) label = randomLabel();\n const at = new Date().toISOString();\n db.run(\n \"INSERT INTO label_issued (label, home_id, route_id, kind, issued_at) VALUES (?, ?, ?, 'server', ?)\",\n label,\n id,\n routeId,\n at,\n );\n db.run(\n \"INSERT INTO artifact_route (id, home_id, artifact_id, owner_link_id, label, created_at) VALUES (?, ?, ?, ?, ?, ?)\",\n routeId,\n id,\n artifactId,\n link,\n label,\n at,\n );\n log.info(\"server.route_minted\", { home: id, artifactId, routeId });\n return { routeId, label };\n });\n\n // ── Hosted pages (INTERFACES §18.4) ────────────────────────────────────────────────────\n\n const routeOf = (artifactId: string): { id: string; label: string } | undefined =>\n directory.read((db) =>\n db.get<{ id: string; label: string }>(\n \"SELECT id, label FROM artifact_route WHERE home_id = ? AND artifact_id = ?\",\n id,\n artifactId,\n ),\n );\n const artifactOfRoute = (routeId: string): string | undefined =>\n directory.read(\n (db) =>\n db.get<{ artifact_id: string }>(\n \"SELECT artifact_id FROM artifact_route WHERE id = ? AND home_id = ?\",\n routeId,\n id,\n )?.artifact_id,\n );\n const domains = [options.domains.active, ...options.domains.spares];\n const originOf = (host: string): string => `${options.scheme}://${host}`;\n const capabilities: Capabilities = new Capabilities({\n ledger,\n log,\n key: capabilityKey(dir, log),\n now: () => Date.now(),\n shellOrigin: () => originOf(options.domains.active),\n servesShell: (origin) => domains.some((domain) => originOf(domain) === origin),\n });\n // A hosted home binds nothing: its faces are served through the front. These answer the few\n // questions the gateway asks of loopback addressing, none of which a hosted face reaches.\n const addressing: Addressing = {\n bindAddress: \"\",\n urlHost: options.domains.active,\n origin: () => originOf(options.domains.active),\n hosts: () => [],\n leased: () => undefined,\n leases: () => [],\n listen: () => Promise.reject(new Error(\"A hosted home binds no listener.\")),\n frameMode: () => \"worker\",\n listenFace: () => Promise.reject(new Error(\"A hosted home binds no listener.\")),\n releaseFace: () => undefined,\n faceLocal: () => \"\",\n };\n const bus = createEphemeralBus();\n // Live values a hosted page reads: tallies (counted here, RM-07) and the values its owner's\n // producers push through the relay. No producer runs here: the home runs no artifact code.\n const noPool = new Proxy(\n {},\n {\n get: () => {\n throw new Error(\"A hosted home runs no workers.\");\n },\n },\n ) as Parameters<typeof createLive>[0][\"pool\"];\n const live = createLive({\n ledger,\n log,\n bus,\n pool: noPool,\n interaction,\n latest: () => undefined,\n artifactsWithLive: () => [],\n version: () => undefined,\n });\n // The relay: a hosted page's runs and calls run on its owner instance (D165 item 4).\n const relay = createHostedRelay({\n ledger,\n interaction,\n bus,\n log,\n ownerOf: (artifactId) => ownerLinkOf(artifactId),\n // The newest session of a link is its own: an older one is a connection the owner already\n // left, which the server may hold until its silence limit (Opus review of WP-29, 1).\n sessionOf: (linkId) =>\n protocol\n .registrants(\"relay\")\n .filter((entry) => entry.owner === linkId)\n .at(-1)?.session,\n call: (session, method, params, timeoutMs) =>\n protocol.callSession(session, method, params, timeoutMs),\n functions: (versionId) => readServerFunctions(registry.store.versionDir(versionId)),\n ...(options.relay?.waitingRunsPerArtifact !== undefined\n ? { waitingRunsPerArtifact: options.relay.waitingRunsPerArtifact }\n : {}),\n ...(options.relay?.drainPerSecond !== undefined\n ? { drainPerSecond: options.relay.drainPerSecond }\n : {}),\n ...(options.relay?.sweepMs !== undefined ? { sweepMs: options.relay.sweepMs } : {}),\n ...(options.relay?.liveRenewMs !== undefined ? { liveRenewMs: options.relay.liveRenewMs } : {}),\n ...(options.relay?.perLink !== undefined ? { perLink: options.relay.perLink } : {}),\n latestVersion: (artifactId) =>\n ledger.read(\n (db) =>\n db.get<{ latest_version_id: string | null }>(\n \"SELECT latest_version_id FROM artifact WHERE id = ?\",\n artifactId,\n )?.latest_version_id ?? undefined,\n ),\n storeLive: (artifactId, versionId, produced) => live.relayed(artifactId, versionId, produced),\n });\n /** A page's live reads: they ask the owner for producers, and say when it is away. */\n const hostedLive: Pick<typeof live, \"read\"> = {\n read(page, input) {\n const states = live.read(page, input);\n relay.liveWanted(page.artifactId);\n if (!relay.ownerOffline(page.artifactId)) return states;\n return states.map((state) =>\n state.key.startsWith(\"$tally/\") ? state : { ...state, ownerOffline: true },\n );\n },\n };\n const gateway: Gateway = createGateway({\n ledger,\n log,\n addressing,\n capabilities,\n artifacts: {\n get: (ref) => registry.get(canonicalRef(ref)),\n versionDir: (versionId) => registry.store.versionDir(versionId),\n damage: (versionId) => hostedDamage(registry.store.versionDir(versionId)),\n },\n shellDir: options.shellDir,\n interaction,\n bus,\n actions: relay,\n live: hostedLive,\n // Both channels: a hosted home has no host to narrow them (its owner is a host of it, D165).\n controls: async () => ({ submitChannels: [\"shell\", \"artifact\"] }),\n activated: () => undefined,\n hosted: {\n shellOrigin: () => originOf(options.domains.active),\n servesShell: (origin) => domains.some((domain) => originOf(domain) === origin),\n shellPath: (artifactId) => `/a/${routeOf(artifactId)?.id ?? artifactId}`,\n artifactOrigin: (artifactId, shellOrigin) => {\n const route = routeOf(artifactId);\n const domain = domains.find((candidate) => originOf(candidate) === shellOrigin);\n return route && domain ? originOf(`${route.label}.${domain}`) : undefined;\n },\n },\n });\n /** The faces of a domain: its shell, and a route's frames, opened when first asked for. */\n const shellSpec = (domain: string): FaceSpec => ({\n by: \"hosted\",\n group: `hosted:${domain}`,\n listener: \"shell\",\n via: \"token\",\n lease: false,\n });\n const ensureShell = async (domain: string): Promise<string> => {\n const spec = shellSpec(domain);\n const handle = await gateway.openFace(spec);\n handle.setOrigin(originOf(domain));\n return handle.key;\n };\n const ensureFrame = async (\n domain: string,\n artifactId: string,\n label: string,\n ): Promise<string> => {\n await ensureShell(domain);\n const handle = await gateway.openFace({\n by: \"hosted\",\n group: `hosted:${domain}`,\n listener: \"artifact\",\n artifactId,\n via: \"token\",\n lease: false,\n mode: \"worker\",\n });\n handle.setOrigin(originOf(`${label}.${domain}`));\n return handle.key;\n };\n const notServed = (response: ServerResponse): void => {\n response.writeHead(404, { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" });\n response.end(\n JSON.stringify(\n createDiagnostic(\"MOSTRA_HYGIENE_NOT_SERVED\", {\n message: \"Nothing is served at this path.\",\n }),\n ),\n );\n };\n const serve = async (\n request: IncomingMessage,\n response: ServerResponse,\n at: HostedAddress,\n ): Promise<void> => {\n const artifactId = artifactOfRoute(at.routeId);\n const route = artifactId === undefined ? undefined : routeOf(artifactId);\n if (artifactId === undefined || !route) {\n notServed(response);\n return;\n }\n if (at.kind === \"shell\") {\n // The shell's paths name the route; the gateway's routes name the artifact (§18.4).\n const url = request.url ?? \"/\";\n const prefix = `/a/${at.routeId}`;\n if (!url.startsWith(prefix)) {\n notServed(response);\n return;\n }\n request.url = `/a/${artifactId}${url.slice(prefix.length)}`;\n const key = await ensureShell(at.domain);\n if (!gateway.dispatch(key, request, response)) notServed(response);\n return;\n }\n const key = await ensureFrame(at.domain, artifactId, route.label);\n if (!gateway.dispatch(key, request, response)) notServed(response);\n };\n\n /** The client files of a listing this home doesn't hold yet. */\n const missingOf = (files: readonly string[]): string[] =>\n directory.read((db) =>\n files.filter(\n (sha) => !db.get(\"SELECT 1 FROM home_file WHERE home_id = ? AND sha256 = ?\", id, sha),\n ),\n );\n\n const push = async (params: HostedPushParams, session: Session): Promise<HostedPushResult> => {\n const link = session.link?.instanceId;\n if (link === undefined || session.attributes[\"linkId\"] !== link) {\n throw refuse(\n \"MOSTRA_REMOTE_NOT_OWNER_INSTANCE\",\n \"Only an owner instance's binding pushes versions.\",\n );\n }\n const version = params.version;\n // The identity is checked, not believed: the version ID is a digest of the artifact ID and the\n // two digests (D89), and the listing's digest is the output digest (DATA_MODEL §2).\n if (\n versionIdFor(params.artifactId, version.sourceDigest, version.envDigest) !== version.versionId\n ) {\n throw refuse(\"MOSTRA_HOME_INTEGRITY\", \"The pushed version's ID doesn't match its digests.\");\n }\n const listed = version.listing.map(([path, executable, sha256]) => ({\n path,\n executable,\n sha256,\n }));\n if (listingDigest(listed) !== version.outputDigest) {\n throw refuse(\"MOSTRA_HOME_INTEGRITY\", \"The pushed listing doesn't match the output digest.\");\n }\n const registryEntry = version.listing.find(([path]) => path === \"registry.json\");\n if (!registryEntry || sha256Text(version.registry) !== registryEntry[2]) {\n throw refuse(\n \"MOSTRA_HOME_INTEGRITY\",\n \"The pushed registry.json isn't the one the listing names.\",\n );\n }\n for (const [path] of version.listing) {\n if (!(path === \"registry.json\" || path.startsWith(\"client/\") || path.startsWith(\"server/\"))) {\n throw refuse(\"MOSTRA_HOME_INTEGRITY\", `The listing names ${path}, outside a version.`);\n }\n if (!safeListingPath(path)) {\n throw refuse(\n \"MOSTRA_HOME_INTEGRITY\",\n `The listing names an unsafe path, ${JSON.stringify(path.slice(0, 300))}.`,\n );\n }\n }\n let manifestDoc: { manifest?: unknown; artifactId?: unknown; versionId?: unknown };\n try {\n manifestDoc = JSON.parse(version.manifest) as typeof manifestDoc;\n } catch {\n throw refuse(\"MOSTRA_HOME_INTEGRITY\", \"The pushed manifest.json isn't JSON.\");\n }\n if (\n manifestDoc.artifactId !== params.artifactId ||\n manifestDoc.versionId !== version.versionId\n ) {\n throw refuse(\"MOSTRA_HOME_INTEGRITY\", \"The pushed manifest.json names another version.\");\n }\n const manifest = ArtifactManifest.safeParse(manifestDoc.manifest);\n if (!manifest.success)\n throw refuse(\"MOSTRA_HOME_INTEGRITY\", \"The pushed artifact manifest isn't valid.\");\n\n const route = routeFor(params.artifactId, link);\n if (registry.hasVersion(version.versionId)) {\n const known = registry\n .get({ artifactId: params.artifactId })\n .versions.find((v) => v.id === version.versionId);\n return {\n status: \"complete\",\n versionId: version.versionId,\n number: known?.number ?? version.number,\n route,\n };\n }\n // Only client files are stored: server code never reaches the server (D165 item 3).\n const clientFiles = version.listing.filter(([path]) => path.startsWith(\"client/\"));\n const missing = missingOf([...new Set(clientFiles.map(([, , sha]) => sha))]);\n if (missing.length > 0) {\n pending.set(version.versionId, new Set(missing));\n return { status: \"missing\", files: missing, route };\n }\n pending.delete(version.versionId);\n\n // Every file is here: lay the version out as the gateway serves versions, then commit it.\n const stage = join(\n registry.store.stagingDir,\n `${version.versionId}.push-${process.pid}-${Date.now()}`,\n );\n await rm(stage, { recursive: true, force: true });\n mkdirSync(stage, { recursive: true, mode: 0o700 });\n try {\n writeFileSync(join(stage, \"manifest.json\"), version.manifest);\n writeFileSync(join(stage, \"registry.json\"), version.registry);\n writeFileSync(join(stage, \"lock.yaml\"), version.lock);\n // The full listing, server files included, so the version can be checked as built.\n writeFileSync(join(stage, \"listing.json\"), JSON.stringify(version.listing));\n for (const [path, , sha] of clientFiles) {\n const target = join(stage, ...path.split(\"/\"));\n // Checked again where it lands: nothing a tenant names leaves its own staging directory.\n if (relative(stage, target).startsWith(\"..\") || isAbsolute(relative(stage, target))) {\n throw refuse(\"MOSTRA_HOME_INTEGRITY\", \"The listing names a path outside the version.\");\n }\n mkdirSync(join(target, \"..\"), { recursive: true, mode: 0o700 });\n const stored = join(options.filesDir, sha);\n try {\n linkSync(stored, target);\n } catch {\n await copyFile(stored, target);\n }\n }\n await registry.store.promote(stage, version.versionId);\n } catch (error) {\n await rm(stage, { recursive: true, force: true });\n throw error;\n }\n const committed = registry.commit({\n artifactId: params.artifactId,\n bindingPath: undefined,\n number: version.number,\n manifestId: params.artifactId,\n versionId: version.versionId,\n sourceDigest: version.sourceDigest,\n envDigest: version.envDigest,\n outputDigest: version.outputDigest,\n manifest: manifest.data,\n // The owner's policy in force, as the owner's host decided it (D102): it sticks here.\n policy: version.policy,\n forcedCodes: [],\n stillClaims: () => false,\n });\n directory.write((db) => {\n for (const sha of new Set(clientFiles.map(([, , file]) => file))) {\n const added = db.run(\n \"INSERT OR IGNORE INTO home_file (home_id, sha256) VALUES (?, ?)\",\n id,\n sha,\n );\n if (added.changes > 0) {\n db.run(\n \"INSERT INTO file_ref (sha256, homes) VALUES (?, 1) ON CONFLICT (sha256) DO UPDATE SET homes = homes + 1, unreferenced_at = NULL\",\n sha,\n );\n }\n }\n });\n log.info(\"server.version_pushed\", {\n home: id,\n artifactId: params.artifactId,\n versionId: version.versionId,\n });\n return { status: \"complete\", versionId: version.versionId, number: committed.version, route };\n };\n\n const describe = (): InstanceInfo => {\n const head = ledger.read(\n (db) =>\n db.get<{ cursor: number | null }>(\"SELECT MAX(cursor) AS cursor FROM event\")?.cursor ?? 0,\n );\n return {\n version: options.runtimeVersion,\n home: `hosted:${id}`,\n platform: platformName(),\n pid: process.pid,\n mode: \"hosted\",\n incarnation,\n cursor: String(head),\n };\n };\n\n protocol = new ProtocolServer({\n log,\n describe,\n servesHome: () => false,\n supportedPorts: [\"submissions\", \"relay\"],\n notifications: [\"events/notify\"],\n admit: (session, params) => {\n // The owner instance is the witness a restore can't roll back: a home that holds less than\n // its owner committed, or saw less of its relay, was restored to an earlier copy, and rotates\n // its incarnation before it answers (INTERFACES §18.2).\n const link = params.link;\n if (link !== undefined && link.instanceId === session.attributes[\"linkId\"]) {\n const marks = ledger.read((db) => ({\n head: db.get<{ head: number | null }>(\"SELECT MAX(cursor) AS head FROM event\")?.head ?? 0,\n // What the home knows of the link's relay: its runs, and the highest mark its owner\n // reported, kept so a restore is told once, not at every later reconnect.\n relayHigh: Math.max(\n db.get<{ high: number | null }>(\n \"SELECT MAX(relay_seq) AS high FROM relay_run WHERE owner_link_id = ?\",\n link.instanceId,\n )?.high ?? 0,\n db.get<{ floor: number }>(\n \"SELECT floor FROM relay_floor WHERE link_id = ?\",\n link.instanceId,\n )?.floor ?? 0,\n ),\n }));\n const followedAhead =\n link.followed !== undefined &&\n link.followed.incarnation === incarnation &&\n Number(link.followed.cursor) > marks.head;\n const relayAhead = link.relayMark > marks.relayHigh;\n if (followedAhead || relayAhead) {\n incarnation = rotateIncarnation(ledger);\n log.warn(\"server.home_rotated\", {\n home: id,\n why: followedAhead ? \"owner-cursor\" : \"owner-relay-mark\",\n });\n }\n ledger.write((db) =>\n db.run(\n `INSERT INTO relay_floor (link_id, floor) VALUES (?, ?)\n ON CONFLICT (link_id) DO UPDATE SET floor = MAX(floor, excluded.floor)`,\n link.instanceId,\n link.relayMark,\n ),\n );\n }\n // An owner link is its own grant's: a session can't speak for another instance's link.\n if (params.link !== undefined && params.link.instanceId !== session.attributes[\"linkId\"]) {\n throw refuse(\n \"MOSTRA_REMOTE_NOT_OWNER_INSTANCE\",\n \"This binding's sign-in is for another instance link.\",\n );\n }\n // A session that takes deliveries or relayed runs is an owner instance's, so it names its own\n // link: one without a link could otherwise be taken for an owner by its client name (Opus\n // review of WP-29, 6).\n if (params.link === undefined && params.ports.length > 0) {\n throw refuse(\n \"MOSTRA_REMOTE_NOT_OWNER_INSTANCE\",\n \"A binding that registers ports must name its own instance link.\",\n );\n }\n },\n onInitialized: (session) => {\n interaction.connected(session);\n relay.connected(session);\n },\n onClosed: (session) => {\n interaction.disconnected(session);\n relay.disconnected(session);\n },\n handlers: [\n ...interaction.methods(),\n handler(artifactListMethod, (params) => ({ artifacts: registry.list(params.filter ?? {}) })),\n handler(artifactGetMethod, (params) => registry.get(canonicalRef(params.artifact))),\n handler(hostedPushMethod, (params, session) => push(params, session)),\n handler(hostedSubmissionMethod, (params, session) => {\n // Only the owner instance of its artifact reads a submission this way (D165 item 1b),\n // and only one it was, or is, delivered.\n const link = session.link?.instanceId;\n const envelope =\n link === undefined ? undefined : interaction.envelopeFor(params.submissionId, link);\n if (!envelope) {\n throw refuse(\n \"MOSTRA_HOST_INVALID_PARAMS\",\n `This home delivers no submission ${params.submissionId} to this instance.`,\n );\n }\n return envelope;\n }),\n ...gateway.methods(),\n ...relay.methods(),\n ...liveMethods(live, (ref) => registry.get(canonicalRef(ref)).id),\n handler(remoteTokenMethod, (params, session) => {\n const found = options.auth.authenticate(params.accessToken);\n if (!found || found.grantId !== session.attributes[\"grantId\"]) {\n throw refuse(\n \"MOSTRA_REMOTE_LOGIN_FAILED\",\n \"That access token isn't this binding's grant's.\",\n );\n }\n const replace = session.attributes[\"replaceToken\"] as\n | ((expiresAt: number) => void)\n | undefined;\n replace?.(found.expiresAt);\n return { expiresAt: new Date(found.expiresAt).toISOString() };\n }),\n ],\n });\n interaction.start();\n live.start();\n\n return {\n id,\n dir,\n ledger,\n registry,\n interaction,\n protocol,\n incarnation: () => incarnation,\n wanted: (sha) => [...pending.values()].some((files) => files.has(sha)),\n uploaded(sha) {\n directory.write((db) => {\n const added = db.run(\n \"INSERT OR IGNORE INTO home_file (home_id, sha256) VALUES (?, ?)\",\n id,\n sha,\n );\n if (added.changes > 0) {\n db.run(\n \"INSERT INTO file_ref (sha256, homes) VALUES (?, 1) ON CONFLICT (sha256) DO UPDATE SET homes = homes + 1, unreferenced_at = NULL\",\n sha,\n );\n }\n });\n for (const files of pending.values()) files.delete(sha);\n },\n busy: () => protocol.connections > 0 || bus.activeViews() > 0 || relay.busy(),\n serve,\n async stop() {\n relay.stop();\n live.stop();\n interaction.stop();\n await gateway.close();\n await protocol.close();\n bus.close?.();\n },\n };\n}\n\n/**\n * What is wrong with a hosted version's stored files (FAILURE_MODEL §3): its listing must be the\n * one its output digest names, and every client file it lists present with its bytes. Server files\n * are listed but never stored (D165 item 3).\n */\nasync function hostedDamage(versionDir: string): Promise<string | undefined> {\n try {\n const manifest = JSON.parse(await readFile(join(versionDir, \"manifest.json\"), \"utf8\")) as {\n outputDigest?: string;\n };\n const listing = JSON.parse(await readFile(join(versionDir, \"listing.json\"), \"utf8\")) as [\n string,\n boolean,\n string,\n number,\n ][];\n const listed = listing.map(([path, executable, sha256]) => ({ path, executable, sha256 }));\n if (listingDigest(listed) !== manifest.outputDigest)\n return \"its listing doesn't match its digest\";\n for (const [path, , sha256] of listing) {\n if (!path.startsWith(\"client/\") && path !== \"registry.json\") continue;\n const bytes = await readFile(join(versionDir, ...path.split(\"/\")));\n if (createHash(\"sha256\").update(bytes).digest(\"hex\") !== sha256) return `${path} was changed`;\n }\n return undefined;\n } catch (error) {\n return `a file is missing (${(error as NodeJS.ErrnoException).code ?? \"unreadable\"})`;\n }\n}\n\n/** The SHA-256 of a text's UTF-8 bytes, lowercase hex. */\nfunction sha256Text(text: string): string {\n return createHash(\"sha256\").update(text, \"utf8\").digest(\"hex\");\n}\n","/**\n * The remote server's configuration (INTERFACES §18.1): a JSON file (`--config`) and\n * `MOSTRA_SERVER_<KEY>` variables, read before the server serves anything. A configuration it\n * can't use stops it, naming the key (`MOSTRA_REMOTE_CONFIG_INVALID`). Domains are configuration,\n * never code (D137, D165 item 0a): the dossier and this code name only `example` hosts.\n */\nimport { readFileSync } from \"node:fs\";\nimport { createDiagnostic, Duration, RpcError } from \"@mostra/protocol\";\nimport * as z from \"zod\";\nimport type { Environment } from \"../log.ts\";\n\n/** A rate: `count` per `per` (a duration such as `1m`, as links' lifetimes are written). */\nconst RateSchema: z.ZodType<Rate> = z.object({\n count: z.int().min(1),\n per: Duration,\n});\n\n/** A host name a link can use: lower-case labels of letters, digits and hyphens. */\nconst HostName: z.ZodString = z\n .string()\n .regex(\n /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(:\\d{1,5})?$/,\n {\n message: \"must be a lower-case host name, with a port only for a local test\",\n },\n );\n\n/**\n * An origin the server is reached at: `https:`, or `http:` for loopback and `*.localhost` (tests\n * and a self-hoster's first run).\n */\nconst Origin: z.ZodType<string> = z.string().refine(\n (value) => {\n try {\n const url = new URL(value);\n if (url.origin !== value) return false;\n if (url.protocol === \"https:\") return true;\n return (\n url.protocol === \"http:\" &&\n (url.hostname === \"127.0.0.1\" ||\n url.hostname === \"localhost\" ||\n url.hostname.endsWith(\".localhost\") ||\n url.hostname === \"[::1]\")\n );\n } catch {\n return false;\n }\n },\n { message: \"must be an https: origin (http: only on loopback), with no path\" },\n);\n\n/** A rate limit: `count` per `per`. */\nexport interface Rate {\n readonly count: number;\n readonly per: string;\n}\n\n/** An identity provider sign-in goes through (§18.5); WP-30 adds `oidc` and `github`. */\nexport interface IdentityProviderConfig {\n readonly id: string;\n readonly kind: \"development\" | \"oidc\" | \"github\";\n readonly label?: string | undefined;\n readonly issuer?: string | undefined;\n readonly clientId?: string | undefined;\n readonly clientSecretFile?: string | undefined;\n}\n\n/** The configuration a remote server runs with (INTERFACES §18.1). */\nexport interface RemoteServerConfig {\n readonly apiOrigin: string;\n readonly domains: { readonly active: string; readonly spares?: string[] | undefined };\n readonly scheme?: \"https\" | \"http\" | undefined;\n readonly trustedProxies?: string[] | undefined;\n readonly identityProviders?: IdentityProviderConfig[] | undefined;\n readonly rateLimits?:\n | {\n readonly perIp?:\n | { readonly submissions?: Rate | undefined; readonly requests?: Rate | undefined }\n | undefined;\n readonly perLink?:\n | { readonly submissions?: Rate | undefined; readonly relayedRuns?: Rate | undefined }\n | undefined;\n readonly ipv6Prefix?: number | undefined;\n }\n | undefined;\n readonly ledger?: { readonly walAutocheckpoint?: number | undefined } | undefined;\n readonly relay?:\n | {\n readonly waitingRunsPerArtifact?: number | undefined;\n readonly drainPerSecond?: number | undefined;\n }\n | undefined;\n readonly homes?: { readonly idleCloseMinutes?: number | undefined } | undefined;\n readonly framing?: { readonly frameAncestors: \"'none'\" } | undefined;\n readonly operator?: string | undefined;\n readonly chatHosts?: Record<string, unknown> | undefined;\n}\n\n/** The schema of {@link RemoteServerConfig}. */\nconst Config: z.ZodType<RemoteServerConfig> & { readonly shape: Record<string, unknown> } =\n z.strictObject({\n apiOrigin: Origin,\n domains: z.strictObject({\n active: HostName,\n spares: z.array(HostName).optional(),\n }),\n /**\n * The scheme the user-content domain is served on: `https` behind a TLS terminator, `http`\n * for a loopback test. Default `https`.\n */\n scheme: z.enum([\"https\", \"http\"]).optional(),\n trustedProxies: z.array(z.string()).optional(),\n identityProviders: z\n .array(\n z.strictObject({\n id: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/),\n kind: z.enum([\"development\", \"oidc\", \"github\"]),\n label: z.string().min(1).optional(),\n issuer: z.string().optional(),\n clientId: z.string().optional(),\n clientSecretFile: z.string().optional(),\n }),\n )\n .optional(),\n rateLimits: z\n .strictObject({\n perIp: z\n .strictObject({ submissions: RateSchema.optional(), requests: RateSchema.optional() })\n .optional(),\n perLink: z\n .strictObject({ submissions: RateSchema.optional(), relayedRuns: RateSchema.optional() })\n .optional(),\n ipv6Prefix: z.int().min(1).max(128).optional(),\n })\n .optional(),\n ledger: z.strictObject({ walAutocheckpoint: z.int().min(0).optional() }).optional(),\n relay: z\n .strictObject({\n waitingRunsPerArtifact: z.int().min(1).optional(),\n drainPerSecond: z.number().positive().optional(),\n })\n .optional(),\n homes: z.strictObject({ idleCloseMinutes: z.number().positive().optional() }).optional(),\n framing: z.strictObject({ frameAncestors: z.literal(\"'none'\") }).optional(),\n operator: z.string().optional(),\n chatHosts: z.record(z.string(), z.unknown()).optional(),\n });\n\n/** The configuration keys, and the variable each also comes from. */\nconst KEYS = Object.keys(Config.shape) as (keyof RemoteServerConfig)[];\n\n/** `apiOrigin` → `MOSTRA_SERVER_API_ORIGIN`. */\nfunction variableOf(key: string): string {\n return `MOSTRA_SERVER_${key.replace(/[A-Z]/g, (letter) => `_${letter}`).toUpperCase()}`;\n}\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_REMOTE_CONFIG_INVALID\", { message }));\n}\n\n/**\n * Reads the configuration: the file, then each `MOSTRA_SERVER_<KEY>` (a string for a string key,\n * JSON for the others) over it. Throws `MOSTRA_REMOTE_CONFIG_INVALID` naming the first key it\n * can't use.\n */\nexport function readServerConfig(file: string | undefined, env: Environment): RemoteServerConfig {\n let raw: Record<string, unknown> = {};\n if (file !== undefined) {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch (error) {\n throw invalid(\n `The configuration file ${file} can't be read (${(error as NodeJS.ErrnoException).code ?? \"error\"}).`,\n );\n }\n try {\n const parsed = JSON.parse(text) as unknown;\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"not an object\");\n }\n raw = parsed as Record<string, unknown>;\n } catch {\n throw invalid(`The configuration file ${file} isn't a JSON object.`);\n }\n }\n for (const key of KEYS) {\n const variable = variableOf(key);\n const value = env[variable];\n if (value === undefined || value === \"\") continue;\n const stringKey = key === \"apiOrigin\" || key === \"operator\" || key === \"scheme\";\n if (stringKey) raw[key] = value;\n else {\n try {\n raw[key] = JSON.parse(value) as unknown;\n } catch {\n throw invalid(`${variable} isn't JSON.`);\n }\n }\n }\n const checked = Config.safeParse(raw);\n if (!checked.success) {\n const issue = checked.error.issues[0];\n const path = issue?.path.join(\".\") || \"(configuration)\";\n throw invalid(\n `The configuration key \\`${path}\\` can't be used: ${issue?.message ?? \"invalid\"}.`,\n );\n }\n const config = checked.data;\n const domains = [config.domains.active, ...(config.domains.spares ?? [])];\n const api = new URL(config.apiOrigin).host;\n if (domains.some((domain) => domain === api || api.endsWith(`.${domain}`))) {\n throw invalid(\n \"The configuration key `apiOrigin` can't be on a user-content domain: sign-in and the binding live apart from tenant pages (D165 item 7).\",\n );\n }\n if (new Set(domains).size !== domains.length) {\n throw invalid(\"The configuration key `domains` names one domain twice.\");\n }\n return config;\n}\n","/**\n * The remote server (ARCHITECTURE §15, INTERFACES §18, D165): one process holding many hosted\n * homes behind one listener. It speaks plain HTTP behind a TLS terminator and routes every request\n * by its exact `Host`: the API origin (the network binding, version files, sign-in) or a\n * user-content domain (the hosted shell on its apex, an artifact's pages on its route's label).\n * It runs no artifact code: server code runs on each artifact's owner instance, through the relay.\n *\n * ```ts\n * const server = await startServer({ data: \"/var/lib/mostra\", config: readServerConfig(file, env), … });\n * // … mostra-runtime server serves until it is stopped\n * await server.close();\n * ```\n */\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { join } from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport {\n createDiagnostic,\n type Diagnostic,\n type Duration,\n durationMs,\n RouteId,\n RpcError,\n} from \"@mostra/protocol\";\nimport { locateShell, shellAssetResponse } from \"../gateway/index.ts\";\nimport { appendEvent } from \"../interaction/index.ts\";\nimport type { LedgerOwner } from \"../ledger/index.ts\";\nimport type { Environment, Log } from \"../log.ts\";\nimport { type Api, createApi } from \"./api.ts\";\nimport { type Authorization, createAuthorization } from \"./auth.ts\";\nimport type { RemoteServerConfig } from \"./config.ts\";\nimport { type DataDirectory, type HomeAssembler, openDataDirectory } from \"./data.ts\";\nimport { type HostedHome, openHostedHome } from \"./hosted.ts\";\n\nexport { type RemoteServerConfig, readServerConfig } from \"./config.ts\";\n\n/** Options for {@link startServer}. */\nexport interface ServerOptions {\n /** The data directory (`--data`). */\n readonly data: string;\n readonly config: RemoteServerConfig;\n /** `host:port` to listen on (`--listen`). Default `127.0.0.1:8080`. */\n readonly listen?: string;\n /** Homes restored from a backup by hand (`--restored`): their incarnations rotate first. */\n readonly restored?: readonly string[];\n readonly runtimeVersion: string;\n readonly owner: LedgerOwner;\n readonly log: Log;\n readonly env: Environment;\n}\n\n/** A running remote server. */\nexport interface RemoteServer {\n /** Where it listens: `http://host:port`. */\n readonly address: string;\n readonly config: RemoteServerConfig;\n /** Stops listening, closes every hosted home, then the directory, and releases the locks. */\n close(): Promise<void>;\n}\n\n/** An answer as JSON, with the headers every server answer carries. */\nfunction json(response: ServerResponse, status: number, body: unknown): void {\n const text = JSON.stringify(body);\n response.writeHead(status, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"content-length\": Buffer.byteLength(text),\n \"cache-control\": \"no-store\",\n \"cross-origin-resource-policy\": \"same-origin\",\n \"referrer-policy\": \"no-referrer\",\n \"x-content-type-options\": \"nosniff\",\n });\n response.end(text);\n}\n\nfunction refusal(response: ServerResponse, status: number, diagnostic: Diagnostic): void {\n json(response, status, diagnostic);\n}\n\n/** Splits `host:port`, with `[::1]:port` for IPv6. */\nfunction parseListen(listen: string): { host: string; port: number } {\n const match = /^(\\[[^\\]]+\\]|[^:]+):(\\d{1,5})$/.exec(listen);\n if (!match) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_REMOTE_CONFIG_INVALID\", {\n message: `--listen ${listen} isn't host:port.`,\n }),\n );\n }\n return { host: (match[1] as string).replace(/^\\[|\\]$/g, \"\"), port: Number(match[2]) };\n}\n\n/** Starts the remote server: its data directory, then its listener. */\nexport async function startServer(options: ServerOptions): Promise<RemoteServer> {\n const { config, log } = options;\n // The authorization server is made once the directory is open; homes open only after that.\n let auth: Authorization | undefined;\n const shellDir = locateShell(options.env);\n const assembler: HomeAssembler<HostedHome> = {\n assemble: (home) =>\n openHostedHome({\n id: home.id,\n dir: home.dir,\n ledger: home.ledger,\n incarnation: home.incarnation,\n directory: data.directory,\n filesDir: join(options.data, \"files\"),\n auth: auth as Authorization,\n runtimeVersion: options.runtimeVersion,\n log,\n scheme: config.scheme ?? \"https\",\n domains: { active: config.domains.active, spares: config.domains.spares ?? [] },\n shellDir,\n relay: {\n waitingRunsPerArtifact: config.relay?.waitingRunsPerArtifact,\n drainPerSecond: config.relay?.drainPerSecond,\n ...(config.rateLimits?.perLink?.relayedRuns\n ? {\n perLink: {\n count: config.rateLimits.perLink.relayedRuns.count,\n perMs: durationMs(config.rateLimits.perLink.relayedRuns.per as Duration),\n },\n }\n : {}),\n ...(options.env[\"MOSTRA_TEST_RELAY_LIVE_MS\"] !== undefined\n ? { liveRenewMs: Number(options.env[\"MOSTRA_TEST_RELAY_LIVE_MS\"]) }\n : {}),\n ...(options.env[\"MOSTRA_TEST_RELAY_SWEEP_MS\"] !== undefined\n ? { sweepMs: Number(options.env[\"MOSTRA_TEST_RELAY_SWEEP_MS\"]) }\n : {}),\n },\n }),\n disassemble: (home) => home.stop(),\n incarnation: (home) => home.incarnation(),\n busy: (home) => home.busy(),\n };\n const data: DataDirectory<HostedHome> = await openDataDirectory({\n dir: options.data,\n runtimeVersion: options.runtimeVersion,\n owner: options.owner,\n log,\n env: options.env,\n assembler,\n ...(options.restored !== undefined ? { restored: options.restored } : {}),\n ...(config.homes?.idleCloseMinutes !== undefined\n ? { idleCloseMs: config.homes.idleCloseMinutes * 60_000 }\n : {}),\n ...(config.ledger?.walAutocheckpoint !== undefined\n ? { walAutocheckpoint: config.ledger.walAutocheckpoint }\n : {}),\n });\n auth = createAuthorization({\n directory: data.directory,\n config,\n log,\n ...(Number(options.env[\"MOSTRA_TEST_ACCESS_TTL_MS\"]) > 0\n ? { accessTtlMs: Number(options.env[\"MOSTRA_TEST_ACCESS_TTL_MS\"]) }\n : {}),\n // A new instance link is a hosted event the account's instances see (§18.5).\n linked: ({ homeId, linkId, name }) => {\n void data.home(homeId).then(\n (home) =>\n home.assembled.ledger.write((db) =>\n appendEvent(db, {\n artifactId: null,\n type: \"instance.linked\",\n actor: { kind: \"mostra\" },\n payload: { instanceId: linkId, name },\n }),\n ),\n (error: unknown) => log.error(\"server.linked_event_failed\", { home: homeId, error }),\n );\n },\n });\n const api: Api = createApi({\n config,\n auth,\n log,\n filesDir: join(options.data, \"files\"),\n home: async (id) => (await data.home(id)).assembled,\n touch: (id) => data.touch(id),\n ...(Number(options.env[\"MOSTRA_TEST_GRANT_RECHECK_MS\"]) > 0\n ? { recheckMs: Number(options.env[\"MOSTRA_TEST_GRANT_RECHECK_MS\"]) }\n : {}),\n });\n const apiHost = new URL(config.apiOrigin).host;\n const domains = new Set([config.domains.active, ...(config.domains.spares ?? [])]);\n\n const onRequest = (request: IncomingMessage, response: ServerResponse): void => {\n const host = (request.headers.host ?? \"\").toLowerCase();\n // Cookies never reach anything on a hosted host (D165 item 8): dropped before routing.\n delete request.headers.cookie;\n const path = (request.url ?? \"/\").split(\"?\")[0] ?? \"/\";\n if (host === apiHost) {\n if (request.method === \"GET\" && path === \"/health\") {\n json(response, 200, { status: \"ok\", homes: data.open().length });\n return;\n }\n api.request(request, response, path).catch((error: unknown) => {\n log.error(\"server.api_failed\", { path, error });\n if (!response.headersSent) {\n refusal(\n response,\n 500,\n createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: \"The server failed to answer.\",\n }),\n );\n } else response.destroy();\n });\n return;\n }\n const domain = [...domains].find(\n (candidate) => host === candidate || host.endsWith(`.${candidate}`),\n );\n if (domain === undefined) {\n refusal(\n response,\n 421,\n createDiagnostic(\"MOSTRA_HYGIENE_HOST_REFUSED\", {\n message: \"This server serves no pages at this host.\",\n }),\n );\n return;\n }\n // Every hosted answer keeps its page in an agent cluster of its own and out of indexes\n // (ARCHITECTURE §15.6, D161).\n response.setHeader(\"origin-agent-cluster\", \"?1\");\n response.setHeader(\"x-robots-tag\", \"noindex\");\n hosted(request, response, host, domain, path).catch((error: unknown) => {\n log.error(\"server.hosted_failed\", { error });\n if (!response.headersSent) {\n refusal(\n response,\n 500,\n createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: \"The server failed to answer.\",\n }),\n );\n } else response.destroy();\n });\n };\n\n const notServed = (response: ServerResponse): void =>\n refusal(\n response,\n 404,\n createDiagnostic(\"MOSTRA_HYGIENE_NOT_SERVED\", { message: \"Nothing is served at this path.\" }),\n );\n\n /** The shell's own files, the same on every domain's apex. */\n const assets = getRequestListener(\n async (request: Request) =>\n (shellDir === undefined ? undefined : await shellAssetResponse(shellDir, request)) ??\n new Response(\n JSON.stringify(\n createDiagnostic(\"MOSTRA_HYGIENE_NOT_SERVED\", { message: \"No shell file at this path.\" }),\n ),\n {\n status: 404,\n headers: { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" },\n },\n ),\n { overrideGlobalObjects: false },\n );\n\n /** A route of the directory: its home and ID, by ID or by label. */\n const routeBy = (column: \"id\" | \"label\", value: string) =>\n data.directory.read((db) =>\n db.get<{ id: string; home_id: string }>(\n `SELECT id, home_id FROM artifact_route WHERE ${column} = ?`,\n value,\n ),\n );\n\n /** A request on a user-content domain: the shell on its apex, a route's frames on its label. */\n const hosted = async (\n request: IncomingMessage,\n response: ServerResponse,\n host: string,\n domain: string,\n path: string,\n ): Promise<void> => {\n if (host === domain) {\n if (path.startsWith(\"/_mostra/shell/assets/\")) {\n await assets(request, response);\n return;\n }\n const match = /^\\/a\\/(rte_[0-9A-HJKMNP-TV-Z]{26})(?:\\/|$)/.exec(path);\n const route =\n match?.[1] !== undefined && RouteId.is(match[1]) ? routeBy(\"id\", match[1]) : undefined;\n if (!route) {\n notServed(response);\n return;\n }\n const home = await data.home(route.home_id);\n await home.assembled.serve(request, response, { kind: \"shell\", domain, routeId: route.id });\n return;\n }\n // One DNS label under the domain: a route's label, never issued twice (§18.4).\n const label = host.slice(0, host.length - domain.length - 1);\n const route = /^[0-9a-hjkmnp-tv-z]{26}$/.test(label) ? routeBy(\"label\", label) : undefined;\n if (!route) {\n refusal(\n response,\n 421,\n createDiagnostic(\"MOSTRA_HYGIENE_HOST_REFUSED\", {\n message: \"This server serves no pages at this host.\",\n }),\n );\n return;\n }\n const home = await data.home(route.home_id);\n await home.assembled.serve(request, response, { kind: \"frame\", domain, routeId: route.id });\n };\n\n const listener: Server = createServer({ maxHeaderSize: 64 * 1024 }, onRequest);\n listener.keepAliveTimeout = 305_000;\n listener.headersTimeout = 30_000;\n listener.requestTimeout = 120_000;\n listener.on(\"upgrade\", (request: IncomingMessage, socket: Duplex, head: Buffer) => {\n const host = (request.headers.host ?? \"\").toLowerCase();\n const path = (request.url ?? \"/\").split(\"?\")[0] ?? \"/\";\n if (host === apiHost) {\n api.upgrade(request, socket, head, path);\n return;\n }\n socket.end(\"HTTP/1.1 404 Not Found\\r\\nconnection: close\\r\\ncontent-length: 0\\r\\n\\r\\n\");\n });\n const { host, port } = parseListen(options.listen ?? \"127.0.0.1:8080\");\n try {\n await new Promise<void>((resolve, reject) => {\n listener.once(\"error\", reject);\n listener.listen(port, host, () => {\n listener.off(\"error\", reject);\n resolve();\n });\n });\n } catch (error) {\n await data.close();\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BIND_FAILED\", {\n message: `The server can't listen on ${host}:${port}: ${(error as NodeJS.ErrnoException).code ?? (error as Error).message}.`,\n }),\n );\n }\n const bound = listener.address() as AddressInfo;\n const address = `http://${bound.family === \"IPv6\" ? `[${bound.address}]` : bound.address}:${bound.port}`;\n log.info(\"server.listening\", { address, apiOrigin: config.apiOrigin, domains: [...domains] });\n let closing: Promise<void> | undefined;\n return {\n address,\n config,\n close() {\n closing ??= (async () => {\n api.close();\n await new Promise<void>((resolve) => {\n listener.close(() => resolve());\n listener.closeAllConnections();\n });\n await data.close();\n log.info(\"server.stopped\", {});\n })();\n return closing;\n },\n };\n}\n","#!/usr/bin/env node\nimport { mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n/**\n * `mostra-runtime`, the runtime bundle's entry point (D85).\n *\n * mostra-runtime host [--home <dir>] the host protocol over stdio (`mostra host`)\n * mostra-runtime daemon [--home <dir>] [--always-on]\n * the home's daemon on its socket (`mostra daemon start`);\n * it exits after 30 idle minutes unless `--always-on`\n * mostra-runtime service install|uninstall|status [--home <dir>] [--no-start]\n * the home's login service (`mostra daemon install`, D62):\n * one JSON line with the service's file and state\n *\n * Both take `--bind <address>` to serve viewers on an address other than 127.0.0.1, and\n * `--url-host <name>`, the host name links use, which a wildcard address needs (D99). Neither is\n * remembered: every wider start is explicit.\n *\n * `daemon` prints one JSON line on stdout: `{\"status\":\"started\",…}` when it took the home,\n * `{\"status\":\"attached\",…}` when another daemon already owns it (then it exits 0), or\n * `{\"status\":\"failed\",\"diagnostic\":…}` (exit 3). `host` speaks only the protocol on stdout; when it\n * can't start, it answers the host's first request with the diagnostic and exits 3. Logs go to\n * `<home>/logs/supervisor.log`; warnings and errors are mirrored to stderr.\n */\nimport { parseArgs } from \"node:util\";\nimport {\n createDiagnostic,\n type Diagnostic,\n encodeLine,\n LineSplitter,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport { checkPlatform, resolveHomePath } from \"./home/index.ts\";\nimport { type Instance, runtimeVersion, startInstance } from \"./instance/index.ts\";\nimport { openFileLog } from \"./log.ts\";\nimport { readProcess, realPath } from \"./platform/index.ts\";\n\nimport { readServerConfig, startServer } from \"./server/index.ts\";\nimport { installService, serviceStatus, uninstallService } from \"./service/index.ts\";\n\n/** Exit codes, as INTERFACES §9 defines them for the CLI. */\nconst EXIT = { ok: 0, failure: 1, usage: 2, environment: 3 } as const;\n\nconst USAGE = [\n \"usage: mostra-runtime <host|daemon> [--home <dir>] [--bind <address> [--url-host <name>]] [--always-on]\",\n \" mostra-runtime service <install|uninstall|status> [--home <dir>] [--no-start]\",\n \" mostra-runtime server --data <dir> [--config <file>] [--listen <host:port>] [--restored <homeId|all>]\",\n].join(\"\\n\");\n\n// A closed stdout or stderr (a starter that read the ready line and left) must not crash the\n// supervisor.\nprocess.stdout.on(\"error\", () => {});\nprocess.stderr.on(\"error\", () => {});\n\nconst mirror = (line: string): void => {\n process.stderr.write(line);\n};\n\nfunction diagnosticOf(error: unknown): Diagnostic {\n if (error instanceof RpcError) return error.diagnostic;\n return createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: `mostra-runtime failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`,\n });\n}\n\n/**\n * In host mode, a supervisor that can't start still speaks the protocol: it answers the host's\n * requests with the diagnostic, then exits once the first is answered or stdin ends.\n */\nfunction refuseOverStdio(diagnostic: Diagnostic, exitCode: number): void {\n mirror(`${JSON.stringify({ level: \"error\", diagnostic })}\\n`);\n const splitter = new LineSplitter();\n const exit = (): void => {\n process.stdout.write(\"\", () => process.exit(exitCode));\n };\n const peer = new RpcPeer({\n send: (message) => {\n process.stdout.write(encodeLine(message));\n },\n onRequest: () => {\n setImmediate(exit);\n throw new RpcError(diagnostic);\n },\n });\n process.stdin.setEncoding(\"utf8\");\n process.stdin.on(\"data\", (chunk: string) => {\n try {\n for (const line of splitter.push(chunk)) peer.receiveLine(line);\n } catch {\n exit();\n }\n });\n process.stdin.on(\"end\", exit);\n process.stdin.on(\"error\", exit);\n setTimeout(exit, 30_000).unref();\n}\n\nfunction handleSignals(instance: Instance): void {\n // SIGTERM and SIGINT on POSIX; on Windows Ctrl+C and Ctrl+Break reach a console process as\n // SIGINT and SIGBREAK, and everything else stops it over the protocol (`mostra/shutdown`, D87).\n for (const signal of [\"SIGTERM\", \"SIGINT\", \"SIGBREAK\"] as const) {\n process.on(signal, () => void instance.stop(signal, EXIT.ok));\n }\n process.on(\"SIGPIPE\", () => {});\n // Last resort: children never outlive an exiting supervisor (FAILURE_MODEL §2).\n process.on(\"exit\", () => instance.processes.killAll());\n process.on(\"uncaughtException\", (error) => {\n mirror(`${JSON.stringify({ level: \"error\", event: \"uncaught\", message: error.message })}\\n`);\n // The home's log keeps what failed and where, so a failure nobody watched stderr for still\n // names its cause (#35: an instance that ended with only \"uncaught exception\" in its log).\n void instance.stop(\n \"uncaught exception\",\n EXIT.failure,\n createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: (error instanceof Error\n ? (error.stack ?? `${error.name}: ${error.message}`)\n : String(error)\n ).slice(0, 8192),\n }),\n );\n setTimeout(() => process.exit(EXIT.failure), 15_000).unref();\n });\n}\n\nasync function main(argv: readonly string[]): Promise<number> {\n let parsed: ReturnType<typeof parse>;\n try {\n parsed = parse(argv);\n } catch (error) {\n process.stderr.write(`${(error as Error).message}\\n${USAGE}\\n`);\n return EXIT.usage;\n }\n const { values, positionals } = parsed;\n if (values.version) {\n process.stdout.write(`${runtimeVersion()}\\n`);\n return EXIT.ok;\n }\n const [mode, ...rest] = positionals;\n if (mode === \"service\" && !values.help)\n return await service(rest, values.home, values[\"no-start\"] === true);\n if (mode === \"server\" && !values.help && rest.length === 0) {\n return await remoteServer({\n data: values.data,\n config: values.config,\n listen: values.listen,\n restored: values.restored ?? [],\n });\n }\n if (values.help || (mode !== \"host\" && mode !== \"daemon\") || rest.length > 0) {\n (values.help ? process.stdout : process.stderr).write(`${USAGE}\\n`);\n return values.help ? EXIT.ok : EXIT.usage;\n }\n\n try {\n const started = await startInstance({\n mode,\n home: values.home,\n bind: values.bind,\n urlHost: values[\"url-host\"],\n alwaysOn: values[\"always-on\"] === true,\n mirror,\n ...(mode === \"host\" ? { stdio: { input: process.stdin, output: process.stdout } } : {}),\n });\n if (started.kind === \"attached\") {\n process.stdout.write(\n `${JSON.stringify({\n status: \"attached\",\n pid: started.record.pid,\n home: started.result.instance.home,\n socket: started.record.socket,\n revision: started.result.revision,\n })}\\n`,\n );\n return EXIT.ok;\n }\n const { instance } = started;\n handleSignals(instance);\n if (mode === \"daemon\") {\n process.stdout.write(\n `${JSON.stringify({\n status: \"started\",\n pid: instance.info.pid,\n home: instance.info.home,\n socket: instance.socketPath,\n reaped: instance.reaped.filter((child) => child.signalled.length > 0).length,\n })}\\n`,\n );\n }\n const stop = await instance.stopped;\n return stop.exitCode;\n } catch (error) {\n const diagnostic = diagnosticOf(error);\n const exitCode = error instanceof RpcError ? EXIT.environment : EXIT.failure;\n if (mode === \"host\") {\n refuseOverStdio(diagnostic, exitCode);\n return new Promise<number>(() => {});\n }\n process.stdout.write(`${JSON.stringify({ status: \"failed\", diagnostic })}\\n`);\n mirror(`${JSON.stringify({ level: \"error\", diagnostic })}\\n`);\n return exitCode;\n }\n}\n\n/**\n * `mostra-runtime server`: the remote server (INTERFACES §18.1). Prints one JSON line on stdout\n * (`{\"status\":\"started\",\"address\",…}` or `{\"status\":\"failed\",\"diagnostic\"}` with exit 3), then\n * serves until SIGTERM, SIGINT or Ctrl+Break, and stops cleanly: every hosted home is closed and\n * every lock released. Logs go to the data directory's `logs/`.\n */\nasync function remoteServer(args: {\n readonly data: string | undefined;\n readonly config: string | undefined;\n readonly listen: string | undefined;\n readonly restored: readonly string[];\n}): Promise<number> {\n if (args.data === undefined) {\n process.stderr.write(`mostra-runtime server needs --data <dir>.\\n${USAGE}\\n`);\n return EXIT.usage;\n }\n try {\n checkPlatform();\n mkdirSync(args.data, { recursive: true, mode: 0o700 });\n const data = realPath(args.data);\n const config = readServerConfig(args.config, process.env);\n const me = await readProcess(process.pid);\n if (!me) throw new Error(\"Couldn't read this process's own start time.\");\n const log = openFileLog({ dir: join(data, \"logs\"), mirror });\n const server = await startServer({\n data,\n config,\n ...(args.listen !== undefined ? { listen: args.listen } : {}),\n restored: args.restored,\n runtimeVersion: runtimeVersion(),\n owner: { pid: me.pid, startTime: me.startTime },\n log,\n env: process.env,\n });\n process.stdout.write(\n `${JSON.stringify({ status: \"started\", pid: process.pid, address: server.address, data })}\\n`,\n );\n return await new Promise<number>((resolve) => {\n let stopping = false;\n const stop = (): void => {\n if (stopping) return;\n stopping = true;\n void server.close().then(\n () => resolve(EXIT.ok),\n (error: unknown) => {\n log.error(\"server.stop_failed\", { error });\n resolve(EXIT.failure);\n },\n );\n };\n for (const signal of [\"SIGTERM\", \"SIGINT\", \"SIGBREAK\"] as const) process.on(signal, stop);\n });\n } catch (error) {\n const diagnostic = diagnosticOf(error);\n process.stdout.write(`${JSON.stringify({ status: \"failed\", diagnostic })}\\n`);\n mirror(`${JSON.stringify({ level: \"error\", diagnostic })}\\n`);\n return error instanceof RpcError ? EXIT.environment : EXIT.failure;\n }\n}\n\n/** `mostra-runtime service …`: the home's login service, as one JSON line (D62, RT-08). */\nasync function service(\n args: readonly string[],\n home: string | undefined,\n noStart: boolean,\n): Promise<number> {\n const [action, ...extra] = args;\n if ((action !== \"install\" && action !== \"uninstall\" && action !== \"status\") || extra.length > 0) {\n process.stderr.write(`${USAGE}\\n`);\n return EXIT.usage;\n }\n const gate = checkPlatform();\n if (gate) {\n process.stdout.write(`${JSON.stringify({ status: \"failed\", diagnostic: gate })}\\n`);\n return EXIT.environment;\n }\n try {\n const resolved = resolveHomePath({ home, env: process.env });\n mkdirSync(resolved, { recursive: true, mode: 0o700 });\n const spec = {\n // As the daemon spells its home, so the service's name and hash are the daemon's (D82).\n home: realPath(resolved),\n node: process.execPath,\n entry: fileURLToPath(import.meta.url),\n };\n // Who asks, should a Windows uninstall stop the daemon over its pipe.\n const client = { name: \"mostra-runtime-service\", version: runtimeVersion() };\n const status =\n action === \"install\"\n ? await installService(spec, { noStart, client })\n : action === \"uninstall\"\n ? await uninstallService(spec, { noStart, client })\n : serviceStatus(spec);\n process.stdout.write(`${JSON.stringify({ status: \"ok\", action, service: status })}\\n`);\n return EXIT.ok;\n } catch (error) {\n const diagnostic = diagnosticOf(error);\n process.stdout.write(`${JSON.stringify({ status: \"failed\", diagnostic })}\\n`);\n return EXIT.environment;\n }\n}\n\nfunction parse(argv: readonly string[]) {\n return parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n home: { type: \"string\" },\n bind: { type: \"string\" },\n \"url-host\": { type: \"string\" },\n \"always-on\": { type: \"boolean\" },\n \"no-start\": { type: \"boolean\" },\n help: { type: \"boolean\", short: \"h\" },\n version: { type: \"boolean\" },\n data: { type: \"string\" },\n config: { type: \"string\" },\n listen: { type: \"string\" },\n restored: { type: \"string\", multiple: true },\n },\n });\n}\n\nconst code = await main(process.argv.slice(2));\n// Let stdout drain before exiting, so the status line is never cut off.\nprocess.stdout.write(\"\", () => process.exit(code));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,gCAA6C,IAAI,IAAI;CACzD,CAAC,OAAQ,KAAK;CACd,CAAC,OAAQ,KAAK;CACd,CAAC,YAAY,MAAM;CACnB,CAAC,YAAY,MAAM;CACnB,CAAC,UAAY,MAAM;CACnB,CAAC,YAAY,KAAK;CAClB,CAAC,YAAY,MAAM;CACnB,CAAC,UAAY,IAAI;CACjB,CAAC,YAAY,MAAM;AACrB,CAAC;AAED,MAAM,cAAc;;AAGpB,SAAgB,kBAAkB,KAAiC;CACjE,IAAI,QAAQ,aAAa,SACvB,IAAI;EAEF,MAAM,OAAO,WAAW,GAAG,CAAC,CAAC,SAAS;EACtC,OAAO,cAAc,IAAI,IAAI;CAC/B,QAAQ;EACN;CACF;CAEF,IAAI,QAAQ,a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