@mostra/runtime 0.10.0 → 0.12.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 (257) hide show
  1. package/dist/bin.js +4178 -310
  2. package/dist/bin.js.map +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/{instance-FExcyENK.js → instance-CBUlOmzG.js} +1892 -85
  6. package/dist/instance-CBUlOmzG.js.map +1 -0
  7. package/dist/reference/cli.md +1432 -0
  8. package/dist/reference/diagnostics.json +1579 -0
  9. package/dist/reference/errors/MOSTRA_A11Y_MINOR.md +23 -0
  10. package/dist/reference/errors/MOSTRA_A11Y_SERIOUS.md +23 -0
  11. package/dist/reference/errors/MOSTRA_ACTION_CANCELLED.md +23 -0
  12. package/dist/reference/errors/MOSTRA_ACTION_EVENT_INVALID.md +23 -0
  13. package/dist/reference/errors/MOSTRA_ACTION_EXPORT_INVALID.md +23 -0
  14. package/dist/reference/errors/MOSTRA_ACTION_INTERRUPTED.md +23 -0
  15. package/dist/reference/errors/MOSTRA_ACTION_PAUSED.md +23 -0
  16. package/dist/reference/errors/MOSTRA_ACTION_RUN_NOT_FOUND.md +23 -0
  17. package/dist/reference/errors/MOSTRA_ACTION_THREW.md +23 -0
  18. package/dist/reference/errors/MOSTRA_ACTION_TOO_LARGE.md +23 -0
  19. package/dist/reference/errors/MOSTRA_ACTION_UNKNOWN_FUNCTION.md +23 -0
  20. package/dist/reference/errors/MOSTRA_ACTION_UNSERIALIZABLE.md +23 -0
  21. package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
  22. package/dist/reference/errors/MOSTRA_ARTIFACT_DIR_NOT_EMPTY.md +23 -0
  23. package/dist/reference/errors/MOSTRA_ARTIFACT_ENTRY_AMBIGUOUS.md +23 -0
  24. package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
  25. package/dist/reference/errors/MOSTRA_ARTIFACT_NOT_FOUND.md +23 -0
  26. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_ENTRY.md +23 -0
  27. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_PAGE.md +23 -0
  28. package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
  29. package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
  30. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_MISSING.md +23 -0
  31. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_UNREADABLE.md +23 -0
  32. package/dist/reference/errors/MOSTRA_ARTIFACT_TEMPLATE_UNKNOWN.md +23 -0
  33. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_COLLECTED.md +23 -0
  34. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_NOT_FOUND.md +23 -0
  35. package/dist/reference/errors/MOSTRA_BUILD_CRASHED.md +23 -0
  36. package/dist/reference/errors/MOSTRA_BUILD_FAILED.md +23 -0
  37. package/dist/reference/errors/MOSTRA_BUILD_TIMEOUT.md +23 -0
  38. package/dist/reference/errors/MOSTRA_BUILD_UNRESOLVED.md +23 -0
  39. package/dist/reference/errors/MOSTRA_CLI_CONFIG_UNWRITABLE.md +23 -0
  40. package/dist/reference/errors/MOSTRA_CLI_UNKNOWN_COMMAND.md +23 -0
  41. package/dist/reference/errors/MOSTRA_CLI_USAGE.md +23 -0
  42. package/dist/reference/errors/MOSTRA_CONSOLE_ERROR.md +23 -0
  43. package/dist/reference/errors/MOSTRA_CONSOLE_WARNING.md +23 -0
  44. package/dist/reference/errors/MOSTRA_DEP_INSTALL_FAILED.md +23 -0
  45. package/dist/reference/errors/MOSTRA_DEP_MISSING.md +23 -0
  46. package/dist/reference/errors/MOSTRA_DEP_NOT_FOUND.md +23 -0
  47. package/dist/reference/errors/MOSTRA_DEP_OFFLINE.md +23 -0
  48. package/dist/reference/errors/MOSTRA_DEP_SPEC_INVALID.md +23 -0
  49. package/dist/reference/errors/MOSTRA_DEP_TIMEOUT.md +23 -0
  50. package/dist/reference/errors/MOSTRA_DEP_WARM_CONFLICT.md +23 -0
  51. package/dist/reference/errors/MOSTRA_ENV_BIND_FAILED.md +23 -0
  52. package/dist/reference/errors/MOSTRA_ENV_BROWSER_MISSING.md +23 -0
  53. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED.md +23 -0
  54. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_INVALID.md +23 -0
  55. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_UNAVAILABLE.md +23 -0
  56. package/dist/reference/errors/MOSTRA_ENV_HELPER_MISSING.md +23 -0
  57. package/dist/reference/errors/MOSTRA_ENV_NODE_UNSUPPORTED.md +23 -0
  58. package/dist/reference/errors/MOSTRA_ENV_PORT_TAKEN.md +23 -0
  59. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
  60. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_MISSING.md +23 -0
  61. package/dist/reference/errors/MOSTRA_ENV_SERVICE_FAILED.md +23 -0
  62. package/dist/reference/errors/MOSTRA_ENV_SHELL_MISSING.md +23 -0
  63. package/dist/reference/errors/MOSTRA_ENV_WARM_MISSING.md +23 -0
  64. package/dist/reference/errors/MOSTRA_FIELD_CONFLICT.md +23 -0
  65. package/dist/reference/errors/MOSTRA_FIELD_DUPLICATE_ID.md +23 -0
  66. package/dist/reference/errors/MOSTRA_FIELD_ID_INVALID.md +23 -0
  67. package/dist/reference/errors/MOSTRA_FIELD_ID_UNSTABLE.md +23 -0
  68. package/dist/reference/errors/MOSTRA_FIELD_MUTATION_ID_REUSED.md +23 -0
  69. package/dist/reference/errors/MOSTRA_FIELD_SHARED.md +23 -0
  70. package/dist/reference/errors/MOSTRA_FIELD_TOO_LARGE.md +23 -0
  71. package/dist/reference/errors/MOSTRA_FIELD_UNBOUND.md +23 -0
  72. package/dist/reference/errors/MOSTRA_HOME_DISK_FULL.md +23 -0
  73. package/dist/reference/errors/MOSTRA_HOME_GC_INCOMPLETE.md +23 -0
  74. package/dist/reference/errors/MOSTRA_HOME_GONE.md +23 -0
  75. package/dist/reference/errors/MOSTRA_HOME_INTEGRITY.md +23 -0
  76. package/dist/reference/errors/MOSTRA_HOME_LEDGER_UNREADABLE.md +23 -0
  77. package/dist/reference/errors/MOSTRA_HOME_LOCKED.md +23 -0
  78. package/dist/reference/errors/MOSTRA_HOME_MISMATCH.md +23 -0
  79. package/dist/reference/errors/MOSTRA_HOME_NETWORK_FILESYSTEM.md +23 -0
  80. package/dist/reference/errors/MOSTRA_HOME_NOT_ALWAYS_ON.md +23 -0
  81. package/dist/reference/errors/MOSTRA_HOME_NOT_OWNED.md +23 -0
  82. package/dist/reference/errors/MOSTRA_HOME_SOCKET_TOO_LONG.md +23 -0
  83. package/dist/reference/errors/MOSTRA_HOME_TOO_NEW.md +23 -0
  84. package/dist/reference/errors/MOSTRA_HOST_CONNECTION_CLOSED.md +23 -0
  85. package/dist/reference/errors/MOSTRA_HOST_CURSOR_COMPACTED.md +23 -0
  86. package/dist/reference/errors/MOSTRA_HOST_IDENTITY_UNAVAILABLE.md +23 -0
  87. package/dist/reference/errors/MOSTRA_HOST_INITIALIZE_ORDER.md +23 -0
  88. package/dist/reference/errors/MOSTRA_HOST_INTERNAL_ERROR.md +23 -0
  89. package/dist/reference/errors/MOSTRA_HOST_INVALID_PARAMS.md +23 -0
  90. package/dist/reference/errors/MOSTRA_HOST_MALFORMED.md +23 -0
  91. package/dist/reference/errors/MOSTRA_HOST_MESSAGE_TOO_LARGE.md +23 -0
  92. package/dist/reference/errors/MOSTRA_HOST_METHOD_UNKNOWN.md +23 -0
  93. package/dist/reference/errors/MOSTRA_HOST_NOTIFICATION_UNSUPPORTED.md +23 -0
  94. package/dist/reference/errors/MOSTRA_HOST_PORT_UNSUPPORTED.md +23 -0
  95. package/dist/reference/errors/MOSTRA_HOST_REQUEST_ID_REUSED.md +23 -0
  96. package/dist/reference/errors/MOSTRA_HOST_REVISION_UNSUPPORTED.md +23 -0
  97. package/dist/reference/errors/MOSTRA_HOST_SHUTDOWN_REFUSED.md +23 -0
  98. package/dist/reference/errors/MOSTRA_HOST_SUBSCRIPTION_UNKNOWN.md +23 -0
  99. package/dist/reference/errors/MOSTRA_HOST_TIMEOUT.md +23 -0
  100. package/dist/reference/errors/MOSTRA_HYGIENE_CONTENT_TYPE.md +23 -0
  101. package/dist/reference/errors/MOSTRA_HYGIENE_CSRF_MISSING.md +23 -0
  102. package/dist/reference/errors/MOSTRA_HYGIENE_FRAME_SESSION.md +23 -0
  103. package/dist/reference/errors/MOSTRA_HYGIENE_HEADERS_TOO_LARGE.md +23 -0
  104. package/dist/reference/errors/MOSTRA_HYGIENE_HOST_REFUSED.md +23 -0
  105. package/dist/reference/errors/MOSTRA_HYGIENE_NOT_SERVED.md +23 -0
  106. package/dist/reference/errors/MOSTRA_HYGIENE_ORIGIN_REFUSED.md +23 -0
  107. package/dist/reference/errors/MOSTRA_HYGIENE_RATE_LIMITED.md +23 -0
  108. package/dist/reference/errors/MOSTRA_HYGIENE_REQUEST_MALFORMED.md +23 -0
  109. package/dist/reference/errors/MOSTRA_HYGIENE_SCOPE_DENIED.md +23 -0
  110. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_CONFLICT.md +23 -0
  111. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_MISSING.md +23 -0
  112. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_INVALID.md +23 -0
  113. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_REVOKED.md +23 -0
  114. package/dist/reference/errors/MOSTRA_LIVE_SOURCE_FAILED.md +23 -0
  115. package/dist/reference/errors/MOSTRA_LIVE_TOO_LARGE.md +23 -0
  116. package/dist/reference/errors/MOSTRA_MANIFEST_INVALID.md +23 -0
  117. package/dist/reference/errors/MOSTRA_MANIFEST_NOT_LITERAL.md +23 -0
  118. package/dist/reference/errors/MOSTRA_MANIFEST_UNKNOWN_KEY.md +23 -0
  119. package/dist/reference/errors/MOSTRA_NETWORK_EXTERNAL_FAILED.md +23 -0
  120. package/dist/reference/errors/MOSTRA_NETWORK_REQUEST_FAILED.md +23 -0
  121. package/dist/reference/errors/MOSTRA_PLATFORM_UNSUPPORTED.md +23 -0
  122. package/dist/reference/errors/MOSTRA_PUBLISH_ID_CONFLICT.md +23 -0
  123. package/dist/reference/errors/MOSTRA_PUBLISH_SOURCE_CHANGED.md +23 -0
  124. package/dist/reference/errors/MOSTRA_PUBLISH_VERIFY_FAILED.md +23 -0
  125. package/dist/reference/errors/MOSTRA_REGRESSION_ACTION_REMOVED.md +23 -0
  126. package/dist/reference/errors/MOSTRA_REGRESSION_ARIA.md +23 -0
  127. package/dist/reference/errors/MOSTRA_REGRESSION_FIELD_REMOVED.md +23 -0
  128. package/dist/reference/errors/MOSTRA_REGRESSION_LIVE_REMOVED.md +23 -0
  129. package/dist/reference/errors/MOSTRA_REGRESSION_PAGE_REMOVED.md +23 -0
  130. package/dist/reference/errors/MOSTRA_REGRESSION_PIXELS.md +23 -0
  131. package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
  132. package/dist/reference/errors/MOSTRA_REMOTE_HOME_MOVING.md +23 -0
  133. package/dist/reference/errors/MOSTRA_REMOTE_HOME_SUSPENDED.md +23 -0
  134. package/dist/reference/errors/MOSTRA_REMOTE_LIMIT_REACHED.md +23 -0
  135. package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
  136. package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
  137. package/dist/reference/errors/MOSTRA_REMOTE_NO_INSTANCE.md +23 -0
  138. package/dist/reference/errors/MOSTRA_REMOTE_OPERATOR_UNAVAILABLE.md +23 -0
  139. package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
  140. package/dist/reference/errors/MOSTRA_REMOTE_PAUSED_BY_OPERATOR.md +23 -0
  141. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
  142. package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
  143. package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
  144. package/dist/reference/errors/MOSTRA_REMOTE_UNDER_REVIEW.md +23 -0
  145. package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
  146. package/dist/reference/errors/MOSTRA_RUNTIME_BLANK.md +23 -0
  147. package/dist/reference/errors/MOSTRA_RUNTIME_NOT_READY.md +23 -0
  148. package/dist/reference/errors/MOSTRA_RUNTIME_PAGE_ERROR.md +23 -0
  149. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_CRASHED.md +23 -0
  150. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_PARKED.md +23 -0
  151. package/dist/reference/errors/MOSTRA_SECRET_MISSING.md +23 -0
  152. package/dist/reference/errors/MOSTRA_SHARE_NOT_ENABLED.md +23 -0
  153. package/dist/reference/errors/MOSTRA_SHARE_NOT_FOUND.md +23 -0
  154. package/dist/reference/errors/MOSTRA_SHARE_PORTS_EXHAUSTED.md +23 -0
  155. package/dist/reference/errors/MOSTRA_SHARE_TOOL_MISSING.md +23 -0
  156. package/dist/reference/errors/MOSTRA_SHARE_TOOL_NOT_READY.md +23 -0
  157. package/dist/reference/errors/MOSTRA_SHARE_TTL_INVALID.md +23 -0
  158. package/dist/reference/errors/MOSTRA_SHARE_TUNNEL_FAILED.md +23 -0
  159. package/dist/reference/errors/MOSTRA_SMOKE_BUDGET.md +23 -0
  160. package/dist/reference/errors/MOSTRA_SMOKE_NO_EFFECT.md +23 -0
  161. package/dist/reference/errors/MOSTRA_SUBMIT_ALREADY.md +23 -0
  162. package/dist/reference/errors/MOSTRA_SUBMIT_BLOCKED.md +23 -0
  163. package/dist/reference/errors/MOSTRA_SUBMIT_CHANNEL_DENIED.md +23 -0
  164. package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +23 -0
  165. package/dist/reference/errors/MOSTRA_SUBMIT_PAUSED.md +23 -0
  166. package/dist/reference/errors/MOSTRA_SUBMIT_POLICY_NONE.md +23 -0
  167. package/dist/reference/errors/MOSTRA_SUBMIT_REVISION_MOVED.md +23 -0
  168. package/dist/reference/errors/MOSTRA_SUBMIT_SIGNAL_INVALID.md +23 -0
  169. package/dist/reference/errors/MOSTRA_SUBMIT_VIEW_INVALID.md +23 -0
  170. package/dist/reference/errors/MOSTRA_TARGET_UNAVAILABLE.md +23 -0
  171. package/dist/reference/errors/MOSTRA_TEAM_PRESENCE_RATE_LIMITED.md +23 -0
  172. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_POLICY.md +23 -0
  173. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_TOO_LARGE.md +23 -0
  174. package/dist/reference/errors/MOSTRA_TYPE_ERROR.md +23 -0
  175. package/dist/reference/errors/MOSTRA_TYPE_UNTYPED_PACKAGE.md +23 -0
  176. package/dist/reference/errors/MOSTRA_VERIFY_ACTION_SKIPPED.md +23 -0
  177. package/dist/reference/errors/MOSTRA_VERIFY_BASELINE_MISSING.md +23 -0
  178. package/dist/reference/errors/MOSTRA_VERIFY_CRASHED.md +23 -0
  179. package/dist/reference/errors/MOSTRA_VERIFY_LIVE_FAILED.md +23 -0
  180. package/dist/reference/errors/MOSTRA_VERIFY_NO_BASELINE.md +23 -0
  181. package/dist/reference/errors/MOSTRA_VERIFY_SECRET_MISSING.md +23 -0
  182. package/dist/reference/errors/MOSTRA_VERIFY_SKIP_CONSEQUENCE.md +23 -0
  183. package/dist/reference/errors/MOSTRA_VERIFY_TIMEOUT.md +23 -0
  184. package/dist/reference/self-hosting.md +130 -0
  185. package/dist/reference/telemetry.md +84 -0
  186. package/dist/skill/SKILL.md +124 -0
  187. package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
  188. package/dist/skill/assets/examples/dashboard/live.ts +25 -0
  189. package/dist/skill/assets/examples/dashboard/styles.css +125 -0
  190. package/dist/skill/assets/examples/decision/index.tsx +95 -0
  191. package/dist/skill/assets/examples/decision/styles.css +125 -0
  192. package/dist/skill/assets/examples/inbox/actions.ts +23 -0
  193. package/dist/skill/assets/examples/inbox/index.tsx +109 -0
  194. package/dist/skill/assets/examples/inbox/styles.css +125 -0
  195. package/dist/skill/assets/studio.css +125 -0
  196. package/dist/skill/references/answers.md +219 -0
  197. package/dist/skill/references/design.md +154 -0
  198. package/dist/skill/references/libraries.md +167 -0
  199. package/dist/skill/references/long-lived.md +148 -0
  200. package/dist/skill/references/mcp.md +68 -0
  201. package/dist/skill/references/page.md +131 -0
  202. package/dist/skill/references/server.md +146 -0
  203. package/dist/skill/references/sharing.md +123 -0
  204. package/dist/skill/references/teams.md +78 -0
  205. package/dist/skill/references/verify.md +71 -0
  206. package/package.json +10 -5
  207. package/src/gateway/actions.ts +20 -0
  208. package/src/gateway/browser.ts +128 -1
  209. package/src/gateway/capabilities.ts +8 -0
  210. package/src/gateway/http.ts +12 -1
  211. package/src/gateway/index.ts +210 -6
  212. package/src/gateway/listener.ts +31 -6
  213. package/src/gateway/routes.ts +8 -0
  214. package/src/gateway/team.ts +181 -0
  215. package/src/gc/index.ts +5 -0
  216. package/src/instance/index.ts +22 -2
  217. package/src/interaction/ephemeral.ts +21 -0
  218. package/src/interaction/events.ts +17 -0
  219. package/src/interaction/index.ts +325 -20
  220. package/src/interaction/pause.ts +106 -0
  221. package/src/interaction/roster.ts +585 -0
  222. package/src/interaction/submissions.ts +42 -1
  223. package/src/interaction/team.ts +426 -0
  224. package/src/interaction/viewers.ts +34 -1
  225. package/src/interaction/wait.ts +150 -0
  226. package/src/ledger/index.ts +20 -1
  227. package/src/ledger/migrations.ts +86 -0
  228. package/src/link/author.ts +215 -0
  229. package/src/link/hosted.ts +51 -4
  230. package/src/link/http.ts +6 -1
  231. package/src/link/index.ts +3 -1
  232. package/src/link/manager.ts +169 -35
  233. package/src/protocol-server/client.ts +53 -0
  234. package/src/protocol-server/index.ts +1 -1
  235. package/src/server/api.ts +514 -72
  236. package/src/server/auth.ts +600 -74
  237. package/src/server/authorize.ts +816 -0
  238. package/src/server/clients.ts +235 -0
  239. package/src/server/config.ts +7 -0
  240. package/src/server/data.ts +59 -1
  241. package/src/server/directory.ts +91 -0
  242. package/src/server/feed.ts +277 -0
  243. package/src/server/handle.ts +172 -0
  244. package/src/server/hosted-pages.ts +532 -0
  245. package/src/server/hosted.ts +551 -18
  246. package/src/server/index.ts +353 -61
  247. package/src/server/mcp.ts +330 -0
  248. package/src/server/metering.ts +156 -0
  249. package/src/server/oauth-clients.ts +510 -0
  250. package/src/server/operator.ts +557 -0
  251. package/src/server/providers.ts +284 -0
  252. package/src/server/remove.ts +148 -0
  253. package/src/server/routing.ts +275 -0
  254. package/src/share/index.ts +50 -2
  255. package/src/verify/index.ts +7 -0
  256. package/src/verify/runner.ts +27 -2
  257. package/dist/instance-FExcyENK.js.map +0 -1
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
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,aAAa,UACvB,IAAI;EACF,MAAM,OAAO,aAAa,iBAAiB;GAAC;GAAM;GAAM;EAAG,GAAG;GAC5D,UAAU;GACV,OAAO;IAAC;IAAU;IAAQ;GAAQ;EACpC,CAAC,CAAC,CAAC,KAAK;EACR,OAAO,YAAY,KAAK,IAAI,IAAI,OAAO,KAAA;CACzC,QAAQ;EACN;CACF;CAEF,IAAI,QAAQ,aAAa,SAAS;EAChC,IAAI,eAAe,KAAK,GAAG,GAAG,OAAO;EACrC,MAAM,QAAQ,MAAM,GAAG,CAAC,CAAC,KAAK,QAAQ,OAAO,EAAE;EAC/C,IAAI,CAAC,cAAc,KAAK,KAAK,GAAG,OAAO,KAAA;EACvC,IAAI;GACF,MAAM,SAAS,aACb,GAAG,QAAQ,IAAI,iBAAiB,cAAc,yBAC9C;IAAC;IAAU;IAAa;GA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GAAI;GACpC,SAAS,EAAE,MAAM,UAAU;GAC3B,MAAM,EAAE,MAAM,SAAS;GACvB,QAAQ,EAAE,MAAM,SAAS;GACzB,QAAQ,EAAE,MAAM,SAAS;GACzB,UAAU;IAAE,MAAM;IAAU,UAAU;GAAK;EAC7C;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":["escapeHtml","developmentProvider","request","httpRequest","httpsRequest","SignInIdentitySchema","durationMs","ChatHostPolicySchema","invalid","refusal","BASE_HEADERS","createServer","parse"],"sources":["../src/platform/filesystems.ts","../src/server/api.ts","../src/server/auth.ts","../src/server/oauth-clients.ts","../src/server/authorize.ts","../src/server/clients.ts","../src/server/directory.ts","../src/server/data.ts","../src/server/handle.ts","../src/server/feed.ts","../src/server/hosted-pages.ts","../src/server/relay.ts","../src/server/remove.ts","../src/server/hosted.ts","../src/server/mcp.ts","../src/server/metering.ts","../src/server/operator.ts","../src/server/providers.ts","../src/server/routing.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 { createDiagnostic, type Diagnostic } from \"@mostra/protocol\";\nimport type { CredentialResource } from \"@mostra/protocol/operator\";\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 { Authorize } from \"./authorize.ts\";\nimport type { ClientAddresses, RateLimiter } from \"./clients.ts\";\nimport type { RemoteServerConfig } from \"./config.ts\";\nimport type { HostedHome } from \"./hosted.ts\";\nimport type { RemoteMcp } from \"./mcp.ts\";\nimport type { Clients } from \"./oauth-clients.ts\";\nimport type { Operator } from \"./operator.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/** How often the operator is asked again whether an account is suspended (`accounts.status`). */\nconst STATUS_RECHECK_MS = 30_000;\n\n/** Dynamic Client Registrations an address may make a minute (D167). */\nconst REGISTRATIONS_PER_MINUTE = 10;\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 /** Told each message a home's binding carried in (relay and sync traffic), for metering. */\n readonly message?: (homeId: string) => void;\n /** Told the bytes a home stored (an upload it hadn't stored before), for metering. */\n readonly stored?: (homeId: string, bytes: number) => void;\n /** The remote MCP endpoint (`/mcp`, INTERFACES §18.8). */\n readonly mcp?: RemoteMcp;\n /** The authorization server's browser pages (sign-in, consent, viewer sign-in). */\n readonly authorize: Authorize;\n /** Its clients, for Dynamic Client Registration. */\n readonly clients: Clients;\n /**\n * Where a request comes from, and the rate its registrations count against (D167): Dynamic\n * Client Registration takes no credential, so each address may register a few clients a minute.\n */\n readonly registrations?: {\n readonly addresses: ClientAddresses;\n readonly rates: RateLimiter;\n };\n /** The operator module: its `accounts.authenticate` admits credentials it issued. */\n readonly operator?: Operator;\n /** Whether the operator suspended a home: its bindings and uploads are refused (D165 item 9). */\n readonly suspended?: (homeId: string) => boolean;\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 /** Closes every binding of a home now (a suspension or a move, 4403). */\n closeHome(homeId: 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/** The device page for a browser already signed in: approving links a machine (§18.5). */\nfunction deviceApproval(options: {\n readonly code: string;\n readonly name: string;\n readonly csrf: string;\n}): string {\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>\n<p><strong>Approving links a machine to your account, ${escapeHtml(options.name)}.</strong> That machine's\nMostra can then host pages under your account and receives their answers. Continue only if you started\nthis sign-in yourself, on that machine.</p>\n<form method=\"post\" action=\"/device\"><input type=\"hidden\" name=\"csrf\" value=\"${escapeHtml(options.csrf)}\">\n<label>Code <input name=\"user_code\" value=\"${escapeHtml(options.code)}\" autocomplete=\"off\" required></label>\n<p><button name=\"session_decision\" value=\"approve\">Approve this machine</button>\n<button name=\"session_decision\" value=\"deny\">Refuse</button></p></form></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 const bindingHomes = new Map<WebSocket, string>();\n\n /**\n * Whether the device page offers the development provider's form (D166 item 4): only while it is\n * the one provider a sign-in may use now, none other configured and none the operator supplies.\n * The page's GET and its POST judge by this one rule.\n */\n const devFormOffered = async (): Promise<boolean> => {\n const development = developmentProvider(config);\n if (development === undefined) return false;\n const offered = await options.authorize.providers();\n return offered.length === 1 && offered[0]?.id === development.id;\n };\n\n /**\n * The operator's word on accounts (`accounts.status`, §18.6), asked at most every 30 s per\n * account and written into the directory, so a suspension reaches every grant: its refreshes, its\n * bindings, its MCP calls (Fable review of WP-30, 6). An operator that doesn't answer leaves the\n * last word standing.\n */\n const statusAsked = new Map<string, number>();\n const accountStanding = async (accountId: string): Promise<\"active\" | \"suspended\"> => {\n if (options.operator?.has.status === true) {\n const last = statusAsked.get(accountId);\n const every = Math.min(STATUS_RECHECK_MS, options.recheckMs ?? STATUS_RECHECK_MS);\n if (last === undefined || Date.now() - last >= every) {\n statusAsked.set(accountId, Date.now());\n if (statusAsked.size > 10_000)\n statusAsked.delete(statusAsked.keys().next().value as string);\n const said = await options.operator.status(accountId);\n if (said !== undefined) auth.setAccountStatus(accountId, said);\n }\n }\n return auth.accountStatus(accountId);\n };\n\n /**\n * Whether an authenticated caller may act now: its home not suspended by the operator, its\n * account not suspended (D165 item 9). One place for `/host`, `/files`, `/mcp` and `/link`\n * (Fable review of WP-30, 1).\n */\n const standing = async (who: Authenticated): Promise<Diagnostic | undefined> => {\n if (options.suspended?.(who.homeId) || (await accountStanding(who.accountId)) === \"suspended\") {\n return createDiagnostic(\"MOSTRA_REMOTE_HOME_SUSPENDED\", {\n message: \"This account's pages are suspended by the server's operator.\",\n });\n }\n return undefined;\n };\n\n /**\n * The account a bearer token names for one resource (`host`, `files` or `mcp`): a token this\n * server issued for exactly that audience (RFC 8707; a token for `/mcp` opens no binding), or a\n * credential the operator issued (`accounts.authenticate`, §18.6); or why it may not act now.\n */\n const bearer = async (\n request: IncomingMessage,\n resource: CredentialResource,\n ): Promise<Authenticated | { readonly refused: Diagnostic } | undefined> => {\n const header = request.headers.authorization ?? \"\";\n const match = /^bearer\\s+(\\S+)$/i.exec(header);\n if (!match) return undefined;\n const token = match[1] as string;\n const audience = `${apiOrigin}/${resource === \"files\" ? \"host\" : resource}`;\n const issued = auth.authenticate(token);\n let who: Authenticated | undefined;\n if (issued) {\n if (issued.resource !== audience) return undefined;\n who = issued;\n } else {\n if (!options.operator?.has.authenticate) return undefined;\n const credential = await options.operator.authenticate(token, resource);\n if (!credential?.scope.includes(\"mostra\")) return undefined;\n who = auth.credentialSession({\n account: credential.account,\n subject: credential.subject ?? \"default\",\n resource: audience,\n // Only the binding links an instance; a key used on /mcp or /files names none.\n link: resource === \"host\",\n });\n }\n const refused = await standing(who);\n return refused ? { refused } : who;\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 /**\n * RFC 8414 metadata (INTERFACES §18.5): Client ID Metadata Documents with `none` among the token\n * endpoint's methods, which Claude needs before it uses one, Dynamic Client Registration as the\n * fallback, PKCE S256, `iss` in responses, and `offline_access` for rotating refresh tokens.\n */\n const metadata = () => ({\n issuer: apiOrigin,\n authorization_endpoint: `${apiOrigin}/oauth/authorize`,\n token_endpoint: `${apiOrigin}/oauth/token`,\n registration_endpoint: `${apiOrigin}/oauth/register`,\n device_authorization_endpoint: `${apiOrigin}/oauth/device`,\n revocation_endpoint: `${apiOrigin}/oauth/revoke`,\n response_types_supported: [\"code\"],\n response_modes_supported: [\"query\"],\n grant_types_supported: [\n \"authorization_code\",\n \"refresh_token\",\n \"urn:ietf:params:oauth:grant-type:device_code\",\n ],\n token_endpoint_auth_methods_supported: [\"none\"],\n revocation_endpoint_auth_methods_supported: [\"none\"],\n code_challenge_methods_supported: [\"S256\"],\n scopes_supported: [\"mostra\", \"offline_access\"],\n client_id_metadata_document_supported: true,\n authorization_response_iss_parameter_supported: true,\n });\n\n const sessionDevicePage = (code: string, signed: { accountId: string; hash: string }): string =>\n deviceApproval({\n code,\n name: auth.accountName(signed.accountId).name ?? \"your account\",\n csrf: options.authorize.csrf(signed.hash, \"device\"),\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 = await bearer(request, \"files\");\n if (!who) {\n unauthorized(response, \"Version files need the binding's access token.\");\n return;\n }\n if (\"refused\" in who) {\n send(response, 403, who.refused);\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 const declared = home.wanted(sha);\n if (declared === undefined) {\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 /** Refuses the upload and closes its connection once the answer is out: the rest isn't read. */\n const refuseUpload = (status: number, message: string): void => {\n response.once(\"finish\", () => request.destroy());\n send(response, status, { code: \"MOSTRA_HOME_INTEGRITY\", message }, { connection: \"close\" });\n };\n const sizeMessage = \"The file's bytes aren't the size its push gave them.\";\n // A body announced at another size than its push gave is refused before any byte is read.\n const announced = request.headers[\"content-length\"];\n if (announced !== undefined && Number(announced) !== declared) {\n refuseUpload(declared > MAX_FILE_BYTES ? 413 : 400, sizeMessage);\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 const onData = (chunk: Buffer): void => {\n size += chunk.length;\n // Past the size its push gave it, or the cap: no more of it is read.\n if (size > MAX_FILE_BYTES || size > declared) {\n tooLarge = true;\n request.off(\"data\", onData);\n request.pause();\n out.end(() => resolve());\n return;\n }\n hash.update(chunk);\n out.write(chunk);\n };\n request.on(\"data\", onData);\n request.on(\"end\", () => {\n if (!tooLarge) out.end(() => resolve());\n });\n request.on(\"error\", reject);\n request.on(\"close\", () => out.end(() => resolve()));\n }).catch(() => undefined);\n const shortOrLong = !tooLarge && size !== declared;\n if (tooLarge || shortOrLong || hash.digest(\"hex\") !== sha) {\n await rm(scratch, { force: true });\n refuseUpload(\n tooLarge && size > MAX_FILE_BYTES ? 413 : 400,\n tooLarge || shortOrLong ? sizeMessage : \"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 options.stored?.(who.homeId, size);\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 (await options.authorize.handle(request, response, path)) return;\n if (method === \"GET\" && path === \"/.well-known/oauth-protected-resource/mcp\") {\n send(response, 200, {\n resource: `${apiOrigin}/mcp`,\n authorization_servers: [apiOrigin],\n scopes_supported: [\"mostra\"],\n bearer_methods_supported: [\"header\"],\n resource_name: \"Mostra\",\n });\n return;\n }\n if (method === \"POST\" && path === \"/link\") {\n // What a binding's credential links (D167): the account, the instance link it binds and\n // whether that instance is the account's default; `default=1` makes it so. A person's\n // device-grant token and an operator-issued key alike, for the binding's own resource.\n const who = await bearer(request, \"host\");\n if (who && \"refused\" in who) {\n send(response, 403, who.refused);\n return;\n }\n if (!who || who.linkId === undefined) {\n unauthorized(response, \"This credential links no instance on this server.\");\n return;\n }\n const body = await form(request);\n const linked = auth.linkState(who.linkId, body?.get(\"default\") === \"1\");\n send(response, 200, {\n account: {\n id: who.accountId,\n ...(who.accountName !== undefined ? { name: who.accountName } : {}),\n },\n instanceId: who.linkId,\n default: linked.default,\n });\n return;\n }\n if (method === \"POST\" && path === \"/oauth/register\") {\n // Dynamic Client Registration (RFC 7591): JSON in, the client's record out.\n if (!(request.headers[\"content-type\"] ?? \"\").startsWith(\"application/json\")) {\n send(response, 400, {\n error: \"invalid_client_metadata\",\n error_description: \"Send JSON.\",\n });\n return;\n }\n const body = await readBody(request, 64 * 1024);\n let metadata: unknown;\n try {\n metadata = JSON.parse(body?.toString(\"utf8\") ?? \"\");\n } catch {\n send(response, 400, {\n error: \"invalid_client_metadata\",\n error_description: \"Send JSON.\",\n });\n return;\n }\n // A registration takes no credential: an address registers a few a minute, so nobody fills\n // the directory with clients (each is removed after 30 days unused).\n if (options.registrations) {\n const { addresses, rates } = options.registrations;\n const taken = rates.take(`register:${addresses.keyOf(addresses.of(request))}`, {\n count: REGISTRATIONS_PER_MINUTE,\n perMs: 60_000,\n });\n if (!taken.ok) {\n send(\n response,\n 429,\n {\n error: \"slow_down\",\n error_description: \"Too many registrations from this address; try again shortly.\",\n },\n { \"retry-after\": String(taken.retryAfterS) },\n );\n return;\n }\n }\n const registered = options.clients.register(metadata);\n if (\"error\" in registered && \"description\" in registered) {\n send(response, 400, {\n error: registered[\"error\"],\n error_description: registered[\"description\"],\n });\n return;\n }\n send(response, 201, registered);\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 // A refresh asks the operator's word on its account first: a suspended account refreshes\n // nothing, and one the operator lifted refreshes again (`accounts.status`, §18.6).\n if (body.get(\"grant_type\") === \"refresh_token\") {\n const account = auth.refreshAccount(body.get(\"refresh_token\") ?? \"\");\n if (account !== undefined) await accountStanding(account);\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 const signed = options.authorize.sessionAccount(request);\n if (method === \"GET\") {\n const code = new URL(request.url ?? \"/\", apiOrigin).searchParams.get(\"user_code\") ?? \"\";\n if (signed) {\n page(response, 200, sessionDevicePage(code, signed));\n return;\n }\n // Real providers sign the person in first; the development one asks on this page, when it\n // is the only one: none other configured, and no operator that supplies its own (D167).\n if (!(await devFormOffered())) {\n await options.authorize.signInPage(\n response,\n `/device?user_code=${encodeURIComponent(code)}`,\n );\n return;\n }\n page(response, 200, devicePage({ code, provider }));\n return;\n }\n // The body is read once, for either form.\n let posted: URLSearchParams | undefined;\n if (method === \"POST\" && signed && request.headers.origin === apiOrigin) {\n const body = await form(request);\n posted = body;\n const decision = body?.get(\"session_decision\");\n if (body && decision !== null && decision !== undefined) {\n const code = body.get(\"user_code\") ?? \"\";\n if (body.get(\"csrf\") !== options.authorize.csrf(signed.hash, \"device\")) {\n page(\n response,\n 403,\n devicePage({\n code: \"\",\n provider,\n message: \"This form must be sent from this page.\",\n }),\n );\n return;\n }\n const approve = decision === \"approve\";\n const decided = auth.decideFor({ code, approve, accountId: signed.accountId });\n page(\n response,\n decided.ok ? 200 : 400,\n devicePage({\n code,\n provider,\n ...(decided.ok\n ? {\n done: true,\n message: approve\n ? \"The machine is linked to your account.\"\n : \"The sign-in was refused.\",\n }\n : { message: decided.reason }),\n }),\n );\n return;\n }\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 = posted ?? (await form(request));\n const code = body?.get(\"user_code\") ?? \"\";\n const name = (body?.get(\"name\") ?? \"\").trim().slice(0, 64);\n // Only where the page offers the development form: a server with real providers, or an\n // operator's, signs people in through them alone (Fable review of WP-30, 5).\n if (\n !body ||\n !provider ||\n !(await devFormOffered()) ||\n body.get(\"provider\") !== provider.id ||\n name === \"\"\n ) {\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 // The code first, read only: a made-up code resolves nobody, makes no account and asks\n // the operator nothing (second Fable review of WP-30, 5).\n const pending = auth.pendingCode(code);\n if (!pending.ok) {\n page(response, 400, devicePage({ code, provider, message: pending.reason }));\n return;\n }\n // The typed name is an identity like any provider's: the operator's `accounts.resolve`\n // decides its account, its refusals, suspensions and first steps (D165 item 9).\n const identity = { provider: provider.id, subject: name.toLowerCase(), name };\n let decided: { readonly ok: true } | { readonly ok: false; readonly reason: string };\n if (!approve) decided = auth.decide({ code, approve: false, identity });\n else {\n const account = await auth.resolveAccount(identity, 0);\n if (account.kind !== \"account\") {\n const reason =\n account.kind === \"unavailable\"\n ? \"Sign-in is unavailable for a moment; try again shortly.\"\n : account.kind === \"refused\"\n ? account.message\n : account.kind === \"suspended\"\n ? \"This account is suspended.\"\n : \"This server asks for a step before a first sign-in, which the development sign-in can't take.\";\n page(\n response,\n account.kind === \"unavailable\" ? 503 : 403,\n devicePage({ code, provider, message: reason }),\n );\n return;\n }\n decided = auth.decideFor({ code, approve: true, accountId: account.accountId });\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 if (path === \"/mcp\" && options.mcp) {\n const who = await bearer(request, \"mcp\");\n const challenge = `Bearer resource_metadata=\"${apiOrigin}/.well-known/oauth-protected-resource/mcp\"`;\n if (!who) {\n // A 401 with resource_metadata is how an MCP client finds the authorization server\n // (RFC 9728; Claude starts sign-in only from it).\n send(\n response,\n 401,\n { error: \"invalid_token\", error_description: \"Sign in to use Mostra here.\" },\n { \"www-authenticate\": challenge },\n );\n return;\n }\n if (\"refused\" in who) {\n send(response, 403, who.refused);\n return;\n }\n if (!who.scope.split(\" \").includes(\"mostra\")) {\n send(\n response,\n 403,\n { error: \"insufficient_scope\", error_description: \"The token lacks the mostra scope.\" },\n { \"www-authenticate\": `${challenge}, error=\"insufficient_scope\", scope=\"mostra\"` },\n );\n return;\n }\n await options.mcp.handle(request, response, who);\n return;\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 void bearer(request, \"host\").then(\n (who) => upgradeFor(who),\n (error: unknown) => {\n log.error(\"binding.auth_failed\", { error });\n refuse(503, \"Service Unavailable\");\n },\n );\n const upgradeFor = (\n who: Authenticated | { readonly refused: Diagnostic } | undefined,\n ): void => {\n if (who && \"refused\" in who) {\n refuse(403, \"Forbidden\");\n return;\n }\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 bindingHomes.set(ws, who.homeId);\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 (who.grantId.startsWith(\"credential:\")) {\n // An operator's credential: the operator is asked again; a key it revoked, or\n // an account it suspended, closes the binding within the bound.\n void bearer(request, \"host\").then(\n (still) => {\n if (!still || \"refused\" in still) {\n log.info(\"binding.credential_revoked\", { home: who.homeId });\n ws.close(4403, \"credential revoked\");\n } else expiresAt = still.expiresAt;\n },\n () => undefined,\n );\n } else if (!auth.grantLive(who.grantId)) {\n log.info(\"binding.grant_revoked\", { home: who.homeId });\n ws.close(4403, \"grant revoked\");\n } else {\n // The operator may have suspended the account since: asked within the bound.\n void standing(who).then(\n (refused) => {\n if (refused) {\n log.info(\"binding.account_suspended\", { home: who.homeId });\n ws.close(4403, \"account suspended\");\n }\n },\n () => undefined,\n );\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 bindingHomes.delete(ws);\n });\n ws.on(\"message\", () => {\n options.touch(who.homeId);\n options.message?.(who.homeId);\n });\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\n closeHome(homeId) {\n for (const [ws, home] of bindingHomes) {\n if (home === homeId) ws.close(4403, \"home unavailable\");\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 { SignInIdentity } from \"@mostra/protocol/operator\";\nimport type { Ledger, LedgerDb } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport type { RemoteServerConfig } from \"./config.ts\";\nimport type { Operator } from \"./operator.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/** An authorization code lives a minute (OAuth 2.1 §4.1.2: short-lived). */\nconst CODE_TTL_MS = 60_000;\n/** How long a used or expired code is kept to recognize its reuse (an hour). */\nconst CODE_KEPT_MS = 60 * 60 * 1000;\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 /** The resource (audience) the token was issued for: `<apiOrigin>/host` or `<apiOrigin>/mcp`. */\n readonly resource: string;\n /** The client the grant is for. */\n readonly clientId: string;\n /** The grant's scopes, space-separated. */\n readonly scope: string;\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/** What an authorization code carries, kept with its hash (one minute, single use). */\nexport interface CodeGrant {\n readonly clientId: string;\n readonly redirectUri: string;\n readonly challenge: string;\n readonly resource: string;\n readonly scope: string;\n readonly accountId: string;\n /** A hosted shell's viewer sign-in this code finishes (INTERFACES §18.4). */\n readonly viewerSignin?: string;\n /**\n * Whether the authorization request named its redirect URI; the token request must name it\n * too then (OAuth 2.1 §4.1.3). Absent: it did.\n */\n readonly redirectGiven?: boolean;\n}\n\n/** A sign-in identity resolved to the server's account, or why not. */\nexport type ResolvedAccount =\n | { readonly kind: \"account\"; readonly accountId: string; readonly name: string | undefined }\n | { readonly kind: \"step\"; readonly url: string }\n | { readonly kind: \"refused\"; readonly message: string }\n | { readonly kind: \"suspended\" }\n | { readonly kind: \"unavailable\" };\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/** Whether a PKCE verifier hashes to the S256 challenge (RFC 7636 §4.6), in constant time. */\nexport function pkceMatches(verifier: string, challenge: string): boolean {\n if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) return false;\n const computed = createHash(\"sha256\").update(verifier).digest(\"base64url\");\n return (\n computed.length === challenge.length &&\n timingSafeEqual(Buffer.from(computed), Buffer.from(challenge))\n );\n}\n\n/**\n * A resource indicator in its canonical form (RFC 8707; the MCP specification): scheme and host in\n * lower case, no trailing slash, no fragment. An unusable one answers `\"\"`.\n */\nexport function canonicalResource(resource: string): string {\n try {\n // WHATWG URL parsing already lower-cases the scheme and host.\n const url = new URL(resource);\n if (url.hash !== \"\" || url.search !== \"\") return \"\";\n return `${url.protocol}//${url.host}${url.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return \"\";\n }\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 /** The operator module, for `accounts.resolve` and `accounts.status` (D165 item 9). */\n readonly operator?: Operator;\n readonly now?: () => number;\n /** How long an access token lasts; an hour unless tests shorten it. */\n readonly accessTtlMs?: number;\n /** How long a used refresh token returns its successor; 30 s unless tests shorten it. */\n readonly rotationGraceMs?: 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 /** Approves or denies a device code for an account a browser session signed in as. */\n decideFor(input: {\n readonly code: string;\n readonly approve: boolean;\n readonly accountId: string;\n }): { readonly ok: true } | { readonly ok: false; readonly reason: string };\n /**\n * Resolves a sign-in identity to an account (INTERFACES §18.5): through the operator's\n * `accounts.resolve` when it has one, else the server's own accounts; `steps` counts the first\n * sign-in steps already taken.\n */\n resolveAccount(identity: SignInIdentity, steps: number): Promise<ResolvedAccount>;\n /** An account's display name, and the provider that verified it (its first identity's). */\n accountName(accountId: string): { readonly name?: string; readonly provider?: string };\n /** Mints an authorization code (one minute, single use; only its hash is kept). */\n issueCode(grant: CodeGrant): string;\n /**\n * Redeems a hosted shell's viewer sign-in code (never at the token endpoint): its client, PKCE\n * verifier and sign-in must match. Answers the account, or why not.\n */\n redeemViewerCode(input: {\n readonly code: string;\n readonly verifier: string;\n readonly clientId: string;\n readonly viewerSignin: string;\n }): { readonly accountId: string } | { readonly refused: string };\n /**\n * A session for a credential the operator issued (`accounts.authenticate`, §18.6): the account\n * (kept under the operator's ID), its hosted home, and one instance link per credential subject,\n * so a program holding an operator-issued key runs an always-on owner instance.\n */\n credentialSession(input: {\n readonly account: string;\n readonly subject: string;\n readonly resource: string;\n /** Whether this use links an instance (the binding's, `/host`); `/mcp` and `/files` don't. */\n readonly link: boolean;\n }): Authenticated;\n /** The account a refresh token belongs to, so the operator's word on it is asked first. */\n refreshAccount(refreshToken: string): string | undefined;\n /** An account's standing in the directory. */\n accountStatus(accountId: string): \"active\" | \"suspended\";\n /** Records the operator's word on an account (`accounts.status`, §18.6). */\n setAccountStatus(accountId: string, status: \"active\" | \"suspended\"): void;\n /**\n * Whether an instance link is its account's default, after making it so when `makeDefault`\n * (`POST /link`, D167; one default per account, as `mostra login --default` makes it).\n */\n linkState(linkId: string, makeDefault: boolean): { readonly default: boolean };\n /** The account's hosted home, made on its first use (one home per owner per server). */\n ensureHome(accountId: string): string;\n /** Whether an account has consented to a client. */\n consented(accountId: string, clientId: string): boolean;\n /** Records an account's consent to a client. */\n consent(accountId: string, clientId: string): void;\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 rotationGraceMs = options.rotationGraceMs ?? ROTATION_GRACE_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 /** An account the operator names: kept in the directory under the operator's own ID. */\n const operatorAccount = (\n db: LedgerDb,\n identity: { provider: string; subject: string; name?: string; email?: string },\n account: string,\n name: string | undefined,\n status: \"active\" | \"suspended\",\n ): void => {\n db.run(\n `INSERT INTO account (id, name, status, created_at) VALUES (?, ?, ?, ?)\n ON CONFLICT (id) DO UPDATE SET name = COALESCE(excluded.name, name), status = excluded.status`,\n account,\n name ?? identity.name ?? null,\n status,\n iso(now()),\n );\n db.run(\n `INSERT INTO identity (provider, subject, account_id, email, name, linked_at) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (provider, subject) DO UPDATE SET account_id = excluded.account_id,\n email = excluded.email, name = excluded.name`,\n identity.provider,\n identity.subject,\n account,\n identity.email ?? null,\n identity.name ?? null,\n iso(now()),\n );\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 scope: string;\n }>(\n `SELECT g.account_id, g.link_id, a.name, l.is_default, l.home_id, g.scope\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: row.scope,\n mostra_account: { id: row.account_id, ...(row.name !== null ? { name: row.name } : {}) },\n // An instance's link, for the CLI's device grant; an MCP client's grant has none.\n ...(row.link_id !== null\n ? {\n mostra_instance: row.link_id,\n mostra_default: row.is_default === 1,\n mostra_home: row.home_id ?? \"\",\n }\n : {}),\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) if (now() - entry.at > rotationGraceMs) recent.delete(hash);\n };\n\n /** `grant_type=refresh_token`: rotation with a 30 s grace, reuse after it revokes the grant. */\n const refresh = (form: URLSearchParams, clientId: string): TokenAnswer | OAuthError => {\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 (\n !row ||\n !grantLiveIn(db, row.grant_id, { anyStatus: true }) ||\n grantClient(db, row.grant_id) !== clientId\n ) {\n return oauthError(400, \"invalid_grant\", \"The refresh token isn't valid; sign in again.\");\n }\n // A suspended account's refresh token stays good: the refresh is refused for now, without\n // touching the token, so the instance or client keeps it and refreshes once the operator\n // lifts the suspension. `invalid_grant` would tell it to sign in again (second Fable\n // review of WP-30, 1).\n if (!grantLiveIn(db, row.grant_id)) {\n return oauthError(\n 403,\n \"temporarily_unavailable\",\n \"This account is suspended; its sign-in works again once the server's operator lifts the suspension.\",\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 <= rotationGraceMs) {\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\n /** The client a grant is for. */\n const grantClient = (db: LedgerDb, grantId: string): string | undefined =>\n db.get<{ client_id: string }>('SELECT client_id FROM \"grant\" WHERE id = ?', grantId)?.client_id;\n\n const grantLiveIn = (\n db: LedgerDb,\n grantId: string,\n options: { readonly anyStatus?: boolean } = {},\n ): boolean => {\n // An operator's credential is checked by asking the operator, by the binding's watch.\n if (grantId.startsWith(\"credential:\")) return true;\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 (\n row !== undefined &&\n row.revoked_at === null &&\n (options.anyStatus === true || row.status === \"active\")\n );\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 const clientId = form.get(\"client_id\") ?? \"\";\n if (grantType === \"authorization_code\") {\n const code = form.get(\"code\") ?? \"\";\n const hash = hashSecret(code);\n return directory.write((db): TokenAnswer | OAuthError => {\n const row = db.get<{ data_json: string; expires_at: string; used_at: string | null }>(\n \"SELECT data_json, expires_at, used_at FROM token WHERE hash = ? AND kind = 'code'\",\n hash,\n );\n if (row?.used_at != null) {\n // A code presented again: someone else may hold it, so what it gave is revoked\n // (OAuth 2.1 §4.1.3, RFC 9700 §4.5.3).\n const spent = JSON.parse(row.data_json) as CodeGrant & { readonly grantId?: string };\n if (spent.grantId !== undefined) {\n db.run(\n 'UPDATE \"grant\" SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL',\n iso(now()),\n spent.grantId,\n );\n log.warn(\"auth.code_reused\", { grant: spent.grantId });\n }\n return oauthError(400, \"invalid_grant\", \"The code is unknown, used or expired.\");\n }\n // Spent at its first presentation, whatever comes of it: a code works once. The row is\n // kept (as a hash) until it is long expired, so a second presentation is recognized.\n // Code rows only: a refresh token sent as a code is no code, and is left alone.\n db.run(\"UPDATE token SET used_at = ? WHERE hash = ? AND kind = 'code'\", iso(now()), hash);\n if (!row || Date.parse(row.expires_at) <= now()) {\n return oauthError(400, \"invalid_grant\", \"The code is unknown, used or expired.\");\n }\n const grant = JSON.parse(row.data_json) as CodeGrant;\n if (grant.viewerSignin !== undefined) {\n return oauthError(\n 400,\n \"invalid_grant\",\n \"This code is a page's sign-in, not a client's.\",\n );\n }\n if (grant.clientId !== clientId) {\n return oauthError(400, \"invalid_grant\", \"The code was issued to another client.\");\n }\n // Required when the authorization request named it (OAuth 2.1 §4.1.3), and the same.\n const redirectUri = form.get(\"redirect_uri\");\n if (\n (redirectUri === null && grant.redirectGiven !== false) ||\n (redirectUri !== null && redirectUri !== grant.redirectUri)\n ) {\n return oauthError(\n 400,\n \"invalid_grant\",\n \"redirect_uri isn't the one the code was issued for.\",\n );\n }\n if (!pkceMatches(form.get(\"code_verifier\") ?? \"\", grant.challenge)) {\n return oauthError(400, \"invalid_grant\", \"The PKCE code_verifier doesn't match.\");\n }\n const resource = form.get(\"resource\");\n if (resource !== null && canonicalResource(resource) !== grant.resource) {\n return oauthError(\n 400,\n \"invalid_target\",\n \"resource isn't the one the code was issued for.\",\n );\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 (?, ?, ?, ?, ?, NULL, ?)',\n grantId,\n grant.accountId,\n grant.clientId,\n grant.scope,\n grant.resource,\n iso(now()),\n );\n db.run(\n \"UPDATE token SET data_json = ? WHERE hash = ? AND kind = 'code'\",\n JSON.stringify({ ...grant, grantId }),\n hash,\n );\n log.info(\"auth.code_redeemed\", { client: grant.clientId, grant: grantId });\n return answer(db, grantId, issue(db, grantId));\n });\n }\n if (grantType === \"refresh_token\") return refresh(form, clientId);\n if (clientId !== 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 return oauthError(\n 400,\n \"unsupported_grant_type\",\n \"Use authorization_code, refresh_token or the device grant.\",\n );\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 resource: string;\n client_id: string;\n scope: string;\n }>(\n `SELECT t.hash, t.expires_at, t.grant_id, g.account_id, g.link_id, a.name, g.resource, g.client_id, g.scope\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 // A suspended account's token still names it, so its caller hears \"suspended\" (403)\n // rather than \"sign in again\", and the operator's later word can lift it (D165 item 9).\n if (expiresAt <= now() || !grantLiveIn(db, row.grant_id, { anyStatus: true }))\n return undefined;\n const home = db.get<{ id: string }>(\n \"SELECT id FROM home WHERE owner_account_id = ?\",\n row.account_id,\n );\n // An MCP client's account may have no home yet: it gets one at its first hosted call.\n if (!home && row.resource.endsWith(\"/host\")) return undefined;\n return {\n resource: row.resource,\n clientId: row.client_id,\n scope: row.scope,\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 decideFor(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 db.run(\n \"UPDATE token SET data_json = ? WHERE hash = ?\",\n JSON.stringify(\n input.approve\n ? { ...state, status: \"approved\", accountId: input.accountId }\n : { ...state, status: \"denied\" },\n ),\n row.hash,\n );\n if (input.approve) {\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 input.accountId,\n CLI_CLIENT_ID,\n iso(now()),\n );\n }\n return { ok: true as const };\n });\n },\n\n async resolveAccount(identity, steps) {\n const verdict = options.operator\n ? await options.operator.resolve(identity, steps)\n : ({ default: true } as const);\n if (verdict === \"unavailable\") return { kind: \"unavailable\" };\n if (\"default\" in verdict) {\n const accountId = directory.write((db) => accountFor(db, identity));\n const status = directory.read(\n (db) =>\n db.get<{ status: string }>(\"SELECT status FROM account WHERE id = ?\", accountId)\n ?.status,\n );\n if (status === \"suspended\") return { kind: \"suspended\" };\n return { kind: \"account\", accountId, name: identity.name };\n }\n if (\"step\" in verdict) return { kind: \"step\", url: verdict.step.url };\n if (\"refused\" in verdict) return { kind: \"refused\", message: verdict.refused.message };\n directory.write((db) =>\n operatorAccount(db, identity, verdict.account, verdict.name, verdict.status),\n );\n if (verdict.status === \"suspended\") return { kind: \"suspended\" };\n return { kind: \"account\", accountId: verdict.account, name: verdict.name ?? identity.name };\n },\n\n accountName(accountId) {\n return directory.read((db) => {\n const row = db.get<{ name: string | null; provider: string | null }>(\n `SELECT a.name, (SELECT i.provider FROM identity i WHERE i.account_id = a.id\n ORDER BY i.linked_at LIMIT 1) AS provider FROM account a WHERE a.id = ?`,\n accountId,\n );\n return {\n ...(row?.name ? { name: row.name } : {}),\n ...(row?.provider ? { provider: row.provider } : {}),\n };\n });\n },\n\n issueCode(grant) {\n const code = secret();\n directory.write((db) => {\n // Codes are kept a while after use to recognize a second presentation, then dropped.\n db.run(\n \"DELETE FROM token WHERE kind = 'code' AND expires_at < ?\",\n iso(now() - CODE_KEPT_MS),\n );\n db.run(\n \"INSERT INTO token (hash, kind, expires_at, data_json) VALUES (?, 'code', ?, ?)\",\n hashSecret(code),\n iso(now() + CODE_TTL_MS),\n JSON.stringify(grant),\n );\n });\n return code;\n },\n\n redeemViewerCode(input) {\n const hash = hashSecret(input.code);\n return directory.write((db) => {\n const row = db.get<{ data_json: string; expires_at: string }>(\n \"SELECT data_json, expires_at FROM token WHERE hash = ? AND kind = 'code'\",\n hash,\n );\n db.run(\"DELETE FROM token WHERE hash = ?\", hash);\n if (!row || Date.parse(row.expires_at) <= now()) {\n return { refused: \"The sign-in code is unknown, used or expired.\" };\n }\n const grant = JSON.parse(row.data_json) as CodeGrant;\n if (grant.viewerSignin === undefined || grant.viewerSignin !== input.viewerSignin) {\n return { refused: \"This sign-in code was started for another page.\" };\n }\n if (grant.clientId !== input.clientId) {\n return { refused: \"This sign-in code was issued to another shell.\" };\n }\n if (!pkceMatches(input.verifier, grant.challenge)) {\n return { refused: \"The sign-in's PKCE verifier doesn't match.\" };\n }\n return { accountId: grant.accountId };\n });\n },\n\n credentialSession(input) {\n return directory.write((db) => {\n db.run(\n \"INSERT INTO account (id, name, status, created_at) VALUES (?, NULL, 'active', ?) ON CONFLICT (id) DO NOTHING\",\n input.account,\n iso(now()),\n );\n const home = homeFor(db, input.account);\n let link = db.get<{ link_id: string }>(\n \"SELECT link_id FROM credential_link WHERE account_id = ? AND subject = ?\",\n input.account,\n input.subject,\n )?.link_id;\n // Only a binding makes the key's instance link: a key used on /mcp or /files first names\n // none, so no link that never binds takes the account's default (Fable review, 3).\n if (link === undefined && input.link) {\n link = linkFor(\n db,\n input.account,\n home,\n undefined,\n `Service key ${input.subject}`.slice(0, 128),\n );\n db.run(\n \"INSERT INTO credential_link (account_id, subject, link_id) VALUES (?, ?, ?)\",\n input.account,\n input.subject,\n link,\n );\n }\n const name = db.get<{ name: string | null }>(\n \"SELECT name FROM account WHERE id = ?\",\n input.account,\n )?.name;\n return {\n resource: input.resource,\n clientId: \"operator\",\n scope: \"mostra\",\n accountId: input.account,\n accountName: name ?? undefined,\n // Not a grant of this server: the operator is asked again while the binding stays open.\n grantId: `credential:${input.account}:${input.subject}`,\n homeId: home,\n linkId: link,\n expiresAt: now() + accessTtlMs,\n };\n });\n },\n\n refreshAccount(refreshToken) {\n return directory.read(\n (db) =>\n db.get<{ account_id: string }>(\n \"SELECT g.account_id FROM token t JOIN \\\"grant\\\" g ON g.id = t.grant_id WHERE t.hash = ? AND t.kind = 'refresh'\",\n hashSecret(refreshToken),\n )?.account_id,\n );\n },\n\n accountStatus(accountId) {\n return directory.read((db) =>\n db.get<{ status: string }>(\"SELECT status FROM account WHERE id = ?\", accountId)?.status ===\n \"suspended\"\n ? \"suspended\"\n : \"active\",\n );\n },\n\n setAccountStatus(accountId, status) {\n directory.write((db) =>\n db.run(\n \"UPDATE account SET status = ? WHERE id = ? AND status != ?\",\n status,\n accountId,\n status,\n ),\n );\n },\n\n linkState(linkId, makeDefault) {\n return directory.write((db) => {\n if (makeDefault) {\n const owner = db.get<{ account_id: string }>(\n \"SELECT account_id FROM instance_link WHERE id = ?\",\n linkId,\n );\n if (owner) {\n db.run(\n \"UPDATE instance_link SET is_default = 0 WHERE account_id = ? AND id != ?\",\n owner.account_id,\n linkId,\n );\n db.run(\"UPDATE instance_link SET is_default = 1 WHERE id = ?\", linkId);\n }\n }\n const row = db.get<{ is_default: number }>(\n \"SELECT is_default FROM instance_link WHERE id = ?\",\n linkId,\n );\n return { default: row?.is_default === 1 };\n });\n },\n\n ensureHome(accountId) {\n return directory.write((db) => homeFor(db, accountId));\n },\n\n consented(accountId, clientId) {\n return directory.read(\n (db) =>\n db.get(\n \"SELECT 1 FROM consent WHERE account_id = ? AND client_id = ? AND revoked_at IS NULL\",\n accountId,\n clientId,\n ) !== undefined,\n );\n },\n\n consent(accountId, clientId) {\n directory.write((db) =>\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, granted_at = excluded.granted_at\",\n accountId,\n clientId,\n iso(now()),\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 * The authorization server's clients (INTERFACES §18.5; VERIFIED_FACTS, WP-30): first-party ones\n * (the CLI, and one hosted shell per user-content domain), clients that registered through Dynamic\n * Client Registration (RFC 7591, deprecated by the MCP specification and still Claude's fallback),\n * and clients named by a Client ID Metadata Document: an `https` URL with a path whose document the\n * server fetches.\n *\n * A metadata document is fetched over `https` only, from a public address only: the name is\n * resolved once, every address it gives must be public (no loopback, private, link-local,\n * unique-local, carrier-grade NAT, multicast, reserved or cloud metadata address), and the request\n * goes to the address that was checked, so a second resolution can't move it (DNS rebinding). No\n * redirect is followed; at most 64 KiB, within 5 s; the document's `client_id` must equal its URL;\n * it is cached as its `Cache-Control` allows (at least a minute, at most a day).\n *\n * A redirect URI matches exactly, except that the port is ignored for `http://127.0.0.1`,\n * `http://[::1]` and `http://localhost` (RFC 8252 §7.3; Claude Code's loopback callback).\n */\nimport { randomBytes } from \"node:crypto\";\nimport { lookup } from \"node:dns/promises\";\nimport { request as httpRequest } from \"node:http\";\nimport { request as httpsRequest } from \"node:https\";\nimport type { LookupFunction } from \"node:net\";\nimport { isIP } from \"node:net\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Environment, Log } from \"../log.ts\";\n\n/** The largest metadata document read. */\nconst MAX_DOCUMENT_BYTES = 64 * 1024;\n/** How long fetching one may take. */\nconst FETCH_TIMEOUT_MS = 5_000;\n/** Registered clients unused this long are removed (INTERFACES §18.5). */\nconst UNUSED_CLIENT_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** What the server knows of a client. */\nexport interface OAuthClient {\n readonly id: string;\n readonly kind: \"metadata\" | \"registered\" | \"shell\" | \"cli\";\n readonly name: string;\n readonly redirectUris: readonly string[];\n /** Whether the name was stated by the client itself, never checked (all but first-party). */\n readonly unverified: boolean;\n}\n\n/** A refusal of a client, as an OAuth error. */\nexport interface ClientRefusal {\n readonly error:\n | \"invalid_client\"\n | \"invalid_request\"\n | \"invalid_redirect_uri\"\n | \"invalid_client_metadata\";\n readonly description: string;\n}\n\n/**\n * An IPv6 address's eight 16-bit groups, whatever its written form (`::` compressed, a dotted\n * IPv4 tail, hex), or `undefined` when it isn't one.\n */\nfunction ipv6Groups(address: string): number[] | undefined {\n let text = address.toLowerCase();\n const zone = text.indexOf(\"%\");\n if (zone !== -1) text = text.slice(0, zone);\n // A dotted IPv4 tail, read by position rather than a backtracking pattern: the name comes from\n // a client's metadata document URL (as clients.ts reads `X-Forwarded-For`).\n const colon = text.lastIndexOf(\":\");\n const dotted = text.slice(colon + 1);\n if (colon !== -1 && dotted.includes(\".\")) {\n const parts = dotted.split(\".\");\n if (parts.length !== 4 || parts.some((part) => !/^\\d{1,3}$/.test(part))) return undefined;\n const [a, b, c, d] = parts.map(Number) as [number, number, number, number];\n if ([a, b, c, d].some((part) => part > 255)) return undefined;\n text = `${text.slice(0, colon + 1)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;\n }\n const halves = text.split(\"::\");\n if (halves.length > 2) return undefined;\n const parse = (half: string): number[] =>\n half === \"\" ? [] : half.split(\":\").map((group) => Number.parseInt(group, 16));\n const head = parse(halves[0] as string);\n const tail = halves.length === 2 ? parse(halves[1] as string) : [];\n const missing = 8 - head.length - tail.length;\n if (halves.length === 1 ? missing !== 0 : missing < 1) return undefined;\n const groups = [...head, ...Array<number>(halves.length === 2 ? missing : 0).fill(0), ...tail];\n return groups.length === 8 && groups.every((group) => group >= 0 && group <= 0xffff)\n ? groups\n : undefined;\n}\n\n/** Whether an IP address is one no client document may come from. */\nexport function forbiddenAddress(address: string): boolean {\n const family = isIP(address);\n if (family === 4) {\n const [a, b] = address.split(\".\").map(Number) as [number, number];\n return (\n a === 0 ||\n a === 10 ||\n a === 127 ||\n (a === 100 && b >= 64 && b <= 127) ||\n (a === 169 && b === 254) ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 192 && b === 0) ||\n (a === 198 && (b === 18 || b === 19)) ||\n a >= 224\n );\n }\n if (family !== 6) return true;\n const groups = ipv6Groups(address);\n if (!groups) return true;\n const [g0, g1, g2, g3, g4, g5, g6, g7] = groups as [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n ];\n const embedded = `${g6 >> 8}.${g6 & 0xff}.${g7 >> 8}.${g7 & 0xff}`;\n // IPv4-mapped (::ffff:a.b.c.d) and IPv4-compatible (::a.b.c.d) addresses reach the IPv4\n // address they carry, however they are written (`::ffff:7f00:1` is 127.0.0.1).\n if (g0 === 0 && g1 === 0 && g2 === 0 && g3 === 0 && g4 === 0 && (g5 === 0xffff || g5 === 0)) {\n if (g5 === 0 && g6 === 0 && (g7 === 0 || g7 === 1)) return true; // :: and ::1\n return forbiddenAddress(embedded);\n }\n return (\n (g0 & 0xffc0) === 0xfe80 || // link-local fe80::/10\n (g0 & 0xfe00) === 0xfc00 || // unique-local fc00::/7\n (g0 & 0xff00) === 0xff00 || // multicast ff00::/8\n (g0 === 0x64 && g1 === 0xff9b) || // NAT64 64:ff9b::/96 and 64:ff9b:1::/48\n g0 === 0x2002 || // 6to4, which carries an IPv4 address\n (g0 === 0x2001 && g1 === 0) || // Teredo 2001::/32\n (g0 === 0x2001 && g1 === 0xdb8) || // documentation\n (g0 === 0x0100 && g1 === 0 && g2 === 0 && g3 === 0) // discard 100::/64\n );\n}\n\n/** Whether a redirect URI a request names is one the client's list allows. */\nexport function redirectAllowed(registered: readonly string[], asked: string): boolean {\n if (registered.includes(asked)) return true;\n let url: URL;\n try {\n url = new URL(asked);\n } catch {\n return false;\n }\n const loopback =\n url.protocol === \"http:\" &&\n (url.hostname === \"127.0.0.1\" || url.hostname === \"[::1]\" || url.hostname === \"localhost\");\n if (!loopback) return false;\n return registered.some((entry) => {\n try {\n const known = new URL(entry);\n return (\n known.protocol === \"http:\" &&\n known.hostname === url.hostname &&\n known.pathname === url.pathname &&\n known.search === url.search\n );\n } catch {\n return false;\n }\n });\n}\n\n/** Whether a redirect URI may be registered at all: https, or http on a loopback name. */\nfunction redirectRegistrable(uri: string): boolean {\n try {\n const url = new URL(uri);\n if (url.hash !== \"\") return false;\n if (url.protocol === \"https:\") return true;\n return (\n url.protocol === \"http:\" &&\n (url.hostname === \"127.0.0.1\" || url.hostname === \"[::1]\" || url.hostname === \"localhost\")\n );\n } catch {\n return false;\n }\n}\n\n/** Options for {@link createClients}. */\nexport interface ClientsOptions {\n readonly directory: Ledger;\n readonly log: Log;\n readonly env: Environment;\n readonly now?: () => number;\n /**\n * Whether an origin is a hosted shell's (a domain's apex, or a host an operator supplies): each\n * is a first-party public client, `<origin>/_mostra/signin`.\n */\n readonly isShellOrigin: (origin: string) => boolean;\n}\n\n/** The authorization server's clients. */\nexport interface Clients {\n /** A client by its ID: first-party, registered, or fetched from its metadata document. */\n find(clientId: string): Promise<OAuthClient | ClientRefusal>;\n /** Dynamic Client Registration (RFC 7591): the client's answer, or a refusal. */\n register(metadata: unknown): Record<string, unknown> | ClientRefusal;\n /** Notes a client was used, so an unused registration can be removed after 30 days. */\n used(clientId: string): void;\n /** The client ID of a domain's hosted shell. */\n shellClientId(shellOrigin: string): string;\n}\n\n/** Whether a client ID names a metadata document: an https URL with a path. */\nexport function metadataClientId(clientId: string): URL | undefined {\n try {\n const url = new URL(clientId);\n return url.protocol === \"https:\" && url.pathname.length > 1 && url.hash === \"\"\n ? url\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The loopback addresses a test's metadata origin may resolve to (`MOSTRA_TEST_CIMD_ORIGIN`). */\nconst LOOPBACK = new Set([\"127.0.0.1\", \"::1\"]);\n\n/** Builds the clients over the directory. */\nexport function createClients(options: ClientsOptions): Clients {\n const { directory, log } = options;\n const now = options.now ?? (() => Date.now());\n const fetched = new Map<string, { client: OAuthClient; until: number }>();\n // Tests serve a metadata document from loopback over http; only that exact origin, by name.\n const testOrigin = options.env[\"MOSTRA_TEST_CIMD_ORIGIN\"];\n\n const sweep = (): void => {\n directory.write((db) =>\n db.run(\n \"DELETE FROM oauth_client WHERE kind = 'registered' AND COALESCE(last_used_at, created_at) < ? AND id NOT IN (SELECT client_id FROM \\\"grant\\\" WHERE revoked_at IS NULL)\",\n new Date(now() - UNUSED_CLIENT_MS).toISOString(),\n ),\n );\n };\n\n /** Fetches a document from a checked public address, with no redirect, bounded. */\n const fetchDocument = (url: URL): Promise<{ status: number; body: string; maxAge: number }> =>\n new Promise((resolve, reject) => {\n const test =\n testOrigin !== undefined && url.origin === testOrigin.replace(/^http:/, \"https:\");\n // Every address the name has is checked, on the connection that uses it. Node.js asks for\n // all of them (`all: true`, its happy-eyeballs connect) or for one, and expects the answer\n // in the shape it asked for. A test's loopback origin passes the same lookup, with its\n // loopback address allowed, so the tests run this path.\n const pinned: LookupFunction = (hostname, options, callback) => {\n lookup(hostname, { all: true, verbatim: true })\n .then((addresses) => {\n if (addresses.length === 0) throw new Error(\"no address\");\n for (const found of addresses) {\n const allowed = test && LOOPBACK.has(found.address);\n if (!allowed && forbiddenAddress(found.address)) {\n throw new Error(`the name resolves to a non-public address (${found.address})`);\n }\n }\n if ((options as { all?: boolean }).all === true) {\n (callback as unknown as (error: null, list: typeof addresses) => void)(\n null,\n addresses,\n );\n return;\n }\n const chosen = addresses[0] as { address: string; family: number };\n callback(null, chosen.address, chosen.family);\n })\n .catch((error: Error) => callback(error, \"\", 0));\n };\n const literal = isIP(url.hostname.replace(/^\\[|\\]$/g, \"\"));\n if (!test && literal !== 0 && forbiddenAddress(url.hostname.replace(/^\\[|\\]$/g, \"\"))) {\n reject(new Error(\"the document's address isn't public\"));\n return;\n }\n const target = test ? new URL(url.href.replace(/^https:/, \"http:\")) : url;\n const request = (test ? httpRequest : httpsRequest)(\n target,\n {\n method: \"GET\",\n headers: { accept: \"application/json\", \"user-agent\": \"mostra-remote-server\" },\n timeout: FETCH_TIMEOUT_MS,\n lookup: pinned,\n },\n (response) => {\n let size = 0;\n const chunks: Buffer[] = [];\n response.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (size > MAX_DOCUMENT_BYTES) {\n request.destroy(new Error(\"the document is larger than 64 KiB\"));\n return;\n }\n chunks.push(chunk);\n });\n response.on(\"end\", () => {\n const cache = String(response.headers[\"cache-control\"] ?? \"\");\n const age = /max-age=(\\d+)/.exec(cache);\n const noStore = /no-store|no-cache/.test(cache);\n resolve({\n status: response.statusCode ?? 0,\n body: Buffer.concat(chunks).toString(\"utf8\"),\n maxAge: noStore ? 60 : Math.min(86_400, Math.max(60, age ? Number(age[1]) : 300)),\n });\n });\n response.on(\"error\", reject);\n },\n );\n const deadline = setTimeout(\n () => request.destroy(new Error(\"the document took longer than 5 s\")),\n FETCH_TIMEOUT_MS,\n );\n request.on(\"close\", () => clearTimeout(deadline));\n request.on(\"timeout\", () => request.destroy(new Error(\"the document took longer than 5 s\")));\n request.on(\"error\", reject);\n request.end();\n });\n\n const fromDocument = async (url: URL): Promise<OAuthClient | ClientRefusal> => {\n const cached = fetched.get(url.href);\n if (cached && cached.until > now()) return cached.client;\n let answer: { status: number; body: string; maxAge: number };\n try {\n answer = await fetchDocument(url);\n } catch (error) {\n log.warn(\"oauth.cimd_refused\", { client: url.href, reason: (error as Error).message });\n return {\n error: \"invalid_client\",\n description: `The client's metadata document can't be fetched: ${(error as Error).message}.`,\n };\n }\n if (answer.status !== 200) {\n // A redirect is never followed: the document must be served at its own URL.\n return {\n error: \"invalid_client\",\n description: `The client's metadata document answered ${answer.status}, not 200.`,\n };\n }\n let document: {\n client_id?: unknown;\n client_name?: unknown;\n redirect_uris?: unknown;\n };\n try {\n document = JSON.parse(answer.body) as typeof document;\n } catch {\n return { error: \"invalid_client\", description: \"The client's metadata document isn't JSON.\" };\n }\n if (document.client_id !== url.href) {\n return {\n error: \"invalid_client\",\n description: \"The metadata document's client_id isn't its own URL.\",\n };\n }\n const redirects = Array.isArray(document.redirect_uris)\n ? document.redirect_uris.filter(\n (uri): uri is string => typeof uri === \"string\" && redirectRegistrable(uri),\n )\n : [];\n if (redirects.length === 0) {\n return {\n error: \"invalid_client\",\n description: \"The metadata document names no usable redirect_uris.\",\n };\n }\n const client: OAuthClient = {\n id: url.href,\n kind: \"metadata\",\n name:\n typeof document.client_name === \"string\" && document.client_name.trim() !== \"\"\n ? document.client_name.trim().slice(0, 128)\n : url.hostname,\n redirectUris: redirects,\n unverified: true,\n };\n fetched.set(url.href, { client, until: now() + answer.maxAge * 1000 });\n if (fetched.size > 1_000) fetched.delete(fetched.keys().next().value as string);\n directory.write((db) =>\n db.run(\n `INSERT INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'metadata', ?, ?)\n ON CONFLICT (id) DO UPDATE SET metadata_json = excluded.metadata_json`,\n client.id,\n JSON.stringify({ client_name: client.name, redirect_uris: client.redirectUris }),\n new Date(now()).toISOString(),\n ),\n );\n return client;\n };\n\n const shellClientId = (shellOrigin: string): string => `${shellOrigin}/_mostra/signin`;\n\n return {\n shellClientId,\n\n async find(clientId) {\n if (clientId === \"mostra-cli\") {\n return {\n id: clientId,\n kind: \"cli\",\n name: \"Mostra CLI\",\n redirectUris: [],\n unverified: false,\n };\n }\n const suffix = \"/_mostra/signin\";\n const origin = clientId.endsWith(suffix) ? clientId.slice(0, -suffix.length) : undefined;\n if (origin !== undefined && options.isShellOrigin(origin)) {\n directory.write((db) =>\n db.run(\n \"INSERT OR IGNORE INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'shell', ?, ?)\",\n clientId,\n JSON.stringify({ client_name: \"Mostra\" }),\n new Date(now()).toISOString(),\n ),\n );\n return {\n id: clientId,\n kind: \"shell\",\n name: \"Mostra\",\n redirectUris: [`${origin}/_mostra/signin`],\n unverified: false,\n };\n }\n const url = metadataClientId(clientId);\n if (url) return fromDocument(url);\n const row = directory.read((db) =>\n db.get<{ metadata_json: string }>(\n \"SELECT metadata_json FROM oauth_client WHERE id = ? AND kind = 'registered'\",\n clientId,\n ),\n );\n if (!row) return { error: \"invalid_client\", description: \"Unknown client.\" };\n const metadata = JSON.parse(row.metadata_json) as {\n client_name?: string;\n redirect_uris: string[];\n };\n return {\n id: clientId,\n kind: \"registered\",\n name: metadata.client_name ?? \"An unnamed client\",\n redirectUris: metadata.redirect_uris,\n unverified: true,\n };\n },\n\n register(metadata) {\n sweep();\n const body = (typeof metadata === \"object\" && metadata !== null ? metadata : {}) as {\n redirect_uris?: unknown;\n client_name?: unknown;\n token_endpoint_auth_method?: unknown;\n grant_types?: unknown;\n };\n const redirects = Array.isArray(body.redirect_uris)\n ? body.redirect_uris.filter((uri): uri is string => typeof uri === \"string\")\n : [];\n if (\n redirects.length === 0 ||\n redirects.length > 10 ||\n !redirects.every(redirectRegistrable)\n ) {\n return {\n error: \"invalid_redirect_uri\",\n description:\n \"redirect_uris must list https: addresses, or http: on 127.0.0.1, [::1] or localhost.\",\n };\n }\n if (\n body.token_endpoint_auth_method !== undefined &&\n body.token_endpoint_auth_method !== \"none\"\n ) {\n return {\n error: \"invalid_client_metadata\",\n description:\n \"This server registers public clients only (token_endpoint_auth_method none).\",\n };\n }\n const name =\n typeof body.client_name === \"string\" ? body.client_name.trim().slice(0, 128) : undefined;\n const id = `mcl_${randomBytes(16).toString(\"hex\")}`;\n const at = new Date(now());\n directory.write((db) =>\n db.run(\n \"INSERT INTO oauth_client (id, kind, metadata_json, created_at, last_used_at) VALUES (?, 'registered', ?, ?, ?)\",\n id,\n JSON.stringify({ client_name: name, redirect_uris: redirects }),\n at.toISOString(),\n at.toISOString(),\n ),\n );\n log.info(\"oauth.client_registered\", { client: id });\n return {\n client_id: id,\n client_id_issued_at: Math.floor(at.getTime() / 1000),\n ...(name !== undefined ? { client_name: name } : {}),\n redirect_uris: redirects,\n token_endpoint_auth_method: \"none\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n };\n },\n\n used(clientId) {\n directory.write((db) =>\n db.run(\n \"UPDATE oauth_client SET last_used_at = ? WHERE id = ?\",\n new Date(now()).toISOString(),\n clientId,\n ),\n );\n },\n };\n}\n","/**\n * The authorization server's pages on the API origin (INTERFACES §18.5, D165 items 8, 10):\n *\n * - `GET /oauth/authorize`: the authorization code flow with PKCE (S256) for MCP clients (Client\n * ID Metadata Documents, registered clients) and for each hosted shell's viewer sign-in. The\n * client and its redirect URI are checked before anything is redirected anywhere; an `iss`\n * parameter goes with every answer (RFC 9207).\n * - Sign-in through an identity provider (`/signin/<id>/start`, its `callback`), into a browser\n * session on the API origin only, never the user-content domain; the operator's first sign-in\n * steps (`/signin/return`).\n * - The server's own consent page (`/oauth/consent`), for every client an account hasn't\n * approved, never skipped because a provider skipped its own; for a page's sign-in it names\n * the page's sender instead, once per account and home.\n *\n * Every in-progress record (an authorization request, a provider sign-in, a first sign-in step)\n * is kept only as the SHA-256 of its handle, lives minutes, is used once, and is bound to the\n * browser that started it by a cookie of the API origin.\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport {\n type IdentityProvider,\n type SignInIdentity,\n SignInIdentity as SignInIdentitySchema,\n} from \"@mostra/protocol/operator\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { type Authorization, canonicalResource, hashSecret } from \"./auth.ts\";\nimport { type Clients, type OAuthClient, redirectAllowed } from \"./oauth-clients.ts\";\nimport type { Operator } from \"./operator.ts\";\n\n/** How long an authorization request, a provider sign-in or a step waits. */\nconst PENDING_MS = 15 * 60_000;\n/** How long a browser stays signed in to the API origin. */\nconst SESSION_MS = 7 * 24 * 60 * 60_000;\n/** At most this many first sign-in steps per sign-in (D167). */\nconst MAX_STEPS = 3;\n/**\n * How long an identity provider's own calls may take (its authorization address, the code's\n * exchange): inside the 10 s every endpoint of the authorization server answers in (D165 item 10),\n * whether the provider is built in or the operator's.\n */\nconst PROVIDER_MS = 8_000;\n\n/** A provider's call, or a refusal once it took longer than {@link PROVIDER_MS}. */\nasync function bounded<T>(call: () => Promise<T> | T, what: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n Promise.resolve().then(call),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${what} took too long`)), PROVIDER_MS);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** What the pages need. */\nexport interface AuthorizeOptions {\n readonly apiOrigin: string;\n readonly directory: Ledger;\n readonly auth: Authorization;\n readonly clients: Clients;\n readonly operator: Operator;\n /** The built-in providers (configuration); the operator's join them at each sign-in. */\n readonly providers: readonly IdentityProvider[];\n /** Names a hosted home's owner, for a page's sign-in (\"Grace Hopper's page\"). */\n readonly ownerName: (homeId: string) => string | undefined;\n readonly log: Log;\n readonly now?: () => number;\n}\n\n/** A page's sign-in in progress (INTERFACES §18.4), bound to its route and shell session. */\nexport interface ViewerSignin {\n readonly homeId: string;\n readonly routeId: string;\n readonly sessionId: string;\n readonly shellOrigin: string;\n}\n\n/** The pages. */\nexport interface Authorize {\n /** Serves a request of the API origin when it is one of these pages; `false` otherwise. */\n handle(request: IncomingMessage, response: ServerResponse, path: string): Promise<boolean>;\n /**\n * Starts a page's sign-in from its shell (a click in the trusted chrome): the address the shell\n * sends the person to, with `state` bound to the route and the shell session.\n */\n startViewerSignin(\n signin: ViewerSignin,\n challenge: string,\n ): { readonly url: string; readonly state: string };\n /** Finishes a page's sign-in: the code, for the same route and session only. */\n finishViewerSignin(input: {\n readonly state: string;\n readonly code: string;\n readonly verifier: string;\n readonly routeId: string;\n readonly sessionId: string;\n }):\n | { readonly accountId: string; readonly name?: string; readonly provider?: string }\n | { readonly refused: string };\n /** The browser session's account of a request to the API origin, if signed in. */\n sessionAccount(\n request: IncomingMessage,\n ): { readonly accountId: string; readonly hash: string } | undefined;\n /** A CSRF token for a signed-in browser's form. */\n csrf(sessionHash: string, purpose: string): string;\n /** The providers a sign-in may use now: configured ones, then the operator's. */\n providers(): Promise<readonly { readonly id: string; readonly label: string }[]>;\n /** Starts a sign-in whose end continues at a page of the API origin (the device page). */\n signInPage(response: ServerResponse, next: string, message?: string): Promise<void>;\n}\n\nconst BASE = {\n \"cache-control\": \"no-store\",\n \"cross-origin-resource-policy\": \"same-origin\",\n \"x-content-type-options\": \"nosniff\",\n \"x-frame-options\": \"DENY\",\n} as const;\n\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (character) => `&#${character.charCodeAt(0)};`);\n}\n\nfunction shell(title: string, body: string): string {\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>${escapeHtml(title)}</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,a.button{font:inherit;padding:.4rem .9rem;margin:.2rem .5rem .2rem 0;display:inline-block}\n.muted{color:#555}</style></head><body><h1>${escapeHtml(title)}</h1>${body}</body></html>`;\n}\n\n/** Builds the pages. */\nexport function createAuthorize(options: AuthorizeOptions): Authorize {\n const { apiOrigin, directory, auth, clients, operator, log } = options;\n const now = options.now ?? (() => Date.now());\n const secure = apiOrigin.startsWith(\"https:\");\n const sessionCookie = secure ? \"__Host-mostra-signin\" : \"mostra-signin\";\n const flowCookie = secure ? \"__Host-mostra-flow\" : \"mostra-flow\";\n const iso = (ms: number) => new Date(ms).toISOString();\n const token = () => randomBytes(32).toString(\"base64url\");\n\n const cookies = (request: IncomingMessage): Map<string, string> => {\n const found = new Map<string, string>();\n for (const part of (request.headers.cookie ?? \"\").split(\";\")) {\n const at = part.indexOf(\"=\");\n if (at <= 0) continue;\n const name = part.slice(0, at).trim();\n // A repeated name is ambiguous: the first is kept, as browsers send the most specific first.\n if (!found.has(name)) found.set(name, part.slice(at + 1).trim());\n }\n return found;\n };\n const setCookie = (name: string, value: string, maxAgeS: number): string =>\n `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}${secure ? \"; Secure\" : \"\"}`;\n\n const send = (\n response: ServerResponse,\n status: number,\n html: string,\n extra: Record<string, string | string[]> = {},\n formTargets: readonly string[] = [],\n ): void => {\n response.writeHead(status, {\n ...BASE,\n \"content-type\": \"text/html; charset=utf-8\",\n // A form posts here, and its answer may redirect to a client: those origins only.\n \"content-security-policy\": `default-src 'none'; style-src 'unsafe-inline'; form-action 'self' ${formTargets.join(\" \")}; frame-ancestors 'none'; base-uri 'none'`,\n // A form's POST must carry this page's Origin (D166 item 10).\n \"referrer-policy\": \"same-origin\",\n ...extra,\n });\n response.end(html);\n };\n const redirect = (\n response: ServerResponse,\n location: string,\n extra: Record<string, string | string[]> = {},\n ): void => {\n response.writeHead(303, { ...BASE, location, \"referrer-policy\": \"no-referrer\", ...extra });\n response.end();\n };\n const problem = (response: ServerResponse, status: number, message: string): void =>\n send(\n response,\n status,\n shell(\"Sign-in can't continue\", `<p role=\"alert\">${escapeHtml(message)}</p>`),\n );\n\n // ── in-progress records ─────────────────────────────────────────────────────────────────\n\n const keep = (kind: \"provider\" | \"step\" | \"authorize\", handle: string, data: unknown): void =>\n directory.write((db) => {\n db.run(\"DELETE FROM signin WHERE expires_at < ?\", iso(now()));\n db.run(\n \"INSERT INTO signin (hash, kind, data_json, expires_at) VALUES (?, ?, ?, ?)\",\n hashSecret(handle),\n kind,\n JSON.stringify(data),\n iso(now() + PENDING_MS),\n );\n });\n const read = <T>(kind: \"provider\" | \"step\" | \"authorize\", handle: string): T | undefined =>\n directory.read((db) => {\n const row = db.get<{ data_json: string; expires_at: string }>(\n \"SELECT data_json, expires_at FROM signin WHERE hash = ? AND kind = ?\",\n hashSecret(handle),\n kind,\n );\n return row && Date.parse(row.expires_at) > now()\n ? (JSON.parse(row.data_json) as T)\n : undefined;\n });\n const spend = (handle: string): boolean =>\n directory.write(\n (db) => db.run(\"DELETE FROM signin WHERE hash = ?\", hashSecret(handle)).changes > 0,\n );\n\n // ── browser sessions ────────────────────────────────────────────────────────────────────\n\n const sessionAccount = (request: IncomingMessage) => {\n const value = cookies(request).get(sessionCookie);\n if (value === undefined || !/^[A-Za-z0-9_-]{43}$/.test(value)) return undefined;\n const hash = hashSecret(value);\n const row = directory.read((db) =>\n db.get<{ account_id: string; expires_at: string; status: string }>(\n `SELECT s.account_id, s.expires_at, a.status FROM browser_session s\n JOIN account a ON a.id = s.account_id WHERE s.hash = ?`,\n hash,\n ),\n );\n if (!row || Date.parse(row.expires_at) <= now() || row.status !== \"active\") return undefined;\n return { accountId: row.account_id, hash };\n };\n const startSession = (accountId: string): string => {\n const value = token();\n directory.write((db) =>\n db.run(\n \"INSERT INTO browser_session (hash, account_id, created_at, expires_at) VALUES (?, ?, ?, ?)\",\n hashSecret(value),\n accountId,\n iso(now()),\n iso(now() + SESSION_MS),\n ),\n );\n return setCookie(sessionCookie, value, Math.floor(SESSION_MS / 1000));\n };\n const csrf = (sessionHash: string, purpose: string): string =>\n createHash(\"sha256\").update(`mostra csrf ${sessionHash} ${purpose}`).digest(\"base64url\");\n\n // ── providers ───────────────────────────────────────────────────────────────────────────\n\n /** The providers now: configured ones, then the operator's (asked each time, D167). */\n const providers = async (): Promise<IdentityProvider[]> => {\n const supplied = await operator.providers();\n const ids = new Set(options.providers.map((provider) => provider.id));\n return [...options.providers, ...supplied.filter((provider) => !ids.has(provider.id))];\n };\n\n interface ProviderRecord {\n readonly provider: string;\n readonly verifier: string;\n readonly challenge: string;\n readonly nonce: string;\n readonly flow: string;\n readonly next: string;\n }\n interface StepRecord {\n readonly identity: SignInIdentity;\n readonly steps: number;\n readonly flow: string;\n readonly next: string;\n }\n\n /** The page listing the providers; each starts a sign-in that returns to `next`. */\n const signInPage = async (\n response: ServerResponse,\n next: string,\n message?: string,\n ): Promise<void> => {\n const list = await providers();\n const links = list\n .map(\n (provider) =>\n `<p><a class=\"button\" href=\"/signin/${encodeURIComponent(provider.id)}/start?next=${encodeURIComponent(next)}\">Continue with ${escapeHtml(provider.label)}</a></p>`,\n )\n .join(\"\");\n send(\n response,\n 200,\n shell(\n \"Sign in to Mostra\",\n `${message ? `<p role=\"alert\">${escapeHtml(message)}</p>` : \"\"}${links || \"<p>This server has no identity provider configured, so nobody can sign in yet.</p>\"}`,\n ),\n );\n };\n\n /** Where a finished sign-in continues: an address of the API origin only. */\n const safeNext = (next: string | null): string =>\n next?.startsWith(\"/\") && !next.startsWith(\"//\") ? next : \"/\";\n\n /** A resolved identity: a session and on to `next`, a step, or why not. */\n const resolved = async (\n response: ServerResponse,\n identity: SignInIdentity,\n steps: number,\n flow: string,\n next: string,\n ): Promise<void> => {\n const account = await auth.resolveAccount(identity, steps);\n if (account.kind === \"unavailable\") {\n problem(response, 503, \"Sign-in is unavailable for a moment; try again shortly.\");\n return;\n }\n if (account.kind === \"refused\") {\n problem(response, 403, account.message);\n return;\n }\n if (account.kind === \"suspended\") {\n problem(response, 403, \"This account is suspended.\");\n return;\n }\n if (account.kind === \"step\") {\n if (steps >= MAX_STEPS) {\n problem(response, 403, \"Sign-in asked for too many steps; try again later.\");\n return;\n }\n const handle = token();\n keep(\"step\", handle, { identity, steps: steps + 1, flow, next } satisfies StepRecord);\n const url = new URL(account.url);\n url.searchParams.set(\"mostra_return\", `${apiOrigin}/signin/return?step=${handle}`);\n redirect(response, url.href);\n return;\n }\n log.info(\"signin.done\", { provider: identity.provider });\n redirect(response, `${apiOrigin}${safeNext(next)}`, {\n \"set-cookie\": [startSession(account.accountId), setCookie(flowCookie, \"\", 0)],\n });\n };\n\n // ── authorization requests ──────────────────────────────────────────────────────────────\n\n interface AuthorizeRecord {\n readonly clientId: string;\n readonly redirectUri: string;\n readonly state: string | null;\n readonly challenge: string;\n readonly resource: string;\n readonly scope: string;\n readonly viewerSignin?: string;\n readonly redirectGiven: boolean;\n }\n interface ViewerSigninRecord extends ViewerSignin {\n readonly clientId: string;\n }\n\n /** The answer to a client's redirect URI, with `iss` (RFC 9207). */\n const toClient = (\n response: ServerResponse,\n redirectUri: string,\n params: Record<string, string | null>,\n ): void => {\n const url = new URL(redirectUri);\n for (const [key, value] of Object.entries(params))\n if (value !== null) url.searchParams.set(key, value);\n url.searchParams.set(\"iss\", apiOrigin);\n redirect(response, url.href);\n };\n\n /** Consent, or the code: a signed-in account continuing an authorization request. */\n const proceed = async (\n request: IncomingMessage,\n response: ServerResponse,\n handle: string,\n signed: { accountId: string; hash: string },\n ): Promise<void> => {\n const pending = read<AuthorizeRecord>(\"authorize\", handle);\n if (!pending) {\n problem(response, 400, \"This sign-in expired or was already used; start again from the app.\");\n return;\n }\n const client = await clients.find(pending.clientId);\n if (\"error\" in client) {\n problem(response, 400, client.description);\n return;\n }\n const viewer =\n pending.viewerSignin !== undefined\n ? read<ViewerSigninRecord>(\"authorize\", pending.viewerSignin)\n : undefined;\n const homeId = viewer?.homeId;\n const needsConsent =\n client.kind === \"shell\"\n ? homeId !== undefined && !senderShown(signed.accountId, homeId)\n : !auth.consented(signed.accountId, client.id);\n if (needsConsent && request.method !== \"POST\") {\n consentPage(response, pending, client, handle, signed, homeId);\n return;\n }\n if (request.method === \"POST\") {\n // The page's own form only, from this browser's session (D166 item 10).\n const form = await readForm(request);\n if (\n request.headers.origin !== apiOrigin ||\n !form ||\n form.get(\"csrf\") !== csrf(signed.hash, `consent ${handle}`)\n ) {\n problem(response, 403, \"This form must be sent from its own page.\");\n return;\n }\n if (form.get(\"decision\") !== \"approve\") {\n spend(handle);\n toClient(response, pending.redirectUri, { error: \"access_denied\", state: pending.state });\n return;\n }\n if (client.kind === \"shell\" && homeId !== undefined)\n markSenderShown(signed.accountId, homeId);\n else auth.consent(signed.accountId, client.id);\n }\n if (!spend(handle)) {\n problem(response, 400, \"This sign-in was already used.\");\n return;\n }\n clients.used(client.id);\n const code = auth.issueCode({\n clientId: client.id,\n redirectUri: pending.redirectUri,\n challenge: pending.challenge,\n resource: pending.resource,\n scope: pending.scope,\n accountId: signed.accountId,\n redirectGiven: pending.redirectGiven !== false,\n ...(pending.viewerSignin !== undefined\n ? { viewerSignin: hashSecret(pending.viewerSignin) }\n : {}),\n });\n log.info(\"oauth.code_issued\", { client: client.id });\n toClient(response, pending.redirectUri, { code, state: pending.state });\n };\n\n const senderShown = (accountId: string, homeId: string): boolean =>\n directory.read(\n (db) =>\n db.get(\n \"SELECT 1 FROM sender_shown WHERE account_id = ? AND home_id = ?\",\n accountId,\n homeId,\n ) !== undefined,\n );\n const markSenderShown = (accountId: string, homeId: string): void => {\n directory.write((db) =>\n db.run(\n \"INSERT OR IGNORE INTO sender_shown (account_id, home_id, at) VALUES (?, ?, ?)\",\n accountId,\n homeId,\n iso(now()),\n ),\n );\n };\n\n const consentPage = (\n response: ServerResponse,\n pending: AuthorizeRecord,\n client: OAuthClient,\n handle: string,\n signed: { accountId: string; hash: string },\n homeId: string | undefined,\n ): void => {\n const who = auth.accountName(signed.accountId).name ?? \"your account\";\n const redirectHost = new URL(pending.redirectUri).host;\n const loopback = /^(127\\.0\\.0\\.1|\\[::1\\]|localhost)(:\\d+)?$/.test(redirectHost);\n const body =\n client.kind === \"shell\"\n ? `<p>Continue as <strong>${escapeHtml(who)}</strong> to answer <strong>${escapeHtml(\n (homeId !== undefined ? options.ownerName(homeId) : undefined) ?? \"this person\",\n )}</strong>'s page? They will see your name with your answers.</p>`\n : `<p><strong>${escapeHtml(client.name)}</strong>${client.unverified ? ' <span class=\"muted\">(a name the app gives itself, not checked)</span>' : \"\"} asks to use Mostra as <strong>${escapeHtml(who)}</strong>: to read, create and change your hosted pages and their answers.</p>\n<p>It will send you back to <strong>${escapeHtml(redirectHost)}</strong>.${loopback ? \" That is a program on your own computer: continue only if you started this there.\" : \"\"}</p>`;\n send(\n response,\n 200,\n shell(\n client.kind === \"shell\" ? \"Answer as yourself\" : \"Allow access\",\n `${body}<form method=\"post\" action=\"/oauth/authorize/continue?authorize=${encodeURIComponent(handle)}\">\n<input type=\"hidden\" name=\"csrf\" value=\"${csrf(signed.hash, `consent ${handle}`)}\">\n<button name=\"decision\" value=\"approve\">${client.kind === \"shell\" ? \"Continue\" : \"Allow\"}</button>\n<button name=\"decision\" value=\"deny\">Cancel</button></form>`,\n ),\n {},\n [new URL(pending.redirectUri).origin],\n );\n };\n\n const readForm = async (request: IncomingMessage): Promise<URLSearchParams | undefined> => {\n if (!(request.headers[\"content-type\"] ?? \"\").startsWith(\"application/x-www-form-urlencoded\")) {\n return undefined;\n }\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n size += (chunk as Buffer).length;\n if (size > 16 * 1024) return undefined;\n chunks.push(chunk as Buffer);\n }\n return new URLSearchParams(Buffer.concat(chunks).toString(\"utf8\"));\n };\n\n /** `GET /oauth/authorize`. */\n const authorize = async (\n response: ServerResponse,\n query: URLSearchParams,\n request: IncomingMessage,\n ): Promise<void> => {\n // A parameter given twice is ambiguous: refused before anything else (RFC 6749 §3.1).\n for (const key of new Set(query.keys())) {\n if (query.getAll(key).length > 1) {\n problem(response, 400, `The request names ${key} twice.`);\n return;\n }\n }\n const clientId = query.get(\"client_id\") ?? \"\";\n const client = await clients.find(clientId);\n if (\"error\" in client) {\n problem(response, 400, client.description);\n return;\n }\n const redirectUri =\n query.get(\"redirect_uri\") ??\n (client.redirectUris.length === 1 ? (client.redirectUris[0] as string) : \"\");\n // Nothing goes to a redirect URI the client doesn't list (RFC 6749 §4.1.2.1).\n if (!redirectAllowed(client.redirectUris, redirectUri)) {\n problem(response, 400, \"The redirect address isn't one this app registered.\");\n return;\n }\n const state = query.get(\"state\");\n const fail = (error: string, description: string) =>\n toClient(response, redirectUri, { error, error_description: description, state });\n if (query.get(\"response_type\") !== \"code\")\n return fail(\"unsupported_response_type\", \"Only code.\");\n const challenge = query.get(\"code_challenge\") ?? \"\";\n if (query.get(\"code_challenge_method\") !== \"S256\" || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {\n return fail(\"invalid_request\", \"PKCE with S256 is required.\");\n }\n if (client.kind === \"cli\") return fail(\"unauthorized_client\", \"The CLI uses the device grant.\");\n const scopes = (query.get(\"scope\") ?? \"mostra\").split(\" \").filter((part) => part !== \"\");\n if (!scopes.every((part) => part === \"mostra\" || part === \"offline_access\")) {\n return fail(\"invalid_scope\", \"The scopes are mostra and offline_access.\");\n }\n const scope = [\"mostra\", ...(scopes.includes(\"offline_access\") ? [\"offline_access\"] : [])].join(\n \" \",\n );\n let resource = \"\";\n let viewerSignin: string | undefined;\n if (client.kind === \"shell\") {\n // A page's sign-in: started by its shell, bound to its route and session.\n viewerSignin = query.get(\"mostra_signin\") ?? \"\";\n const started = read<ViewerSigninRecord>(\"authorize\", viewerSignin);\n if (!started || started.clientId !== client.id || state !== viewerSignin) {\n return fail(\"invalid_request\", \"This page sign-in wasn't started from its page.\");\n }\n resource = `${apiOrigin}/viewer`;\n } else {\n // The audience: the MCP endpoint (RFC 8707; every MCP client names it).\n resource = canonicalResource(query.get(\"resource\") ?? `${apiOrigin}/mcp`);\n if (resource !== `${apiOrigin}/mcp`)\n return fail(\"invalid_target\", `The resource is ${apiOrigin}/mcp.`);\n }\n const handle = token();\n keep(\"authorize\", handle, {\n clientId: client.id,\n redirectUri,\n state,\n challenge,\n resource,\n scope,\n ...(viewerSignin !== undefined ? { viewerSignin } : {}),\n redirectGiven: query.get(\"redirect_uri\") !== null,\n } satisfies AuthorizeRecord);\n const signed = sessionAccount(request);\n if (signed) {\n await proceed(request, response, handle, signed);\n return;\n }\n await signInPage(response, `/oauth/authorize/continue?authorize=${handle}`);\n };\n\n return {\n sessionAccount,\n csrf,\n signInPage,\n providers: async () =>\n (await providers()).map((provider) => ({ id: provider.id, label: provider.label })),\n\n startViewerSignin(signin, challenge) {\n const state = token();\n const clientId = clients.shellClientId(signin.shellOrigin);\n keep(\"authorize\", state, { ...signin, clientId } satisfies ViewerSigninRecord);\n const url = new URL(`${apiOrigin}/oauth/authorize`);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", clientId);\n url.searchParams.set(\"redirect_uri\", `${signin.shellOrigin}/_mostra/signin`);\n url.searchParams.set(\"state\", state);\n url.searchParams.set(\"mostra_signin\", state);\n url.searchParams.set(\"code_challenge\", challenge);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n return { url: url.href, state };\n },\n\n finishViewerSignin(input) {\n const started = read<ViewerSigninRecord>(\"authorize\", input.state);\n // A code started on one route, or for another shell session, is refused here (login CSRF).\n if (!started || started.routeId !== input.routeId || started.sessionId !== input.sessionId) {\n return { refused: \"This sign-in was started for another page.\" };\n }\n const redeemed = auth.redeemViewerCode({\n code: input.code,\n verifier: input.verifier,\n clientId: started.clientId,\n viewerSignin: hashSecret(input.state),\n });\n spend(input.state);\n if (\"refused\" in redeemed) return redeemed;\n const named = auth.accountName(redeemed.accountId);\n return {\n accountId: redeemed.accountId,\n ...(named.name !== undefined ? { name: named.name } : {}),\n ...(named.provider !== undefined ? { provider: named.provider } : {}),\n };\n },\n\n async handle(request, response, path) {\n const method = request.method ?? \"GET\";\n const url = new URL(request.url ?? \"/\", apiOrigin);\n if (method === \"GET\" && path === \"/oauth/authorize\") {\n await authorize(response, url.searchParams, request);\n return true;\n }\n if (path === \"/oauth/authorize/continue\" && (method === \"GET\" || method === \"POST\")) {\n const handle = url.searchParams.get(\"authorize\") ?? \"\";\n const signed = sessionAccount(request);\n if (!signed) {\n await signInPage(response, `/oauth/authorize/continue?authorize=${handle}`);\n return true;\n }\n await proceed(request, response, handle, signed);\n return true;\n }\n const start = /^\\/signin\\/([a-z][a-z0-9-]{0,31})\\/start$/.exec(path);\n if (method === \"GET\" && start) {\n const provider = (await providers()).find((candidate) => candidate.id === start[1]);\n if (!provider) {\n problem(response, 404, \"No such sign-in.\");\n return true;\n }\n const state = token();\n const verifier = token();\n const challenge = createHash(\"sha256\").update(verifier).digest(\"base64url\");\n const nonce = token();\n const flow = token();\n keep(\"provider\", state, {\n provider: provider.id,\n verifier,\n challenge,\n nonce,\n flow: hashSecret(flow),\n next: safeNext(url.searchParams.get(\"next\")),\n } satisfies ProviderRecord);\n let target: string;\n try {\n target = await bounded(\n () =>\n provider.authorize(\n state,\n { challenge, method: \"S256\", verifier },\n { redirectUri: `${apiOrigin}/signin/${provider.id}/callback`, nonce },\n ),\n \"the provider's sign-in address\",\n );\n // Only to an https: page (a server on loopback http, as tests and a first run use, may\n // send its own providers' pages over http too).\n const parsed = new URL(target, apiOrigin);\n if (parsed.protocol !== \"https:\" && (secure || parsed.protocol !== \"http:\")) {\n throw new Error(\"the provider's sign-in address isn't https:\");\n }\n target = parsed.href;\n } catch (error) {\n log.warn(\"signin.provider_failed\", {\n provider: provider.id,\n message: (error as Error).message,\n });\n problem(\n response,\n 503,\n `${provider.label} can't be reached right now; try again shortly.`,\n );\n return true;\n }\n redirect(response, target, {\n \"set-cookie\": setCookie(flowCookie, flow, Math.floor(PENDING_MS / 1000)),\n });\n return true;\n }\n const name = /^\\/signin\\/([a-z][a-z0-9-]{0,31})\\/name$/.exec(path);\n const callback = /^\\/signin\\/([a-z][a-z0-9-]{0,31})\\/callback$/.exec(path);\n if ((method === \"GET\" && callback) || (name && (method === \"GET\" || method === \"POST\"))) {\n const id = (callback ?? name)?.[1] as string;\n const provider = (await providers()).find((candidate) => candidate.id === id);\n if (!provider) {\n problem(response, 404, \"No such sign-in.\");\n return true;\n }\n if (name && method === \"GET\") {\n // The development provider's page: a name, trusted as typed (D166 item 4).\n const state = url.searchParams.get(\"state\") ?? \"\";\n send(\n response,\n 200,\n shell(\n \"Development sign-in\",\n `<p class=\"muted\">This server signs people in with a development provider, which trusts the name you type. Use it only on a server you run for yourself or for tests.</p>\n<form method=\"post\" action=\"/signin/${escapeHtml(id)}/name\"><input type=\"hidden\" name=\"state\" value=\"${escapeHtml(state)}\">\n<label>Your name <input name=\"name\" required maxlength=\"64\"></label> <button>Continue</button></form>`,\n ),\n );\n return true;\n }\n let params: Record<string, string>;\n if (name) {\n const form = await readForm(request);\n if (request.headers.origin !== apiOrigin || !form) {\n problem(response, 403, \"This form must be sent from its own page.\");\n return true;\n }\n params = Object.fromEntries(form.entries());\n } else {\n params = {};\n for (const key of new Set(url.searchParams.keys())) {\n if (url.searchParams.getAll(key).length > 1) {\n problem(response, 400, `The provider's answer names ${key} twice.`);\n return true;\n }\n params[key] = url.searchParams.get(key) as string;\n }\n }\n const state = params[\"state\"] ?? \"\";\n const pending = read<ProviderRecord>(\"provider\", state);\n const flow = cookies(request).get(flowCookie);\n // The sign-in this browser started, at this provider, once.\n if (\n !pending ||\n pending.provider !== provider.id ||\n flow === undefined ||\n hashSecret(flow) !== pending.flow ||\n !spend(state)\n ) {\n problem(\n response,\n 400,\n \"This sign-in expired, was used, or was started in another browser.\",\n );\n return true;\n }\n let identity: SignInIdentity;\n try {\n const answered = await bounded(\n () =>\n provider.callback(params, {\n redirectUri: `${apiOrigin}/signin/${provider.id}/callback`,\n nonce: pending.nonce,\n state,\n pkce: { challenge: pending.challenge, method: \"S256\", verifier: pending.verifier },\n }),\n \"the provider's answer\",\n );\n // An operator's provider is checked as every operator answer is (D167): a malformed\n // identity names nobody.\n const checked = SignInIdentitySchema.safeParse({ ...answered, provider: provider.id });\n if (!checked.success) throw new Error(\"the provider named nobody this server can use\");\n identity = checked.data;\n } catch (error) {\n log.warn(\"signin.callback_failed\", {\n provider: provider.id,\n message: (error as Error).message,\n });\n problem(\n response,\n 400,\n `${provider.label} didn't sign you in: ${(error as Error).message}`,\n );\n return true;\n }\n await resolved(response, identity, 0, pending.flow, pending.next);\n return true;\n }\n if (method === \"GET\" && path === \"/signin/return\") {\n const handle = url.searchParams.get(\"step\") ?? \"\";\n const step = read<StepRecord>(\"step\", handle);\n const flow = cookies(request).get(flowCookie);\n if (!step || flow === undefined || hashSecret(flow) !== step.flow || !spend(handle)) {\n problem(\n response,\n 400,\n \"This sign-in step expired, was used, or belongs to another browser.\",\n );\n return true;\n }\n await resolved(response, step.identity, step.steps, step.flow, step.next);\n return true;\n }\n return false;\n },\n };\n}\n","/**\n * Who a request comes from, and how often (D165 item 13, FAILURE_MODEL §11.3). The server sits\n * behind a TLS terminator, so the connection's peer is a proxy: `X-Forwarded-For` is believed only\n * when the peer is one of `trustedProxies`, and read from the right, taking the first address that\n * isn't a trusted proxy, so a forged leftmost entry is ignored. Rates key IPv6 addresses by their\n * /64 (`rateLimits.ipv6Prefix`), so rotating addresses inside one allocation doesn't escape them.\n *\n * The rate limiter is a token bucket per key, in memory: a server setting, never operator\n * policy, and with no setting there is no limit (D165 item 14).\n */\nimport type { IncomingMessage } from \"node:http\";\nimport { isIPv4, isIPv6 } from \"node:net\";\n\n/** An address range: an exact address, or a CIDR block (`10.0.0.0/8`, `fd00::/8`). */\ninterface Range {\n readonly v6: boolean;\n readonly bits: bigint;\n readonly prefix: number;\n}\n\n/** An address as a number (IPv4 in 32 bits, IPv6 in 128), or `undefined` when it isn't one. */\nfunction addressBits(address: string): { readonly v6: boolean; readonly bits: bigint } | undefined {\n let text = address.trim();\n if (text.startsWith(\"[\") && text.endsWith(\"]\")) text = text.slice(1, -1);\n // An IPv4 address mapped into IPv6, as Node reports a dual-stack peer.\n const mapped = /^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/i.exec(text);\n if (mapped) text = mapped[1] as string;\n if (isIPv4(text)) {\n const parts = text.split(\".\").map(Number);\n return {\n v6: false,\n bits: parts.reduce((sum, part) => (sum << 8n) | BigInt(part), 0n),\n };\n }\n if (!isIPv6(text)) return undefined;\n const zone = text.indexOf(\"%\");\n if (zone !== -1) text = text.slice(0, zone);\n // A trailing IPv4 part becomes two groups. It is what follows the last colon, read without a\n // pattern: an address comes from a client's `X-Forwarded-For` (CodeQL js/polynomial-redos).\n const last = text.slice(text.lastIndexOf(\":\") + 1);\n if (last.includes(\".\")) {\n if (!isIPv4(last)) return undefined;\n const parts = last.split(\".\").map(Number);\n const high = (((parts[0] as number) << 8) | (parts[1] as number)).toString(16);\n const low = (((parts[2] as number) << 8) | (parts[3] as number)).toString(16);\n text = `${text.slice(0, -last.length)}${high}:${low}`;\n }\n const [head, tail] = text.split(\"::\") as [string, string | undefined];\n const left = head === \"\" ? [] : head.split(\":\");\n const right = tail === undefined ? [] : tail === \"\" ? [] : tail.split(\":\");\n const groups =\n tail === undefined\n ? left\n : [...left, ...new Array(8 - left.length - right.length).fill(\"0\"), ...right];\n if (groups.length !== 8) return undefined;\n return {\n v6: true,\n bits: groups.reduce((sum, group) => (sum << 16n) | BigInt(Number.parseInt(group, 16)), 0n),\n };\n}\n\nfunction parseRange(text: string): Range | undefined {\n const [address, prefixText] = text.split(\"/\") as [string, string | undefined];\n const found = addressBits(address);\n if (!found) return undefined;\n const width = found.v6 ? 128 : 32;\n const prefix = prefixText === undefined ? width : Number(prefixText);\n if (!Number.isInteger(prefix) || prefix < 0 || prefix > width) return undefined;\n return { v6: found.v6, bits: found.bits, prefix };\n}\n\nfunction inRange(range: Range, address: { readonly v6: boolean; readonly bits: bigint }): boolean {\n if (range.v6 !== address.v6) return false;\n const width = range.v6 ? 128n : 32n;\n const shift = width - BigInt(range.prefix);\n return range.bits >> shift === address.bits >> shift;\n}\n\n/** Whether every entry of `trustedProxies` is an address or a CIDR block. */\nexport function validProxies(entries: readonly string[]): string | undefined {\n return entries.find((entry) => parseRange(entry) === undefined);\n}\n\n/** Resolves a request's client address through the configured trusted proxies. */\nexport interface ClientAddresses {\n /** The client's address: the peer's, or the forwarded one when the peer is a trusted proxy. */\n of(incoming: IncomingMessage): string | undefined;\n /** The key a rate counts the address under: the address, or its IPv6 prefix. */\n keyOf(address: string | undefined): string;\n}\n\n/** Options for {@link clientAddresses}. */\nexport interface ClientAddressOptions {\n readonly trustedProxies?: readonly string[] | undefined;\n /** IPv6 addresses count per this prefix (default 64). */\n readonly ipv6Prefix?: number | undefined;\n}\n\n/** Builds the resolver; an entry that isn't an address or a block is ignored (checked at start). */\nexport function clientAddresses(options: ClientAddressOptions): ClientAddresses {\n const proxies = (options.trustedProxies ?? [])\n .map(parseRange)\n .filter((range): range is Range => range !== undefined);\n const trusted = (address: string): boolean => {\n const bits = addressBits(address);\n return bits !== undefined && proxies.some((range) => inRange(range, bits));\n };\n const ipv6Prefix = options.ipv6Prefix ?? 64;\n const seen = new WeakMap<IncomingMessage, string | undefined>();\n return {\n of(incoming) {\n if (seen.has(incoming)) return seen.get(incoming);\n const peer = incoming.socket.remoteAddress;\n let client = peer;\n if (peer !== undefined && trusted(peer)) {\n const header = incoming.headers[\"x-forwarded-for\"];\n const entries = (Array.isArray(header) ? header.join(\",\") : (header ?? \"\"))\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\");\n // From the right: each hop appends the address it saw; the first one that isn't one of\n // ours is the client. Anything to its left was written by the client and is believed by\n // no one.\n for (let index = entries.length - 1; index >= 0; index--) {\n const entry = entries[index] as string;\n if (addressBits(entry) === undefined) break;\n client = entry;\n if (!trusted(entry)) break;\n }\n }\n seen.set(incoming, client);\n return client;\n },\n keyOf(address) {\n if (address === undefined) return \"unknown\";\n const bits = addressBits(address);\n if (!bits) return `other:${address}`;\n if (!bits.v6) return `v4:${bits.bits.toString(16)}`;\n const shift = 128n - BigInt(ipv6Prefix);\n return `v6:${(bits.bits >> shift).toString(16)}/${ipv6Prefix}`;\n },\n };\n}\n\n/** A rate: `count` per `perMs`. */\nexport interface RateLimit {\n readonly count: number;\n readonly perMs: number;\n}\n\n/**\n * A token-bucket rate limiter over keys, in memory, bounded in the keys it keeps: each key holds up\n * to `count` tokens and earns them back at `count` per `perMs`, so a burst of `count` passes and\n * the sustained rate is exactly the rate.\n */\nexport class RateLimiter {\n readonly #buckets = new Map<string, { tokens: number; at: number }>();\n readonly #now: () => number;\n readonly #maxKeys: number;\n\n constructor(options: { readonly now?: () => number; readonly maxKeys?: number } = {}) {\n this.#now = options.now ?? (() => Date.now());\n this.#maxKeys = options.maxKeys ?? 100_000;\n }\n\n /** A key's bucket, refilled to now and marked most recently used, so the bound drops the least. */\n #bucket(key: string, rate: RateLimit, now: number): { tokens: number; at: number } {\n const perToken = rate.perMs / rate.count;\n let bucket = this.#buckets.get(key);\n if (bucket) {\n bucket.tokens = Math.min(rate.count, bucket.tokens + (now - bucket.at) / perToken);\n bucket.at = now;\n this.#buckets.delete(key);\n } else {\n if (this.#buckets.size >= this.#maxKeys) {\n this.#buckets.delete(this.#buckets.keys().next().value as string);\n }\n bucket = { tokens: rate.count, at: now };\n }\n this.#buckets.set(key, bucket);\n return bucket;\n }\n\n /** How long until every bucket holds a token: 0 when they all do now. */\n #wait(\n wanted: readonly { readonly key: string; readonly rate: RateLimit }[],\n now: number,\n ): { readonly waitMs: number; readonly buckets: { tokens: number }[] } {\n let waitMs = 0;\n const buckets = wanted.map(({ key, rate }) => {\n const bucket = this.#bucket(key, rate, now);\n if (bucket.tokens < 1)\n waitMs = Math.max(waitMs, (1 - bucket.tokens) * (rate.perMs / rate.count));\n return bucket;\n });\n return { waitMs, buckets };\n }\n\n /**\n * Takes one token under `key` when there is one. Without one, nothing is taken and the answer\n * says when to try again, in whole seconds (`Retry-After`).\n */\n take(\n key: string,\n rate: RateLimit,\n ): { readonly ok: true } | { readonly ok: false; readonly retryAfterS: number } {\n return this.takeAll([{ key, rate }]);\n }\n\n /**\n * Gives back the token `takeAll` took under every key, as far as each bucket's size: an attempt\n * someone refused after the rates admitted it (the operator's `limits`) costs nothing (second\n * Fable review of WP-30, 2).\n */\n refundAll(wanted: readonly { readonly key: string; readonly rate: RateLimit }[]): void {\n const now = this.#now();\n for (const { key, rate } of wanted) {\n const bucket = this.#bucket(key, rate, now);\n bucket.tokens = Math.min(rate.count, bucket.tokens + 1);\n }\n }\n\n /**\n * Takes one token under every key, or none: when any bucket is empty, nothing is taken from the\n * others, and the answer says when the slowest one has a token again (Fable review, 8).\n */\n takeAll(\n wanted: readonly { readonly key: string; readonly rate: RateLimit }[],\n ): { readonly ok: true } | { readonly ok: false; readonly retryAfterS: number } {\n const { waitMs, buckets } = this.#wait(wanted, this.#now());\n if (waitMs > 0) return { ok: false, retryAfterS: Math.max(1, Math.ceil(waitMs / 1000)) };\n for (const bucket of buckets) bucket.tokens -= 1;\n return { ok: true };\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 version: 2,\n name: \"operator, sign-in and links\",\n up(db) {\n // WP-30 (DATA_MODEL §7.1, additive). A home an operator drained is refused until released;\n // the hosted links of every home, so a handle's revokeLink finds its home; the instance link\n // of each operator-issued credential; sign-ins in progress and the API origin's browser\n // sessions (both by SHA-256 only); and the monthly metering keys' months.\n db.exec(`\n ALTER TABLE home ADD COLUMN drained_at TEXT;\n ALTER TABLE home ADD COLUMN suspend_reason TEXT;\n CREATE TABLE hosted_token (\n token_id TEXT PRIMARY KEY,\n home_id TEXT NOT NULL REFERENCES home(id),\n route_id TEXT NOT NULL\n );\n CREATE TABLE credential_link (\n account_id TEXT NOT NULL REFERENCES account(id),\n subject TEXT NOT NULL,\n link_id TEXT NOT NULL REFERENCES instance_link(id),\n PRIMARY KEY (account_id, subject)\n );\n CREATE TABLE signin (\n hash TEXT PRIMARY KEY,\n kind TEXT NOT NULL CHECK (kind IN ('provider', 'step', 'authorize')),\n data_json TEXT NOT NULL,\n expires_at TEXT NOT NULL\n );\n CREATE TABLE browser_session (\n hash TEXT PRIMARY KEY,\n account_id TEXT NOT NULL REFERENCES account(id),\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL\n );\n CREATE INDEX browser_session_account ON browser_session(account_id);\n -- A host an operator supplies through routing (D165 item 7, D167): a hosted shell for one\n -- home (or one route of it), its frames on <label>.<frame_domain>. Recorded with its\n -- label_issued row when first served, kept forever and never moved to another home.\n CREATE TABLE operator_host (\n host TEXT PRIMARY KEY,\n home_id TEXT NOT NULL REFERENCES home(id),\n route_id TEXT,\n frame_domain TEXT NOT NULL,\n recorded_at TEXT NOT NULL\n );\n CREATE INDEX operator_host_frames ON operator_host(frame_domain);\n CREATE TRIGGER operator_host_kept BEFORE DELETE ON operator_host\n BEGIN\n SELECT RAISE(ABORT, 'an operator host is kept forever');\n END;\n CREATE TRIGGER operator_host_fixed BEFORE UPDATE ON operator_host\n WHEN NEW.host IS NOT OLD.host OR NEW.home_id IS NOT OLD.home_id\n BEGIN\n SELECT RAISE(ABORT, 'an operator host never moves to another home');\n END;\n `);\n },\n },\n {\n version: 3,\n name: \"a route's removal in progress\",\n up(db) {\n // ServerHandle.remove spans two databases, the home's ledger and this directory, so it\n // records its plan here first (the versions and client files it removes); a removal cut\n // off between them is finished by the next call, and the route serves nothing meanwhile\n // (Fable review of WP-30, 4).\n db.exec(\"ALTER TABLE artifact_route ADD COLUMN removing_json TEXT\");\n },\n },\n {\n version: 4,\n name: \"invitations in the outbound queue\",\n up(db) {\n // WP-31 (D168): the operator's `invitations` port is delivered like `events` and `metering`,\n // at least once from the same queue; a row keeps the link's token, never its URL. SQLite\n // can't widen a CHECK in place, so the table is rebuilt with every row it holds.\n db.exec(`\n CREATE TABLE outbound_next (\n id TEXT PRIMARY KEY,\n port TEXT NOT NULL CHECK (port IN ('metering', 'events', 'invitations')),\n payload_json TEXT NOT NULL,\n attempts INTEGER NOT NULL DEFAULT 0,\n next_attempt_at TEXT NOT NULL\n );\n INSERT INTO outbound_next (rowid, id, port, payload_json, attempts, next_attempt_at)\n SELECT rowid, id, port, payload_json, attempts, next_attempt_at FROM outbound;\n DROP TABLE outbound;\n ALTER TABLE outbound_next RENAME TO outbound;\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 /**\n * Closes a home now, if open, and holds it closed until `undrain` (`ServerHandle.drainHome`):\n * every request for it meanwhile is refused with `MOSTRA_REMOTE_HOME_MOVING`, so two data\n * directories never serve one home at once.\n */\n drain(id: string): Promise<void>;\n /** Serves a drained home again (`ServerHandle.releaseHome`). */\n undrain(id: string): void;\n /**\n * A restore from a backup by hand (`ServerHandle.restored`): the home is closed and rotates its\n * incarnation before it serves anything again.\n */\n restored(id: string): Promise<void>;\n /** Closes a home now if open (it reopens on its next request). */\n closeHome(id: string): Promise<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; drained_at: string | null }>(\n \"SELECT data_path, drained_at FROM home WHERE id = ?\",\n id,\n ),\n );\n if (!row) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", { message: `No hosted home ${id}.` }),\n );\n }\n if (row.drained_at !== null) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_REMOTE_HOME_MOVING\", {\n message: \"This account's pages are moving to another machine; try again in a minute.\",\n }),\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 closeHome(id) {\n const entry = entries.get(id);\n if (!entry) return;\n entry.closing ??= closeHome(id, entry);\n await entry.closing;\n },\n async drain(id) {\n directory.write((db) =>\n db.run(\n \"UPDATE home SET drained_at = COALESCE(drained_at, ?) WHERE id = ?\",\n new Date().toISOString(),\n id,\n ),\n );\n const entry = entries.get(id);\n if (entry) {\n entry.closing ??= closeHome(id, entry);\n await entry.closing;\n }\n log.info(\"server.home_drained\", { home: id });\n },\n undrain(id) {\n directory.write((db) => db.run(\"UPDATE home SET drained_at = NULL WHERE id = ?\", id));\n log.info(\"server.home_released\", { home: id });\n },\n async restored(id) {\n restores.add(id);\n const entry = entries.get(id);\n if (entry) {\n entry.closing ??= closeHome(id, entry);\n await entry.closing;\n }\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 server handle an operator module receives (INTERFACES §18.6, D165 item 9): quarantine,\n * pause, suspension, link revocation, moving and restoring homes, and deletion. Every target names\n * a hosted route (`rte_…`), never a bare artifact or version ID, since those repeat across homes\n * when a project is copied: acting on one route never touches another home hosting the same\n * artifact ID or an identical version. Each call is durable when it resolves.\n */\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { OPERATOR_REVISION, type ServerHandle } from \"@mostra/protocol/operator\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport type { DataDirectory } from \"./data.ts\";\nimport type { HostedHome } from \"./hosted.ts\";\n\n/** Options for {@link createHandle}. */\nexport interface HandleOptions {\n readonly apiOrigin: string;\n /** The data directory; set once it is open (the handle is made before the operator loads). */\n readonly data: () => DataDirectory<HostedHome>;\n readonly directory: () => Ledger;\n /** Closes the bindings of a suspended home at once (the API origin's). */\n readonly suspended: (homeId: string) => void;\n readonly log: Log;\n}\n\nfunction unknownTarget(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", { message }));\n}\n\n/** Builds the handle. */\nexport function createHandle(options: HandleOptions): ServerHandle {\n const { log } = options;\n\n /** A route's home and artifact; an unknown route is refused, never guessed. */\n const route = (routeId: string): { readonly home: string; readonly artifactId: string } => {\n const row = options\n .directory()\n .read((db) =>\n db.get<{ home_id: string; artifact_id: string }>(\n \"SELECT home_id, artifact_id FROM artifact_route WHERE id = ?\",\n routeId,\n ),\n );\n if (!row) throw unknownTarget(`No hosted route ${routeId}.`);\n return { home: row.home_id, artifactId: row.artifact_id };\n };\n\n const homeOf = async (homeId: string): Promise<HostedHome> =>\n (await options.data().home(homeId)).assembled;\n\n const knownHome = (homeId: string): void => {\n const found = options\n .directory()\n .read((db) => db.get(\"SELECT 1 FROM home WHERE id = ?\", homeId));\n if (!found) throw unknownTarget(`No hosted home ${homeId}.`);\n };\n\n return {\n revision: OPERATOR_REVISION,\n apiOrigin: options.apiOrigin,\n\n async quarantine(target, reason) {\n const found = route(target.routeId);\n const home = await homeOf(found.home);\n home.quarantine(\n found.artifactId,\n \"versionId\" in target ? target.versionId : undefined,\n reason,\n );\n log.info(\"operator.quarantine\", { routeId: target.routeId });\n },\n\n async release(target) {\n const found = route(target.routeId);\n const home = await homeOf(found.home);\n home.release(found.artifactId, \"versionId\" in target ? target.versionId : undefined);\n log.info(\"operator.release\", { routeId: target.routeId });\n },\n\n async pause(routeId, reason) {\n const found = route(routeId);\n (await homeOf(found.home)).pause(found.artifactId, { paused: true, by: \"operator\", reason });\n log.info(\"operator.pause\", { routeId });\n },\n\n async resume(routeId) {\n const found = route(routeId);\n (await homeOf(found.home)).pause(found.artifactId, { paused: false, by: \"operator\" });\n log.info(\"operator.resume\", { routeId });\n },\n\n async suspendHome(homeId, reason) {\n knownHome(homeId);\n options\n .directory()\n .write((db) =>\n db.run(\n \"UPDATE home SET suspended_at = COALESCE(suspended_at, ?), suspend_reason = ? WHERE id = ?\",\n new Date().toISOString(),\n reason.slice(0, 1_000),\n homeId,\n ),\n );\n options.suspended(homeId);\n await options.data().closeHome(homeId);\n log.info(\"operator.suspend_home\", { home: homeId });\n },\n\n async resumeHome(homeId) {\n knownHome(homeId);\n options\n .directory()\n .write((db) =>\n db.run(\"UPDATE home SET suspended_at = NULL, suspend_reason = NULL WHERE id = ?\", homeId),\n );\n log.info(\"operator.resume_home\", { home: homeId });\n },\n\n async revokeLinks(routeId) {\n const found = route(routeId);\n const count = (await homeOf(found.home)).revokeLinks(found.artifactId);\n log.info(\"operator.revoke_links\", { routeId, count });\n return count;\n },\n\n async revokeLink(tokenId) {\n const row = options\n .directory()\n .read((db) =>\n db.get<{ home_id: string }>(\n \"SELECT home_id FROM hosted_token WHERE token_id = ?\",\n tokenId,\n ),\n );\n if (!row) throw unknownTarget(`No hosted link ${tokenId}.`);\n if (!(await homeOf(row.home_id)).revokeLink(tokenId)) {\n throw unknownTarget(`No hosted link ${tokenId}.`);\n }\n log.info(\"operator.revoke_link\", { tokenId });\n },\n\n async drainHome(homeId) {\n knownHome(homeId);\n options.suspended(homeId);\n await options.data().drain(homeId);\n },\n\n async releaseHome(homeId) {\n knownHome(homeId);\n options.data().undrain(homeId);\n },\n\n async restored(homeId) {\n knownHome(homeId);\n await options.data().restored(homeId);\n log.info(\"operator.restored\", { home: homeId });\n },\n\n async remove(routeId) {\n const found = route(routeId);\n const home = await homeOf(found.home);\n try {\n await home.remove(found.artifactId);\n } finally {\n // The home reopens from its ledger on its next request, holding nothing of the artifact,\n // and nothing a removal cut off part-way left open in it (second Fable review, 8).\n await options.data().closeHome(found.home);\n }\n log.info(\"operator.remove\", { routeId });\n },\n };\n}\n","/**\n * A hosted home's events for its operator (INTERFACES §18.6, D165 item 9): `submission.accepted`\n * (with the submission's Results), `version.pushed`, `run.ended` and `roster.completed` (D168), and\n * an invitation for each expected respondent with an email whom the roster added or gave a new\n * personal link (`roster.changed`'s `added` and `relinked`), read from the home's own\n * event log after `operator_cursor` and handed to the server's durable outbound queue, so each is\n * delivered at least once with a stable ID (`<home>:<incarnation>:<cursor>`). The cursor moves\n * only after the queue holds what was read; a crash between them hands the same events again,\n * under the same IDs. Submissions are counted for metering on the same read. Each event carries\n * its route's label beside its ID (D167).\n *\n * With neither an events nor a metering port, the cursor follows the head, so an operator added\n * later starts from then rather than from the home's whole history.\n */\nimport type { OperatorEvent } from \"@mostra/protocol/operator\";\nimport type { Interaction } from \"../interaction/index.ts\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport type { Meter } from \"./metering.ts\";\nimport type { Operator } from \"./operator.ts\";\n\n/** How many events one read takes. */\nconst PAGE = 200;\n\n/** Options for {@link createOperatorFeed}. */\nexport interface OperatorFeedOptions {\n readonly homeId: string;\n readonly ledger: Ledger;\n readonly interaction: Interaction;\n readonly operator: Operator;\n readonly meter: Meter;\n readonly account: () => string;\n /** Who sends the home's invitations: its owner's name and how it was verified. */\n readonly sender?: () => { readonly name?: string; readonly verifiedBy?: string };\n readonly routeOf: (\n artifactId: string,\n ) => { readonly id: string; readonly label: string } | undefined;\n readonly incarnation: () => string;\n readonly log: Log;\n}\n\n/** The feed of one open hosted home. */\nexport interface OperatorFeed {\n /** Reads what is new now (after every commit, and when the home opens). */\n scan(): void;\n stop(): void;\n}\n\ninterface EventRow {\n readonly cursor: number;\n readonly artifact_id: string | null;\n readonly type: string;\n readonly payload_json: string;\n readonly at: string;\n}\n\nconst RUN_ENDS = new Map([\n [\"action.succeeded\", \"succeeded\"],\n [\"action.failed\", \"failed\"],\n [\"action.cancelled\", \"cancelled\"],\n [\"action.unknown\", \"unknown\"],\n]);\n\n/** Starts the feed of a home. */\nexport function createOperatorFeed(options: OperatorFeedOptions): OperatorFeed {\n const { ledger, operator, meter, log } = options;\n const wanted = operator.has.events || meter.on || operator.has.invitations;\n let stopped = false;\n let scheduled = false;\n\n const cursorOf = (): number =>\n ledger.read(\n (db) =>\n db.get<{ cursor: number }>(\"SELECT cursor FROM operator_cursor WHERE id = 1\")?.cursor ?? -1,\n );\n /**\n * Moves the cursor forward. It writes only when the cursor moves, since every write is a commit\n * that schedules another read: a write that changed nothing would read again for ever.\n */\n const setCursor = (cursor: number): void => {\n if (cursor <= cursorOf()) return;\n ledger.write((db) =>\n db.run(\n `INSERT INTO operator_cursor (id, cursor) VALUES (1, ?)\n ON CONFLICT (id) DO UPDATE SET cursor = MAX(cursor, excluded.cursor)`,\n cursor,\n ),\n );\n };\n const head = (): number =>\n ledger.read(\n (db) => db.get<{ head: number | null }>(\"SELECT MAX(cursor) AS head FROM event\")?.head ?? 0,\n );\n\n const toEvent = (row: EventRow): OperatorEvent | undefined => {\n if (row.artifact_id === null) return undefined;\n const route = options.routeOf(row.artifact_id);\n if (!route) return undefined;\n const payload = JSON.parse(row.payload_json) as Record<string, unknown>;\n const base = {\n eventId: `${options.homeId}:${options.incarnation()}:${row.cursor}`,\n account: options.account(),\n home: options.homeId,\n routeId: route.id,\n label: route.label,\n artifactId: row.artifact_id,\n at: row.at,\n };\n if (row.type === \"submission.created\") {\n const results = options.interaction.resultsOf(String(payload[\"submissionId\"]));\n return results ? { ...base, kind: \"submission.accepted\", payload: results } : undefined;\n }\n if (row.type === \"version.published\") {\n return {\n ...base,\n kind: \"version.pushed\",\n payload: { versionId: payload[\"versionId\"], number: payload[\"number\"] },\n };\n }\n if (row.type === \"roster.completed\") {\n return {\n ...base,\n kind: \"roster.completed\",\n payload: {\n round: payload[\"round\"],\n respondents: payload[\"respondents\"],\n submissions: payload[\"submissions\"],\n },\n };\n }\n const status = RUN_ENDS.get(row.type);\n if (status !== undefined) {\n return {\n ...base,\n kind: \"run.ended\",\n payload: { runId: payload[\"runId\"], action: payload[\"action\"], status },\n };\n }\n return undefined;\n };\n\n /**\n * The invitations a roster change calls for (D168): one per respondent it added or gave a new\n * link, who has an email and is still expected, keyed by their link's token, so a repeated read\n * enqueues nothing new and a later link gets an invitation of its own.\n */\n const invite = (row: EventRow): void => {\n if (row.artifact_id === null) return;\n const route = options.routeOf(row.artifact_id);\n if (!route) return;\n const payload = JSON.parse(row.payload_json) as {\n added?: readonly { ref?: unknown }[];\n relinked?: readonly unknown[];\n };\n const refs = new Set<string>([\n ...(payload.added ?? []).flatMap((entry) =>\n typeof entry.ref === \"string\" ? [entry.ref] : [],\n ),\n ...(payload.relinked ?? []).filter((ref): ref is string => typeof ref === \"string\"),\n ]);\n if (refs.size === 0) return;\n const artifactId = row.artifact_id;\n const found = ledger.read((db) => ({\n title: db.get<{ title: string }>(\"SELECT title FROM artifact WHERE id = ?\", artifactId)\n ?.title,\n entries: [...refs].flatMap((ref) => {\n const entry = db.get<{\n ref: string;\n name: string | null;\n email: string | null;\n token_id: string | null;\n }>(\n \"SELECT ref, name, email, token_id FROM roster_entry WHERE artifact_id = ? AND ref = ?\",\n artifactId,\n ref,\n );\n return entry && entry.email !== null && entry.token_id !== null ? [entry] : [];\n }),\n }));\n const sender = options.sender?.() ?? {};\n for (const entry of found.entries) {\n operator.enqueue({\n port: \"invitations\",\n invitation: {\n invitationId: `${options.homeId}:${entry.token_id}`,\n account: options.account(),\n home: options.homeId,\n routeId: route.id,\n label: route.label,\n artifactId,\n title: found.title ?? \"\",\n respondent: {\n ref: entry.ref,\n ...(entry.name !== null ? { name: entry.name } : {}),\n email: entry.email as string,\n },\n sender: {\n ...(sender.name !== undefined ? { name: sender.name } : {}),\n ...(sender.verifiedBy !== undefined ? { verifiedBy: sender.verifiedBy } : {}),\n },\n tokenId: entry.token_id as string,\n at: row.at,\n },\n });\n }\n };\n\n const scan = (): void => {\n scheduled = false;\n if (stopped) return;\n try {\n let cursor = cursorOf();\n if (!wanted || cursor < 0) {\n // No port reads the feed, or it starts now: from the head, never the whole history.\n setCursor(Math.max(0, head()));\n if (!wanted) return;\n cursor = Math.max(0, cursorOf());\n }\n for (;;) {\n const rows = ledger.read((db) =>\n db.all<EventRow>(\n `SELECT cursor, artifact_id, type, payload_json, at FROM event WHERE cursor > ?\n AND type IN ('submission.created', 'version.published', 'action.succeeded',\n 'action.failed', 'action.cancelled', 'action.unknown',\n 'roster.changed', 'roster.completed')\n ORDER BY cursor LIMIT ?`,\n cursor,\n PAGE,\n ),\n );\n for (const row of rows) {\n if (row.type === \"roster.changed\") {\n if (operator.has.invitations) invite(row);\n continue;\n }\n const event = toEvent(row);\n if (!event) continue;\n if (event.kind === \"submission.accepted\") {\n meter.add(\"submissions\", {\n account: event.account,\n home: event.home,\n artifactId: event.artifactId,\n routeId: event.routeId,\n });\n }\n if (operator.has.events) operator.enqueue({ port: \"events\", event });\n }\n // Up to the last event read, or the head when nothing matched past the cursor.\n const last = rows.at(-1)?.cursor;\n if (last === undefined) {\n setCursor(Math.max(cursor, head()));\n return;\n }\n setCursor(last);\n cursor = last;\n if (rows.length < PAGE) return;\n }\n } catch (error) {\n log.warn(\"operator.feed_failed\", { home: options.homeId, error });\n }\n };\n\n const unsubscribe = ledger.onCommit(() => {\n if (scheduled || stopped) return;\n scheduled = true;\n setImmediate(scan);\n });\n scan();\n\n return {\n scan,\n stop() {\n stopped = true;\n unsubscribe();\n },\n };\n}\n","/**\n * A hosted home's pages beyond the local gateway's (ARCHITECTURE §15.6 to §15.8, INTERFACES\n * §18.4, D161, D165 items 8, 9, 13, 14): who a browser is on a link minted without a viewer, what\n * the trusted chrome shows around a view, which views and submissions the server's rules refuse\n * before they reach the ledger, and the shell routes of a hosted home of its own (the report\n * control, an anonymous viewer's name; sign-in arrives with the authorization server).\n *\n * Everything here answers through the gateway's one checked route table and its hooks\n * (`HostedAddressing`), so every rule is applied in the same order as every other route's (D96).\n */\nimport { randomBytes } from \"node:crypto\";\nimport {\n type ArtifactDetail,\n createDiagnostic,\n type HostedChrome,\n type Refusal,\n refusal,\n} from \"@mostra/protocol\";\nimport type { LinkPolicy } from \"@mostra/protocol/operator\";\nimport {\n type Capabilities,\n type HostedAddressing,\n isRefusal,\n jsonResponse,\n type RouteContext,\n type RouteSpec,\n readJsonObject,\n} from \"../gateway/index.ts\";\nimport type { Interaction } from \"../interaction/index.ts\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport type { ClientAddresses, RateLimit, RateLimiter } from \"./clients.ts\";\nimport type { Operator } from \"./operator.ts\";\n\n/** How long the server's reports from one address may come: 20 an hour (the operator's inbox). */\nconst REPORT_RATE: RateLimit = { count: 20, perMs: 60 * 60_000 };\n\n/** Who owns a hosted home, as its pages name them (D161's sender line). */\nexport interface HomeOwner {\n readonly account: string;\n /** The account's display name. */\n readonly name?: string;\n /** The label of the identity provider that verified the name; absent: unverified. */\n readonly verifiedBy?: string;\n}\n\n/** Options for {@link hostedPages}. */\nexport interface HostedPagesOptions {\n readonly homeId: string;\n readonly ledger: Ledger;\n readonly interaction: Interaction;\n readonly capabilities: Capabilities;\n readonly artifact: (artifactId: string) => ArtifactDetail;\n readonly routeOf: (\n artifactId: string,\n ) => { readonly id: string; readonly label: string } | undefined;\n readonly owner: () => HomeOwner;\n /** Whether the server can sign a viewer in (an identity provider is configured or supplied). */\n readonly signInOffered: () => boolean;\n readonly operator: Operator;\n readonly clients: ClientAddresses;\n readonly rates: RateLimiter;\n /** `rateLimits` of the configuration, in milliseconds (D165 item 13). */\n readonly rateLimits: {\n readonly perIpSubmissions?: RateLimit | undefined;\n readonly perLinkSubmissions?: RateLimit | undefined;\n };\n /** The configuration's made-with mark (off unless an operator shows it, D161). */\n readonly madeWith?: { readonly href?: string } | undefined;\n /** Viewer sign-in on the authorization server, when one is configured (INTERFACES §18.4). */\n readonly signin?: {\n readonly start: (\n signin: { homeId: string; routeId: string; sessionId: string; shellOrigin: string },\n challenge: string,\n ) => { readonly url: string; readonly state: string };\n readonly finish: (input: {\n state: string;\n code: string;\n verifier: string;\n routeId: string;\n sessionId: string;\n }) =>\n | { readonly accountId: string; readonly name?: string; readonly provider?: string }\n | { readonly refused: string };\n };\n /** Told each view the server admitted, for metering (`views`). */\n readonly viewed?: (input: { readonly artifactId: string; readonly viewerId: string }) => void;\n readonly log: Log;\n readonly now?: () => number;\n}\n\n/** A refusal with any cataloged code (the gateway's own `refusal` takes HYGIENE codes only). */\nfunction refuseWith(\n code: Parameters<typeof createDiagnostic>[0],\n message: string,\n status: number,\n): Refusal {\n return { status, diagnostic: createDiagnostic(code, { message }) };\n}\n\n/** The milliseconds of a duration such as `7d` (checked by the operator's schema). */\nfunction durationMs(text: string): number {\n const unit = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }[text.slice(-1)] ?? 0;\n return Number(text.slice(0, -1)) * unit;\n}\n\n/** The gateway hooks of one hosted home's pages. */\nexport function hostedPages(\n options: HostedPagesOptions,\n): Required<\n Pick<\n HostedAddressing,\n | \"client\"\n | \"anonymousViewer\"\n | \"admitView\"\n | \"blocked\"\n | \"chrome\"\n | \"admitSubmit\"\n | \"shellRoutes\"\n >\n> {\n const { ledger, interaction, capabilities, operator, log } = options;\n const now = options.now ?? (() => Date.now());\n\n /** A route's quarantine: the whole route's, or this version's (D165 item 9). */\n const quarantineOf = (artifactId: string, versionId: string): string | undefined =>\n ledger.read(\n (db) =>\n db.get<{ reason: string }>(\n \"SELECT reason FROM quarantine WHERE artifact_id = ? AND version_id IN ('', ?) LIMIT 1\",\n artifactId,\n versionId,\n )?.reason,\n );\n\n const underReview = (): Refusal =>\n refuseWith(\n \"MOSTRA_REMOTE_UNDER_REVIEW\",\n \"This page is under review by the server's operator.\",\n 403,\n );\n\n const policyFor = (artifactId: string, tokenId?: string): Promise<LinkPolicy> => {\n const route = options.routeOf(artifactId);\n if (!route) return Promise.resolve({});\n return operator.linkPolicy({\n account: options.owner().account,\n home: options.homeId,\n routeId: route.id,\n artifactId,\n ...(tokenId !== undefined ? { tokenId } : {}),\n });\n };\n\n /** A link past the operator's longest lifetime or idle limit: revoked now, 410 (D165 item 9). */\n const expired = (tokenId: string, policy: LinkPolicy): Refusal | undefined => {\n if (policy.maxTtl === undefined && policy.idleExpiry === undefined) return undefined;\n const used = ledger.read((db) =>\n db.get<{ created_at: string; last: string | null }>(\n `SELECT t.created_at, (SELECT MAX(last_seen_at) FROM session s WHERE s.token_id = t.id) AS last\n FROM token t WHERE t.id = ?`,\n tokenId,\n ),\n );\n if (!used) return undefined;\n const minted = Date.parse(used.created_at);\n const lastUse = Math.max(minted, used.last === null ? 0 : Date.parse(used.last));\n const tooOld = policy.maxTtl !== undefined && now() - minted > durationMs(policy.maxTtl);\n const idle = policy.idleExpiry !== undefined && now() - lastUse > durationMs(policy.idleExpiry);\n if (!tooOld && !idle) return undefined;\n capabilities.revoke(tokenId);\n log.info(\"hosted.link_expired\", { tokenId, why: tooOld ? \"max-ttl\" : \"idle\" });\n return refusal(\"MOSTRA_HYGIENE_TOKEN_REVOKED\", \"This link has expired.\", 410);\n };\n\n const limitRefusal = (\n verdict: Awaited<ReturnType<Operator[\"limit\"]>>,\n ): (Refusal & { readonly retryAfter?: number }) | undefined => {\n if (verdict.allowed !== false) return undefined;\n return {\n ...refuseWith(\"MOSTRA_REMOTE_LIMIT_REACHED\", verdict.message, 403),\n ...(verdict.retryAfterMs !== undefined\n ? { retryAfter: Math.max(1, Math.ceil(verdict.retryAfterMs / 1000)) }\n : {}),\n };\n };\n\n const rateRefusal = (retryAfterS: number): Refusal & { readonly retryAfter: number } => ({\n ...refuseWith(\n \"MOSTRA_REMOTE_RATE_LIMITED\",\n \"Too many answers came through here in a short time; try again shortly.\",\n 429,\n ),\n retryAfter: retryAfterS,\n });\n\n const shellRoutes = (helpers: Parameters<NonNullable<HostedAddressing[\"shellRoutes\"]>>[0]) => {\n const meta = (context: RouteContext) => ({\n method: context.request.method,\n path: new URL(context.request.url).pathname,\n document: false,\n });\n\n /** The report control (D161): reaches the operator's `abuse.report`. */\n const report = async (context: RouteContext): Promise<Response> => {\n const artifactId = context.artifactId as string;\n const body = await readJsonObject(context.request, 16 * 1024);\n if (isRefusal(body)) return helpers.refuse(body, meta(context));\n const reason = body[\"reason\"];\n const detail = body[\"detail\"];\n if (\n typeof reason !== \"string\" ||\n !/^[a-z][a-z0-9-]{0,31}$/.test(reason) ||\n (detail !== undefined && (typeof detail !== \"string\" || detail.length > 2_000))\n ) {\n return helpers.refuse(\n refusal(\n \"MOSTRA_HYGIENE_REQUEST_MALFORMED\",\n \"A report names a `reason` (a short word) and at most 2000 characters of `detail`.\",\n ),\n meta(context),\n );\n }\n const limited = options.rates.take(\n `report:${options.clients.keyOf(context.client)}`,\n REPORT_RATE,\n );\n if (!limited.ok) return helpers.refuse(rateRefusal(limited.retryAfterS), meta(context));\n const route = options.routeOf(artifactId);\n if (!route) {\n return helpers.refuse(\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"No route here.\"),\n meta(context),\n );\n }\n await operator.report({\n routeId: route.id,\n label: route.label,\n artifactId,\n home: options.homeId,\n ...(context.session?.versionId !== undefined\n ? { versionId: context.session.versionId }\n : {}),\n reason,\n ...(typeof detail === \"string\" && detail !== \"\" ? { detail } : {}),\n at: new Date(now()).toISOString(),\n });\n log.info(\"hosted.reported\", { routeId: route.id, reason });\n return jsonResponse({}, { status: 202 });\n };\n\n /** An anonymous viewer's self-chosen name, recorded unverified (D165 item 8). */\n const name = async (context: RouteContext): Promise<Response> => {\n const body = await readJsonObject(context.request, 4 * 1024);\n if (isRefusal(body)) return helpers.refuse(body, meta(context));\n const value = body[\"name\"];\n const cleaned =\n value === null\n ? null\n : typeof value === \"string\"\n ? value.replace(/\\s+/g, \" \").trim().slice(0, 64)\n : undefined;\n if (cleaned === undefined || cleaned === \"\") {\n return helpers.refuse(\n refusal(\"MOSTRA_HYGIENE_REQUEST_MALFORMED\", \"`name` is a short text, or null.\"),\n meta(context),\n );\n }\n const viewerId = interaction.viewerOf(context.session?.viewerId);\n if (!interaction.nameAnonymous(viewerId, cleaned)) {\n return helpers.refuse(\n refusal(\n \"MOSTRA_HYGIENE_SCOPE_DENIED\",\n \"Only a viewer who isn't signed in names themselves here; a signed-in name is the account's.\",\n ),\n meta(context),\n );\n }\n return jsonResponse({ viewer: interaction.viewer(viewerId) });\n };\n\n /**\n * A page's sign-in, from a click in the trusted chrome only (INTERFACES §18.4): the address of\n * the authorization server, with `state` bound to this route and this shell session.\n */\n const signinStart = async (context: RouteContext): Promise<Response> => {\n const body = await readJsonObject(context.request, 4 * 1024);\n if (isRefusal(body)) return helpers.refuse(body, meta(context));\n const challenge = body[\"challenge\"];\n const route = options.routeOf(context.artifactId as string);\n if (\n typeof challenge !== \"string\" ||\n !/^[A-Za-z0-9_-]{43}$/.test(challenge) ||\n !route ||\n !options.signin ||\n !context.session\n ) {\n return helpers.refuse(\n refusal(\n \"MOSTRA_HYGIENE_REQUEST_MALFORMED\",\n \"A sign-in starts with a PKCE S256 challenge.\",\n ),\n meta(context),\n );\n }\n const started = options.signin.start(\n {\n homeId: options.homeId,\n routeId: route.id,\n sessionId: context.session.id,\n // The shell's own origin: the pipeline checked the request's Origin is exactly it.\n shellOrigin: context.request.headers.get(\"origin\") ?? \"\",\n },\n challenge,\n );\n return jsonResponse(started);\n };\n\n /** The code back from the authorization server: the session acts as the account from now on. */\n const signinFinish = async (context: RouteContext): Promise<Response> => {\n const body = await readJsonObject(context.request, 8 * 1024);\n if (isRefusal(body)) return helpers.refuse(body, meta(context));\n const route = options.routeOf(context.artifactId as string);\n const { code, verifier, state } = body as Record<string, unknown>;\n if (\n typeof code !== \"string\" ||\n typeof verifier !== \"string\" ||\n typeof state !== \"string\" ||\n !route ||\n !options.signin ||\n !context.session\n ) {\n return helpers.refuse(\n refusal(\n \"MOSTRA_HYGIENE_REQUEST_MALFORMED\",\n \"Send the sign-in's code, verifier and state.\",\n ),\n meta(context),\n );\n }\n const finished = options.signin.finish({\n code,\n verifier,\n state,\n routeId: route.id,\n sessionId: context.session.id,\n });\n if (\"refused\" in finished) {\n log.warn(\"hosted.signin_refused\", { routeId: route.id });\n return helpers.refuse(\n refusal(\"MOSTRA_HYGIENE_SCOPE_DENIED\", finished.refused, 403),\n meta(context),\n );\n }\n // A link minted for a named person keeps acting as that person (D104); any other session\n // now acts as the account, its name verified by its provider (D165 item 8).\n const viewerId = interaction.viewerForAccount(finished.accountId, finished.name);\n if (context.session.grant.viewerId === undefined) {\n const sessionId = context.session.id;\n ledger.write((db) =>\n db.run(\"UPDATE session SET viewer_id = ? WHERE id = ?\", viewerId, sessionId),\n );\n }\n log.info(\"hosted.signed_in\", { routeId: route.id });\n return jsonResponse({ viewer: interaction.viewer(viewerId) });\n };\n\n const routes: RouteSpec[] = [\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/session/signin/start\",\n intent: \"mutation\",\n auth: \"session\",\n handler: signinStart,\n },\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/session/signin\",\n intent: \"mutation\",\n auth: \"session\",\n handler: signinFinish,\n },\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/report\",\n intent: \"mutation\",\n auth: \"session\",\n handler: report,\n },\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/session/name\",\n intent: \"mutation\",\n auth: \"session\",\n handler: name,\n },\n ];\n return routes;\n };\n\n return {\n client: (incoming) => options.clients.of(incoming),\n\n anonymousViewer: (browser) =>\n interaction.viewerForAnonymous(\n // Without the route's key (storage blocked), a fresh viewer for this session alone: its\n // draft is this page's until a reload, never anyone else's.\n browser ?? `session:${randomBytes(16).toString(\"hex\")}`,\n ),\n\n async admitView(input) {\n if (quarantineOf(input.artifactId, input.versionId) !== undefined) return underReview();\n const policy = await policyFor(input.artifactId, input.tokenId);\n const gone = expired(input.tokenId, policy);\n if (gone) return gone;\n const route = options.routeOf(input.artifactId);\n // `view` proceeds when the operator doesn't answer: nothing a person sees is held up by it.\n const verdict = await operator.limit({\n account: options.owner().account,\n home: options.homeId,\n artifact: input.artifactId,\n ...(route ? { routeId: route.id } : {}),\n operation: \"view\",\n });\n const refused = limitRefusal(verdict);\n if (refused) return refused;\n return undefined;\n },\n\n blocked: (artifactId, versionId) =>\n quarantineOf(artifactId, versionId) !== undefined ? underReview() : undefined,\n\n async chrome(input) {\n const owner = options.owner();\n const viewer = interaction.viewer(input.viewerId);\n const policy = await policyFor(input.artifactId, input.tokenId);\n options.viewed?.({ artifactId: input.artifactId, viewerId: input.viewerId });\n const chrome: HostedChrome = {\n ...(owner.name !== undefined\n ? {\n sender: {\n name: owner.name,\n ...(owner.verifiedBy !== undefined ? { verifiedBy: owner.verifiedBy } : {}),\n },\n }\n : {}),\n viewer:\n viewer.kind === \"account\"\n ? { kind: \"account\", ...(viewer.name ? { name: viewer.name } : {}), verified: true }\n : viewer.kind === \"anonymous\"\n ? {\n kind: \"anonymous\",\n ...(viewer.name ? { name: viewer.name } : {}),\n verified: false,\n }\n : { kind: \"named\", ...(viewer.name ? { name: viewer.name } : {}), verified: false },\n signIn: viewer.kind !== \"account\" && options.signInOffered(),\n ...(policy.footer !== undefined ? { footer: policy.footer } : {}),\n ...(policy.afterSubmit !== undefined ? { afterSubmit: policy.afterSubmit } : {}),\n ...((policy.madeWith?.show ?? options.madeWith !== undefined)\n ? {\n madeWith: {\n ...((policy.madeWith?.href ?? options.madeWith?.href)\n ? { href: (policy.madeWith?.href ?? options.madeWith?.href) as string }\n : {}),\n },\n }\n : {}),\n ...(policy.interstitial !== undefined ? { interstitial: policy.interstitial } : {}),\n };\n return chrome;\n },\n\n async admitSubmit(page, context) {\n const detail = options.artifact(page.artifactId);\n // `hosted.submissions: \"signed-in\"`: an account, or a link minted for a named person.\n if (detail.manifest?.hosted?.submissions === \"signed-in\") {\n const viewer = interaction.viewer(page.viewerId);\n const named = context.session?.grant.viewerId !== undefined;\n if (viewer.kind !== \"account\" && !named) {\n return refuseWith(\n \"MOSTRA_REMOTE_SIGN_IN_REQUIRED\",\n \"This page takes answers from signed-in viewers; sign in, then submit again. The draft is kept.\",\n 403,\n );\n }\n }\n // The server's rates (D165 item 13), then the operator's `limits`. The rates are taken first,\n // together or not at all (Fable review, 8), so an attempt past them never reaches the\n // operator, concurrent ones included; an attempt the operator then refuses gets its tokens\n // back (second Fable review, 2). Nothing is recorded past either, and the draft is kept.\n const limits = options.rateLimits;\n const wanted: { key: string; rate: NonNullable<typeof limits.perIpSubmissions> }[] = [];\n if (limits.perIpSubmissions) {\n wanted.push({\n key: `submit-ip:${options.clients.keyOf(context.client)}`,\n rate: limits.perIpSubmissions,\n });\n }\n if (limits.perLinkSubmissions && page.tokenId !== undefined) {\n wanted.push({ key: `submit-link:${page.tokenId}`, rate: limits.perLinkSubmissions });\n }\n const taken = options.rates.takeAll(wanted);\n if (!taken.ok) return rateRefusal(taken.retryAfterS);\n // The operator's `limits`: a refusal keeps the draft; no answer lets the submission through.\n const route = options.routeOf(page.artifactId);\n const verdict = await operator.limit({\n account: options.owner().account,\n home: options.homeId,\n artifact: page.artifactId,\n ...(route ? { routeId: route.id } : {}),\n operation: \"submit\",\n });\n const refused = limitRefusal(verdict);\n if (refused) options.rates.refundAll(wanted);\n return refused;\n },\n\n shellRoutes,\n };\n}\n\n/** A diagnostic for a hosted home this server won't serve now: suspended, or moving. */\nexport function homeUnavailable(why: \"suspended\" | \"moving\"): ReturnType<typeof createDiagnostic> {\n return why === \"suspended\"\n ? createDiagnostic(\"MOSTRA_REMOTE_HOME_SUSPENDED\", {\n message: \"This account's pages are suspended by the server's operator.\",\n })\n : createDiagnostic(\"MOSTRA_REMOTE_HOME_MOVING\", {\n message: \"This account's pages are moving to another machine; try again in a minute.\",\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 * Removing a hosted artifact (`ServerHandle.remove`, DATA_MODEL §7.5): an explicit deletion,\n * never part of another action. Everything of the artifact goes in one transaction of its home's\n * ledger: its own rows (every table with an `artifact_id`) and every row that references them,\n * followed through the schema's foreign keys, so no table needs listing here and a table a later\n * migration adds is covered by construction. The write-once triggers that keep versions, events,\n * submissions and tokens immutable are dropped for the transaction and created again in it, so the\n * only way past them is this one.\n */\nimport type { MigrationDb, SqlValue } from \"../ledger/index.ts\";\n\ninterface ForeignKey {\n readonly table: string;\n readonly from: string;\n readonly to: string;\n}\n\n/** What one removal deleted, table by table. */\nexport type Removed = Readonly<Record<string, number>>;\n\n/**\n * Deletes an artifact and everything referencing it from a home's ledger, in the caller's write\n * transaction. Answers the rows deleted per table.\n */\nexport function purgeArtifact(db: MigrationDb, artifactId: string): Removed {\n const tables = db\n .all<{ name: string }>(\n \"SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'\",\n )\n .map((row) => row.name);\n const columns = new Map<string, Set<string>>();\n const children = new Map<string, ForeignKey[]>();\n for (const table of tables) {\n columns.set(\n table,\n new Set(db.all<{ name: string }>(`PRAGMA table_info(\"${table}\")`).map((row) => row.name)),\n );\n for (const key of db.all<{ table: string; from: string; to: string | null }>(\n `PRAGMA foreign_key_list(\"${table}\")`,\n )) {\n const list = children.get(key.table) ?? [];\n list.push({ table, from: key.from, to: key.to ?? \"rowid\" });\n children.set(key.table, list);\n }\n }\n\n // Which rows of each table go: the artifact's own, then whatever references a doomed row.\n const where = new Map<string, { readonly sql: string; readonly params: SqlValue[] }>();\n for (const table of tables) {\n if (table === \"artifact\") where.set(table, { sql: \"id = ?\", params: [artifactId] });\n else if (columns.get(table)?.has(\"artifact_id\")) {\n where.set(table, { sql: \"artifact_id = ?\", params: [artifactId] });\n }\n }\n // A fixed point over the foreign keys: a table joins once a parent of it is doomed. Bounded,\n // since the schema's references form no long chain.\n let grew = true;\n for (let round = 0; grew && round < 16; round++) {\n grew = false;\n for (const [parent, list] of children) {\n const doomed = where.get(parent);\n if (!doomed) continue;\n for (const key of list) {\n const clause = {\n sql: `\"${key.from}\" IN (SELECT \"${key.to}\" FROM \"${parent}\" WHERE ${doomed.sql})`,\n params: doomed.params,\n };\n const existing = where.get(key.table);\n if (!existing) {\n where.set(key.table, clause);\n grew = true;\n } else if (\n !existing.sql.includes(`\"${key.from}\" IN (SELECT \"${key.to}\" FROM \"${parent}\"`)\n ) {\n where.set(key.table, {\n sql: `(${existing.sql}) OR (${clause.sql})`,\n params: [...existing.params, ...clause.params],\n });\n grew = true;\n }\n }\n }\n }\n\n const triggers = db.all<{ name: string; sql: string }>(\n `SELECT name, sql FROM sqlite_schema WHERE type = 'trigger' AND tbl_name IN (${[...where.keys()]\n .map(() => \"?\")\n .join(\", \")})`,\n ...where.keys(),\n );\n for (const trigger of triggers) db.exec(`DROP TRIGGER \"${trigger.name}\"`);\n db.exec(\"PRAGMA defer_foreign_keys = ON\");\n const removed: Record<string, number> = {};\n // Children first: a row is read through its parent's clause before the parent goes.\n const order = [...where.keys()].sort((a, b) => depth(b) - depth(a));\n function depth(table: string, seen = new Set<string>()): number {\n if (table === \"artifact\" || seen.has(table)) return 0;\n seen.add(table);\n let deepest = 0;\n for (const [parent, list] of children) {\n if (list.some((key) => key.table === table) && where.has(parent) && parent !== table) {\n deepest = Math.max(deepest, depth(parent, seen) + 1);\n }\n }\n return deepest;\n }\n // The clauses read the parents, so the rows to delete are fixed first, by rowid.\n const doomedRows = new Map<string, number[]>();\n for (const table of order) {\n const clause = where.get(table);\n if (!clause) continue;\n doomedRows.set(\n table,\n db\n // Named apart: SQLite answers a table's own column name for `rowid` when it has an\n // INTEGER PRIMARY KEY (`document.id`, `event.cursor`).\n .all<{ row: number }>(\n `SELECT rowid AS row FROM \"${table}\" WHERE ${clause.sql}`,\n ...clause.params,\n )\n .map((found) => found.row),\n );\n }\n for (const table of order) {\n const rows = doomedRows.get(table) ?? [];\n let count = 0;\n for (let index = 0; index < rows.length; index += 500) {\n const slice = rows.slice(index, index + 500);\n count += db.run(\n `DELETE FROM \"${table}\" WHERE rowid IN (${slice.map(() => \"?\").join(\", \")})`,\n ...slice,\n ).changes;\n }\n if (count > 0) removed[table] = count;\n }\n for (const trigger of triggers) db.exec(trigger.sql);\n // Nothing left pointing at what went: a row of another artifact naming a removed one would\n // fail the commit anyway; this names it.\n const dangling = db.all<{ table: string; parent: string }>(\"PRAGMA foreign_key_check\");\n if (dangling.length > 0) {\n throw new Error(\n `Removing ${artifactId} would leave ${dangling.length} rows dangling (${[\n ...new Set(dangling.map((row) => `${row.table} → ${row.parent}`)),\n ].join(\", \")}).`,\n );\n }\n return removed;\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, stat } 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 artifactPauseMethod,\n createDiagnostic,\n type HostedPushParams,\n type HostedPushResult,\n type HostedRoute,\n hostedPushMethod,\n hostedSubmissionMethod,\n type InstanceInfo,\n type PausedBy,\n RouteId,\n RpcError,\n remoteTokenMethod,\n viewUrlMethod,\n} from \"@mostra/protocol\";\nimport type { Addressing } from \"../addressing/index.ts\";\nimport { coverageMatcher, readFieldCoverage, readServerFunctions } from \"../builder/index.ts\";\nimport { type Faults, 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 { removeTree } from \"../platform/index.ts\";\nimport {\n handler,\n type MethodHandler,\n ProtocolServer,\n type Session,\n} 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 type { ClientAddresses, RateLimiter } from \"./clients.ts\";\nimport { rotateIncarnation } from \"./data.ts\";\nimport { createOperatorFeed, type OperatorFeed } from \"./feed.ts\";\nimport { type HomeOwner, type HostedPagesOptions, hostedPages } from \"./hosted-pages.ts\";\nimport type { Meter } from \"./metering.ts\";\nimport type { Operator } from \"./operator.ts\";\nimport { createHostedRelay } from \"./relay.ts\";\nimport { purgeArtifact } from \"./remove.ts\";\nimport type { Routing } from \"./routing.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 /**\n * The size a pending push of this home gives a client file it names as missing, or `undefined`\n * when none names it: an upload must bring exactly those bytes (Fable review of WP-30, 2).\n */\n wanted(sha256: string): number | undefined;\n /** Records a file this home uploaded (`PUT /files/<sha256>`, §18.2). */\n uploaded(sha256: string): void;\n /** Pauses or resumes an artifact as its owner or the operator (D165 item 14). */\n pause(\n artifactId: string,\n change: { readonly paused: boolean; readonly by: PausedBy; readonly reason?: string },\n ): { readonly paused: boolean; readonly by?: PausedBy };\n /** Quarantines an artifact, or one version of it, here only (D165 item 9). */\n quarantine(artifactId: string, versionId: string | undefined, reason: string): void;\n /** Ends a quarantine: the artifact's, or one version's. */\n release(artifactId: string, versionId: string | undefined): void;\n /** Revokes every live link of an artifact; answers how many were live. */\n revokeLinks(artifactId: string): number;\n /** Revokes one link; `false` when this home has no such link. */\n revokeLink(tokenId: string): boolean;\n /**\n * A personal link's URL and expiry, built from its token now (an invitation's, D168), or\n * `undefined` when it no longer works: revoked, expired, or made where it can't be shown again.\n */\n invitationLink(\n tokenId: string,\n ): { readonly url: string; readonly expiresAt?: string } | undefined;\n /**\n * Removes an artifact and everything of it from this home (`ServerHandle.remove`): its rows, its\n * version files no other version of the home names, and its route; its label is kept issued\n * forever, never served again (DATA_MODEL §7.5).\n */\n remove(artifactId: string): Promise<{ readonly rows: number }>;\n /**\n * The session of the account's default owner instance, while it is connected: where remote MCP's\n * authoring goes (D165 items 1b, 5). The newest session of the link is its own.\n */\n defaultOwnerSession(): number | undefined;\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 /** The test fault points (`MOSTRA_TEST_FAULTS`); none by default. */\n readonly faults?: Faults;\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 /** What the server lends every hosted home: its operator, client addresses and rates (WP-30). */\n readonly services?: HostedServices;\n}\n\n/** What the server lends every hosted home (WP-30). */\nexport interface HostedServices {\n readonly operator: Operator;\n readonly clients: ClientAddresses;\n readonly rates: RateLimiter;\n readonly rateLimits: HostedPagesOptions[\"rateLimits\"];\n /** Who owns a home, as its pages' sender line names them. */\n readonly owner: (homeId: string) => HomeOwner;\n readonly signInOffered: () => boolean;\n readonly madeWith?: { readonly href?: string } | undefined;\n /** The server's routing by exact `Host`: operator hosts, their frames and link hosts (D167). */\n readonly routing: Routing;\n /** The server's meter: views here, submissions through the operator feed. */\n readonly meter: Meter;\n /** Viewer sign-in on the authorization server (INTERFACES §18.4). */\n readonly signin?: HostedPagesOptions[\"signin\"];\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 faults = options.faults ?? noFaults;\n const { id, dir, ledger, directory, log } = options;\n const registry = await openRegistry({ home: dir, ledger });\n /** Pending pushes: version ID → each missing client file's SHA-256 and the size its listing gives. */\n const pending = new Map<string, Map<string, number>>();\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 // The owner is the account the home belongs to, signed in on its page (CO-07): it sees every\n // respondent and every present viewer, whatever the artifact's visibility.\n isOwner: (viewer) =>\n options.services !== undefined &&\n viewer.kind === \"account\" &&\n viewer.ref === options.services.owner(id).account,\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<{\n id: string;\n label: string;\n owner_link_id: string;\n removing_json: string | null;\n }>(\n \"SELECT id, label, owner_link_id, removing_json FROM artifact_route WHERE home_id = ? AND artifact_id = ?\",\n id,\n artifactId,\n );\n if (found?.removing_json != null) {\n throw refuse(\n \"MOSTRA_REMOTE_HOME_MOVING\",\n \"This artifact is being removed from the server; push it again once that's done.\",\n );\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 // A route being removed serves nothing (its removal finishes on the next call).\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 = ? AND removing_json IS NULL\",\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 = ? AND removing_json IS NULL\",\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 /** The host of one of this server's origins, or `undefined` for another scheme. */\n const hostOfOrigin = (origin: string): string | undefined =>\n origin.startsWith(`${options.scheme}://`) ? origin.slice(options.scheme.length + 3) : undefined;\n /** Whether a shell origin is this home's: a configured apex, or an operator host of it. */\n const servesShell = (origin: string): boolean => {\n const host = hostOfOrigin(origin);\n if (host === undefined) return false;\n return options.services\n ? options.services.routing.servesShell(id, host)\n : domains.includes(host);\n };\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,\n // Every hosted link is indexed in the directory, so the operator's `revokeLink` finds its home.\n onMinted: ({ tokenId, artifactId }) => {\n const route = routeOf(artifactId);\n if (!route) return;\n directory.write((db) =>\n db.run(\n \"INSERT OR IGNORE INTO hosted_token (token_id, home_id, route_id) VALUES (?, ?, ?)\",\n tokenId,\n id,\n route.id,\n ),\n );\n },\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 // `roster/add` asks the operator's `limits` for the personal links it mints (D168).\n linkLimit: (artifactId, count) => linkLimit(artifactId, count),\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,\n shellPath: (artifactId) => `/a/${routeOf(artifactId)?.id ?? artifactId}`,\n artifactOrigin: (artifactId, shellOrigin) => {\n const route = routeOf(artifactId);\n const host = hostOfOrigin(shellOrigin);\n if (!route || host === undefined) return undefined;\n const frameDomain = options.services\n ? options.services.routing.frameDomainOf(id, route.id, host)\n : domains.includes(host)\n ? host\n : undefined;\n return frameDomain === undefined ? undefined : originOf(`${route.label}.${frameDomain}`);\n },\n ...(options.services\n ? {\n // A new link goes on the operator's host for it when it names one that serves this\n // route (D167, `routing.linkHost`), else on the active domain.\n linkOrigin: async (artifactId: string) => {\n const services = options.services as HostedServices;\n const route = routeOf(artifactId);\n if (!route || !services.operator.has.linkHost) return undefined;\n const wanted = await services.operator.linkHost({\n account: services.owner(id).account,\n home: id,\n routeId: route.id,\n });\n if (wanted === null) return undefined;\n const host = await services.routing.linkHost(id, route.id, wanted);\n return host === undefined ? undefined : originOf(host);\n },\n frameAncestors: (artifactId: string, frameOrigin: string) => {\n const route = routeOf(artifactId);\n const host = hostOfOrigin(frameOrigin);\n if (!route || host === undefined) return \"\";\n const frameDomain = host.slice(host.indexOf(\".\") + 1);\n return (options.services as HostedServices).routing\n .ancestorsOf(id, route.id, frameDomain)\n .map(originOf)\n .join(\" \");\n },\n }\n : {}),\n ...(options.services\n ? hostedPages({\n homeId: id,\n ledger,\n interaction,\n capabilities,\n artifact: (artifactId) => registry.get({ artifactId }),\n routeOf,\n owner: () => (options.services as HostedServices).owner(id),\n signInOffered: options.services.signInOffered,\n operator: options.services.operator,\n clients: options.services.clients,\n rates: options.services.rates,\n rateLimits: options.services.rateLimits,\n madeWith: options.services.madeWith,\n ...(options.services.signin ? { signin: options.services.signin } : {}),\n viewed: (input) => metered(input.artifactId, input.viewerId),\n log,\n })\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 /**\n * Quarantines a route's artifact, or one version of it, in this home only (D165 item 9): its\n * links show the neutral \"under review\" page and its files are withheld; data is kept. An\n * identical version in another home is untouched, since the row is this home's.\n */\n const quarantine = (artifactId: string, versionId: string | undefined, reason: string): void => {\n ledger.write((db) =>\n db.run(\n `INSERT INTO quarantine (artifact_id, version_id, reason, at) VALUES (?, ?, ?, ?)\n ON CONFLICT (artifact_id, version_id) DO UPDATE SET reason = excluded.reason`,\n artifactId,\n versionId ?? \"\",\n reason.slice(0, 1_000),\n new Date().toISOString(),\n ),\n );\n log.info(\"server.quarantined\", { home: id, artifactId, versionId: versionId ?? null });\n };\n\n /**\n * New links on a hosted home under the operator's `limits` (`link`): `view/url`'s one, and the\n * personal links `roster/add` mints (D168); refused with the operator's words, and refused for now\n * when it doesn't answer, since a link creates something (D165 item 9).\n */\n const linkLimit = async (artifactId: string, quantity?: number): Promise<void> => {\n const services = options.services;\n if (!services) return;\n const route = routeOf(artifactId);\n const verdict = await services.operator.limit({\n account: services.owner(id).account,\n home: id,\n artifact: artifactId,\n ...(route ? { routeId: route.id } : {}),\n operation: \"link\",\n ...(quantity !== undefined ? { quantity } : {}),\n });\n if (verdict.allowed === \"unavailable\") {\n throw refuse(\n \"MOSTRA_REMOTE_OPERATOR_UNAVAILABLE\",\n \"The server's operator didn't answer in time; try minting the link again.\",\n );\n }\n if (verdict.allowed === false) throw refuse(\"MOSTRA_REMOTE_LIMIT_REACHED\", verdict.message);\n };\n const limitedLinks = (method: MethodHandler): MethodHandler => ({\n definition: method.definition,\n async handle(params, session) {\n const ref = (params as { artifact?: unknown }).artifact;\n await linkLimit(registry.get(canonicalRef(ref as never)).id);\n return method.handle(params, session);\n },\n });\n\n /**\n * A view for metering, under the viewer's monthly pseudonymous key (D167): the account for a\n * signed-in viewer, the viewer for a link minted with one, the route's key for anyone else.\n */\n const metered = (artifactId: string, viewerId: string): void => {\n const meter = options.services?.meter;\n if (!meter?.on) return;\n const viewer = ledger.read((db) =>\n db.get<{ kind: string; external_ref: string | null }>(\n \"SELECT kind, external_ref FROM viewer WHERE id = ?\",\n viewerId,\n ),\n );\n const subject =\n viewer?.kind === \"account\" || viewer?.kind === \"anonymous\"\n ? `${viewer.kind}:${viewer.external_ref ?? viewerId}`\n : `viewer:${id}:${viewerId}`;\n const route = routeOf(artifactId);\n meter.add(\"views\", {\n account: (options.services as HostedServices).owner(id).account,\n home: id,\n artifactId,\n ...(route ? { routeId: route.id } : {}),\n dimensions: { viewerKey: meter.viewerKey(subject) },\n });\n };\n\n /** The live links of an artifact, revoked; answers how many were live. */\n const revokeLinks = (artifactId: string): number => {\n const tokens = ledger.read((db) =>\n db\n .all<{ id: string }>(\n \"SELECT id FROM token WHERE artifact_id = ? AND revoked_at IS NULL\",\n artifactId,\n )\n .map((row) => row.id),\n );\n let revoked = 0;\n for (const tokenId of tokens) if (capabilities.revoke(tokenId) === \"revoked\") revoked += 1;\n return revoked;\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 services = options.services;\n // A first push hosts the artifact: the operator's `limits` judge it as a share, failing\n // closed when it doesn't answer (D165 item 9).\n if (services && routeOf(params.artifactId) === undefined) {\n const verdict = await services.operator.limit({\n account: services.owner(id).account,\n home: id,\n artifact: params.artifactId,\n operation: \"share\",\n });\n if (verdict.allowed === \"unavailable\") {\n throw refuse(\n \"MOSTRA_REMOTE_OPERATOR_UNAVAILABLE\",\n \"The server's operator didn't answer in time; the share is tried again later.\",\n );\n }\n if (verdict.allowed === false) throw refuse(\"MOSTRA_REMOTE_LIMIT_REACHED\", verdict.message);\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 // The sizes a listing gives are what the storage limit is asked with, so each is held to the\n // bytes: one file has one size, a file this home holds already has the size it has on disk, and\n // an upload brings exactly the size given (Fable review of WP-30, 2).\n const sizes = new Map<string, number>();\n for (const [path, , sha, size] of clientFiles) {\n if (!Number.isSafeInteger(size) || size < 0 || (sizes.get(sha) ?? size) !== size) {\n throw refuse(\n \"MOSTRA_HOME_INTEGRITY\",\n `The listing gives ${path} a size its bytes can't have.`,\n );\n }\n sizes.set(sha, size);\n }\n for (const [sha, size] of sizes) {\n const held = directory.read((db) =>\n db.get(\"SELECT 1 FROM home_file WHERE home_id = ? AND sha256 = ?\", id, sha),\n );\n if (held === undefined) continue;\n const onDisk = await stat(join(options.filesDir, sha)).then(\n (found) => found.size,\n () => undefined,\n );\n if (onDisk !== undefined && onDisk !== size) {\n throw refuse(\n \"MOSTRA_HOME_INTEGRITY\",\n \"The listing gives a held file another size than its bytes.\",\n );\n }\n }\n // The operator's `limits` on a push and the bytes it stores: refused for good with its words,\n // and refused for now (fail closed) when the operator doesn't answer (D165 item 9).\n if (services) {\n const owner = services.owner(id).account;\n for (const [operation, quantity] of [\n [\"version.push\", 1],\n [\"storage\", [...sizes.values()].reduce((sum, size) => sum + size, 0)],\n ] as const) {\n const verdict = await services.operator.limit({\n account: owner,\n home: id,\n artifact: params.artifactId,\n routeId: route.routeId,\n operation,\n quantity,\n });\n if (verdict.allowed === \"unavailable\") {\n throw refuse(\n \"MOSTRA_REMOTE_OPERATOR_UNAVAILABLE\",\n \"The server's operator didn't answer in time; the push is tried again later.\",\n );\n }\n if (verdict.allowed === false) throw refuse(\"MOSTRA_REMOTE_LIMIT_REACHED\", verdict.message);\n }\n }\n const missing = missingOf([...new Set(clientFiles.map(([, , sha]) => sha))]);\n if (missing.length > 0) {\n pending.set(\n version.versionId,\n new Map(missing.map((sha) => [sha, sizes.get(sha) as number])),\n );\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 // The operator's after-push hook reads the client files; its answer can quarantine the\n // version afterwards, never holding up serving it (D165 item 9).\n if (services?.operator.has.pushed) {\n const files = clientFiles.map(([path]) => path);\n const shaOf = new Map(clientFiles.map(([path, , sha]) => [path, sha]));\n services.operator.pushed(\n {\n routeId: route.routeId,\n label: route.label,\n artifactId: params.artifactId,\n home: id,\n versionId: version.versionId,\n manifest: manifest.data,\n files,\n read: async (path) => {\n const sha = shaOf.get(path);\n if (sha === undefined) throw new Error(`No client file ${path} in this version.`);\n return new Uint8Array(await readFile(join(options.filesDir, sha)));\n },\n },\n async (reason) => {\n quarantine(params.artifactId, version.versionId, reason);\n },\n );\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\n .methods()\n .map((method) =>\n method.definition.method === viewUrlMethod.method ? limitedLinks(method) : method,\n ),\n handler(artifactPauseMethod, (params) => {\n // The account's own instances pause and resume as the owner; only the operator, through\n // its handle, resumes an operator's pause (D165 item 14).\n const artifactId = registry.get(canonicalRef(params.artifact)).id;\n return interaction.pause(artifactId, {\n paused: params.paused,\n by: \"owner\",\n ...(params.reason !== undefined ? { reason: params.reason } : {}),\n });\n }),\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 // The operator's feed of this home's events, and its submissions for metering (§18.6).\n const feed: OperatorFeed | undefined = options.services\n ? createOperatorFeed({\n homeId: id,\n ledger,\n interaction,\n operator: options.services.operator,\n meter: options.services.meter,\n account: () => (options.services as HostedServices).owner(id).account,\n sender: () => {\n const owner = (options.services as HostedServices).owner(id);\n return {\n ...(owner.name !== undefined ? { name: owner.name } : {}),\n ...(owner.verifiedBy !== undefined ? { verifiedBy: owner.verifiedBy } : {}),\n };\n },\n routeOf,\n incarnation: () => incarnation,\n log,\n })\n : undefined;\n\n return {\n id,\n dir,\n ledger,\n registry,\n interaction,\n protocol,\n incarnation: () => incarnation,\n wanted: (sha) => {\n for (const files of pending.values()) {\n const size = files.get(sha);\n if (size !== undefined) return size;\n }\n return undefined;\n },\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 pause: (artifactId, change) => interaction.pause(artifactId, change),\n quarantine,\n release(artifactId, versionId) {\n ledger.write((db) =>\n db.run(\n versionId === undefined\n ? \"DELETE FROM quarantine WHERE artifact_id = ?\"\n : \"DELETE FROM quarantine WHERE artifact_id = ? AND version_id = ?\",\n ...(versionId === undefined ? [artifactId] : [artifactId, versionId]),\n ),\n );\n },\n revokeLinks,\n revokeLink: (tokenId) => capabilities.revoke(tokenId) !== \"unknown\",\n invitationLink(tokenId) {\n const grant = capabilities.grant(tokenId);\n if (!grant?.live) return undefined;\n const url = gateway.reveal(tokenId);\n if (url === undefined) return undefined;\n return { url, ...(grant.expiresAt !== undefined ? { expiresAt: grant.expiresAt } : {}) };\n },\n async remove(artifactId) {\n /** The client files a version's listing names. */\n const clientFilesOf = async (versionId: string): Promise<string[]> => {\n try {\n const listing = JSON.parse(\n await readFile(join(registry.store.versionDir(versionId), \"listing.json\"), \"utf8\"),\n ) as [string, boolean, string, number][];\n return listing.filter(([path]) => path.startsWith(\"client/\")).map(([, , sha]) => sha);\n } catch {\n return [];\n }\n };\n // The plan is recorded in the directory before anything goes, so a removal cut off between\n // the two databases is finished by the next call, from the same plan (Fable review, 4).\n const recorded = directory.read(\n (db) =>\n db.get<{ removing_json: string | null }>(\n \"SELECT removing_json FROM artifact_route WHERE home_id = ? AND artifact_id = ?\",\n id,\n artifactId,\n )?.removing_json,\n );\n let plan: { readonly versions: string[]; readonly going: string[] };\n if (recorded != null) plan = JSON.parse(recorded) as typeof plan;\n else {\n const versions = registry.get({ artifactId }).versions.map((version) => version.id);\n const files = new Set<string>();\n for (const versionId of versions)\n for (const sha of await clientFilesOf(versionId)) files.add(sha);\n plan = { versions, going: [...files] };\n directory.write((db) =>\n db.run(\n \"UPDATE artifact_route SET removing_json = ? WHERE home_id = ? AND artifact_id = ?\",\n JSON.stringify(plan),\n id,\n artifactId,\n ),\n );\n }\n const versions = plan.versions;\n const going = new Set(plan.going);\n if (registry.list({}).some((summary) => summary.id === artifactId)) revokeLinks(artifactId);\n const removed = ledger.removal((db) => purgeArtifact(db, artifactId));\n // A test cuts the removal off here, between its two databases (`remove:after-purge`).\n faults.at(\"remove:after-purge\");\n // Files another version of this home still names stay this home's.\n const kept = new Set<string>();\n for (const other of registry.list({})) {\n for (const version of registry.get({ artifactId: other.id }).versions) {\n for (const sha of await clientFilesOf(version.id)) kept.add(sha);\n }\n }\n const route = directory.read((db) =>\n db.get<{ id: string }>(\n \"SELECT id FROM artifact_route WHERE home_id = ? AND artifact_id = ?\",\n id,\n artifactId,\n ),\n );\n directory.write((db) => {\n for (const sha of going) {\n if (kept.has(sha)) continue;\n if (\n db.run(\"DELETE FROM home_file WHERE home_id = ? AND sha256 = ?\", id, sha).changes > 0\n ) {\n db.run(\n `UPDATE file_ref SET homes = homes - 1,\n unreferenced_at = CASE WHEN homes - 1 = 0 THEN ? ELSE NULL END\n WHERE sha256 = ?`,\n new Date().toISOString(),\n sha,\n );\n }\n }\n if (route) {\n db.run(\"DELETE FROM hosted_token WHERE route_id = ?\", route.id);\n // The route goes; its label stays in `label_issued`, never issued again.\n db.run(\"DELETE FROM artifact_route WHERE id = ?\", route.id);\n }\n });\n for (const versionId of versions) {\n await removeTree(registry.store.versionDir(versionId)).catch((error: unknown) =>\n log.warn(\"server.remove_files_failed\", { versionId, error }),\n );\n }\n const rows = Object.values(removed).reduce((sum, count) => sum + count, 0);\n log.info(\"server.artifact_removed\", { home: id, artifactId, rows });\n return { rows };\n },\n defaultOwnerSession() {\n const link = directory.read(\n (db) =>\n db.get<{ id: string }>(\n \"SELECT id FROM instance_link WHERE home_id = ? AND is_default = 1 AND revoked_at IS NULL\",\n id,\n )?.id,\n );\n if (link === undefined) return undefined;\n return protocol\n .registrants(\"relay\")\n .filter((entry) => entry.owner === link)\n .at(-1)?.session;\n },\n busy: () => protocol.connections > 0 || bus.activeViews() > 0 || relay.busy(),\n serve,\n async stop() {\n feed?.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 MCP server (INTERFACES §18.8, MC-04, D165 items 5, 10): `@mostra/mcp`'s tools over\n * Streamable HTTP at `<apiOrigin>/mcp`, statelessly, behind the authorization server. Each request\n * is built for the account its token names:\n *\n * - **the instance** reads and writes the account's hosted home through a protocol session of its\n * own in this process, as any host would (invariant 11); authoring (`artifact/create`, `verify`,\n * `publish`) goes to the account's default owner instance through `port/relay.author`, and\n * answers `MOSTRA_REMOTE_NO_INSTANCE` while none is connected;\n * - **the workspace** is the default owner instance's own, reached the same way;\n * - **the docs** are the reference this build carries. There is no browser.\n *\n * Each call is counted (`mcp.calls`, with the client's `clientInfo` name, D148) and asked of the\n * operator's `limits` (`mcp.call`) first; a refusal answers the operator's code.\n */\nimport { existsSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { join } from \"node:path\";\nimport {\n createAuthorizedEndpoint,\n fileDocs,\n type McpAuthorization,\n type McpDocs,\n type McpInstance,\n type McpWorkspace,\n type WorkspaceFile,\n} from \"@mostra/mcp\";\nimport {\n type ArtifactRef,\n createDiagnostic,\n type MethodDefinition,\n type PortRelayAuthorParams,\n portRelayAuthorMethod,\n type RelayAuthorMethod,\n RpcError,\n viewDefaultMethod,\n} from \"@mostra/protocol\";\nimport type { Log } from \"../log.ts\";\nimport { runtimeRoot } from \"../platform/index.ts\";\nimport { attachInProcess, type SocketClient } from \"../protocol-server/index.ts\";\nimport type { Authenticated } from \"./auth.ts\";\nimport type { HostedHome } from \"./hosted.ts\";\nimport type { Meter } from \"./metering.ts\";\nimport type { Operator } from \"./operator.ts\";\n\n/** How long a relayed authoring step may take: verify and publish can take minutes. */\nconst AUTHOR_TIMEOUT_MS = 10 * 60_000;\n/** How long a workspace step may take. */\nconst WORKSPACE_TIMEOUT_MS = 30_000;\n/** How long a relayed publish waits for its version to arrive here before answering its link. */\nconst PUSH_WAIT_MS = 120_000;\n/** The largest request body read. */\nconst MAX_BODY_BYTES = 16 * 1024 * 1024;\n\n/** The methods that run on the owner instance, never on the hosted home. */\nconst AUTHORING = new Set<string>([\"artifact/create\", \"artifact/verify\", \"artifact/publish\"]);\n\n/** What the endpoint needs of the server. */\nexport interface RemoteMcpOptions {\n readonly apiOrigin: string;\n readonly version: string;\n readonly docs: McpDocs;\n readonly log: Log;\n readonly operator: Operator;\n readonly meter: Meter | undefined;\n /** The account's hosted home, opened on demand. */\n readonly home: (homeId: string) => Promise<HostedHome>;\n /** The account's hosted home, made when it has none yet (an account that signed in only here). */\n readonly ensureHome: (accountId: string) => string;\n}\n\n/** The remote MCP endpoint. */\nexport interface RemoteMcp {\n /** Serves `/mcp` for a request whose token names `who`, for the resource `/mcp`. */\n handle(request: IncomingMessage, response: ServerResponse, who: Authenticated): Promise<void>;\n close(): Promise<void>;\n}\n\nfunction noInstance(): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_REMOTE_NO_INSTANCE\", {\n message:\n \"No Mostra instance of this account is connected to the server, and building and verifying run there. Start Mostra on the linked machine (mostra daemon start), or link one with mostra login <server> --default.\",\n }),\n );\n}\n\n/**\n * The reference this runtime carries: its build's copy (`dist/reference`, `dist/skill`), or the\n * repository's when it runs from source.\n */\nexport function serverDocs(): McpDocs {\n const root = runtimeRoot();\n const built = join(root, \"dist\", \"reference\");\n return existsSync(built)\n ? fileDocs({ referenceDir: built, skillDir: join(root, \"dist\", \"skill\") })\n : fileDocs({\n referenceDir: join(root, \"..\", \"..\", \"docs\", \"reference\"),\n skillDir: join(root, \"..\", \"..\", \"skills\", \"mostra\"),\n });\n}\n\n/** Builds the endpoint. */\nexport function createRemoteMcp(options: RemoteMcpOptions): RemoteMcp {\n const { log } = options;\n\n /** The default owner instance's session on a home: the account's chat-host authoring goes there. */\n const authorOn = (home: HostedHome) => {\n const call = async (method: RelayAuthorMethod, params: unknown, timeoutMs: number) => {\n const session = home.defaultOwnerSession();\n if (session === undefined) throw noInstance();\n const answer = await home.protocol.callSession(\n session,\n portRelayAuthorMethod.method,\n { method, params } satisfies PortRelayAuthorParams,\n timeoutMs,\n );\n return answer as unknown;\n };\n return call;\n };\n\n const endpoint = createAuthorizedEndpoint(\n (authorization: McpAuthorization) => {\n const subject = authorization.subject as {\n readonly home: HostedHome;\n readonly client: SocketClient;\n readonly account: string;\n readonly root: string;\n };\n const author = authorOn(subject.home);\n // A directory names an artifact on the owner's machine: the owner says which it is.\n const resolveRef = async (ref: ArtifactRef): Promise<ArtifactRef> => {\n if (!(\"path\" in ref)) return ref;\n const found = (await author(\"artifact/get\", { artifact: ref }, WORKSPACE_TIMEOUT_MS)) as {\n id: string;\n };\n return { artifactId: found.id };\n };\n const instance: McpInstance = {\n async call<P, R>(method: MethodDefinition<P, R>, params: P): Promise<R> {\n if (method.method === \"artifact/publish\") {\n // Published and hosted on the owner; the answer's link is the hosted default link,\n // once the version has arrived here (D165 item 5).\n const receipt = (await author(\"artifact/publish\", params, AUTHOR_TIMEOUT_MS)) as {\n artifactId: string;\n versionId: string;\n };\n const until = Date.now() + PUSH_WAIT_MS;\n while (!subject.home.registry.hasVersion(receipt.versionId) && Date.now() < until) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n const link = await subject.client.peer.call(viewDefaultMethod, {\n artifact: { artifactId: receipt.artifactId },\n });\n return { ...receipt, url: link.url, tokenId: link.tokenId } as R;\n }\n if (AUTHORING.has(method.method)) {\n return (await author(\n method.method as RelayAuthorMethod,\n params,\n AUTHOR_TIMEOUT_MS,\n )) as R;\n }\n const value = params as { artifact?: ArtifactRef };\n const sent =\n value.artifact !== undefined\n ? ({ ...value, artifact: await resolveRef(value.artifact) } as P)\n : params;\n return (await subject.client.peer.call(method, sent)) as R;\n },\n // Progress of a relayed verify isn't streamed back; the verdict arrives whole.\n onProgress: () => () => undefined,\n };\n const workspace: McpWorkspace = {\n // The owner's workspace root, as the owner said it (its paths are the owner's).\n root: subject.root,\n // The owner resolves and checks every path itself: a relative one inside its workspace.\n resolveDir: (dir) => dir,\n allocateDir: async (title) =>\n (await author(\"workspace/allocate\", { title }, WORKSPACE_TIMEOUT_MS)) as string,\n async read(dir, path) {\n const answer = (await author(\"workspace/read\", { dir, path }, WORKSPACE_TIMEOUT_MS)) as {\n content?: string;\n };\n return answer.content === undefined ? undefined : Buffer.from(answer.content, \"base64\");\n },\n async apply(dir, changes) {\n return (await author(\n \"workspace/apply\",\n {\n dir,\n write: changes.write.map((file: WorkspaceFile) => ({\n path: file.path,\n content: Buffer.from(file.content).toString(\"base64\"),\n })),\n delete: changes.delete,\n },\n WORKSPACE_TIMEOUT_MS,\n )) as { written: string[]; deleted: string[] };\n },\n };\n return {\n instance,\n workspace,\n docs: options.docs,\n version: options.version,\n readScreenshot: async (path) => {\n const answer = (await author(\"verify/screenshot\", { path }, WORKSPACE_TIMEOUT_MS)) as {\n png?: string;\n };\n if (answer.png === undefined) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ARTIFACT_PATH_INVALID\", {\n message: \"That screenshot isn't one of the owner instance's verify runs.\",\n }),\n );\n }\n return Buffer.from(answer.png, \"base64\");\n },\n onClient: (client) => {\n options.meter?.add(\"mcp.calls\", {\n account: subject.account,\n home: subject.home.id,\n dimensions: { client: client.name.slice(0, 64) },\n });\n },\n };\n },\n { onError: (error) => log.warn(\"mcp.error\", { message: error.message }) },\n );\n\n return {\n async handle(request, response, who) {\n const homeId = who.homeId !== \"\" ? who.homeId : options.ensureHome(who.accountId);\n const verdict = await options.operator.limit({\n account: who.accountId,\n home: homeId,\n operation: \"mcp.call\",\n });\n if (verdict.allowed === false || verdict.allowed === \"unavailable\") {\n const diagnostic =\n verdict.allowed === false\n ? createDiagnostic(\"MOSTRA_REMOTE_LIMIT_REACHED\", { message: verdict.message })\n : createDiagnostic(\"MOSTRA_REMOTE_OPERATOR_UNAVAILABLE\", {\n message: \"The server's operator didn't answer in time; try again shortly.\",\n });\n const text = JSON.stringify({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32000, message: diagnostic.message, data: diagnostic },\n });\n response.writeHead(verdict.allowed === false ? 403 : 503, {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n ...(verdict.allowed === false && verdict.retryAfterMs !== undefined\n ? { \"retry-after\": String(Math.ceil(verdict.retryAfterMs / 1000)) }\n : {}),\n });\n response.end(text);\n return;\n }\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n size += (chunk as Buffer).length;\n if (size > MAX_BODY_BYTES) {\n response.writeHead(413, { \"content-type\": \"application/json\" });\n response.end(\n JSON.stringify({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32600, message: \"The request is too large.\" },\n }),\n );\n return;\n }\n chunks.push(chunk as Buffer);\n }\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (value === undefined || name === \"host\" || name === \"cookie\") continue;\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n const web = new Request(`${options.apiOrigin}${request.url ?? \"/mcp\"}`, {\n method: request.method ?? \"POST\",\n headers,\n ...(request.method === \"POST\" ? { body: Buffer.concat(chunks) } : {}),\n });\n const home = await options.home(homeId);\n // The owner's workspace root, when an owner instance is connected to say it.\n let root = \"the workspace of this account's Mostra instance\";\n if (home.defaultOwnerSession() !== undefined) {\n const found = await authorOn(home)(\"workspace/root\", {}, WORKSPACE_TIMEOUT_MS).catch(\n () => undefined,\n );\n if (typeof found === \"string\") root = found;\n }\n const { client } = await attachInProcess(\n home.protocol,\n { name: \"mostra-remote-mcp\", version: options.version },\n { accountId: who.accountId, grantId: who.grantId, homeId, linkId: undefined },\n );\n try {\n const answer = await endpoint.fetch(web, {\n token: \"\",\n clientId: who.clientId,\n scopes: [\"mostra\"],\n expiresAt: Math.floor(who.expiresAt / 1000),\n resource: `${options.apiOrigin}/mcp`,\n subject: { home, client, account: who.accountId, root },\n });\n const out: Record<string, string> = {};\n answer.headers.forEach((value, name) => {\n out[name] = value;\n });\n response.writeHead(answer.status, out);\n if (answer.body) {\n for await (const chunk of answer.body as unknown as AsyncIterable<Uint8Array>) {\n response.write(chunk);\n }\n }\n response.end();\n } finally {\n client.close();\n }\n },\n close: () => endpoint.close(),\n };\n}\n","/**\n * Metering for an operator (INTERFACES §18.6, D165 item 9): counters kept in memory for a window,\n * then handed to the operator's `metering.record` as one batch with a stable `batchId`, through\n * the durable outbound queue, so a batch is delivered at least once across restarts. With no\n * metering port nothing is counted.\n *\n * Views carry `viewerKey`, a monthly pseudonymous key: an HMAC of the viewer's subject under a key\n * the server makes for each month (`<data>/keys/metering-<YYYY-MM>`), so an operator can count\n * monthly viewers without learning who they are or matching them across months. The subject is\n * the account for a signed-in viewer, the viewer for a link minted with one, and the route's\n * anonymous key for anyone else (D167): no route ever learns another's key.\n */\nimport { createHmac, randomBytes, randomUUID } from \"node:crypto\";\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { MeterCounter, MeterName } from \"@mostra/protocol/operator\";\nimport type { Log } from \"../log.ts\";\nimport type { Operator } from \"./operator.ts\";\n\n/** How long one batch's window lasts. */\nconst WINDOW_MS = 60_000;\n\n/** What one counter is counted under, besides its name. */\nexport interface MeterScope {\n readonly account: string;\n readonly home?: string | undefined;\n readonly artifactId?: string | undefined;\n readonly routeId?: string | undefined;\n readonly dimensions?: Readonly<Record<string, string>> | undefined;\n}\n\n/** The server's meter. */\nexport interface Meter {\n /** Whether anything is counted (an operator implements `metering`). */\n readonly on: boolean;\n /** Adds `value` to a counter. */\n add(name: MeterName, scope: MeterScope, value?: number): void;\n /** The month's pseudonymous key of a viewer's subject, for `views`. */\n viewerKey(subject: string): string;\n /** Hands the window's counters to the outbound queue now. */\n flush(): void;\n stop(): void;\n}\n\n/** Options for {@link createMeter}. */\nexport interface MeterOptions {\n readonly operator: Operator;\n /** `<data>/keys`, where the monthly keys live (mode 0700). */\n readonly keysDir: string;\n readonly log: Log;\n readonly now?: () => number;\n /** The window, shortened by tests. */\n readonly windowMs?: number;\n /** Seconds each open home was active, added at every window. */\n readonly activeHomes?: () => readonly { readonly home: string; readonly account: string }[];\n}\n\n/** Creates the meter. */\nexport function createMeter(options: MeterOptions): Meter {\n const on = options.operator.has.metering;\n const now = options.now ?? (() => Date.now());\n const windowMs = options.windowMs ?? WINDOW_MS;\n const counters = new Map<string, { counter: MeterCounter; value: number }>();\n let from = now();\n const monthKeys = new Map<string, Buffer>();\n\n const monthKey = (): Buffer => {\n const month = new Date(now()).toISOString().slice(0, 7);\n let key = monthKeys.get(month);\n if (key) return key;\n const file = join(options.keysDir, `metering-${month}`);\n try {\n key = readFileSync(file);\n } catch {\n key = randomBytes(32);\n try {\n writeFileSync(file, key, { mode: 0o600, flag: \"wx\" });\n } catch {\n // Another process wrote it first: its key is the month's.\n key = readFileSync(file);\n }\n }\n monthKeys.clear();\n monthKeys.set(month, key);\n return key;\n };\n\n const flush = (): void => {\n if (!on) return;\n const to = now();\n const seconds = Math.max(0, Math.round((to - from) / 1000));\n if (seconds > 0) {\n for (const active of options.activeHomes?.() ?? []) {\n add(\"home.activeSeconds\", { account: active.account, home: active.home }, seconds);\n }\n }\n if (counters.size === 0) {\n from = to;\n return;\n }\n const batch = {\n batchId: randomUUID(),\n from: new Date(from).toISOString(),\n to: new Date(to).toISOString(),\n counters: [...counters.values()].map(({ counter, value }) => ({ ...counter, value })),\n };\n counters.clear();\n from = to;\n options.operator.enqueue({ port: \"metering\", batch });\n };\n\n const add = (name: MeterName, scope: MeterScope, value = 1): void => {\n if (!on || scope.account === \"\" || value <= 0) return;\n const key = JSON.stringify([\n name,\n scope.account,\n scope.home ?? null,\n scope.artifactId ?? null,\n scope.routeId ?? null,\n scope.dimensions ?? null,\n ]);\n const found = counters.get(key);\n if (found) {\n found.value += value;\n return;\n }\n counters.set(key, {\n counter: {\n name,\n account: scope.account,\n ...(scope.home !== undefined ? { home: scope.home } : {}),\n ...(scope.artifactId !== undefined ? { artifactId: scope.artifactId } : {}),\n ...(scope.routeId !== undefined ? { routeId: scope.routeId } : {}),\n value: 0,\n ...(scope.dimensions !== undefined ? { dimensions: { ...scope.dimensions } } : {}),\n },\n value,\n });\n };\n\n const timer = on ? setInterval(flush, windowMs) : undefined;\n timer?.unref();\n if (on) options.log.info(\"meter.started\", { windowMs });\n\n return {\n on,\n add,\n viewerKey: (subject) =>\n createHmac(\"sha256\", monthKey()).update(`mostra viewer ${subject}`).digest(\"base64url\"),\n flush,\n stop() {\n if (timer) clearInterval(timer);\n flush();\n },\n };\n}\n","/**\n * The remote server's operator boundary at run time (ARCHITECTURE §15.10, INTERFACES §18.6, D165\n * items 9, 11): the operator module a configuration names, loaded in process, and every call into\n * it. Each call has its time limit and its answer is checked against `@mostra/protocol/operator`'s\n * schemas; a call that throws, times out or answers what the schema refuses counts as no answer,\n * and each port's caller says what no answer means (`limits`: operations that create fail closed,\n * viewer input proceeds; `routing`: nothing is served; `policy`: nothing is added). Outbound\n * deliveries (`metering`, `events`, `invitations`) are kept in the directory's `outbound` table and\n * retried with backoff until the operator takes them, at least once and idempotent by their IDs,\n * across restarts. An invitation is kept by its link's token and handed over with the link built\n * then, so the queue never holds a capability secret (D168).\n *\n * Without an operator module every port is its no-op default, and this module does nothing but\n * answer \"allowed\".\n */\nimport { pathToFileURL } from \"node:url\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport {\n AccountResolution,\n AuthenticatedCredential,\n type ChatHostPolicy,\n ChatHostPolicy as ChatHostPolicySchema,\n type CredentialResource,\n type IdentityProvider,\n type Invitation,\n LimitAnswer,\n type LimitQuery,\n LinkHost,\n LinkPolicy,\n type LinkQuery,\n type MeterBatch,\n OPERATOR_TIME_LIMITS,\n type OperatorEvent,\n type OperatorPorts,\n PushedAnswer,\n type PushedVersion,\n RoutingAnswer,\n type ServerHandle,\n type SignInIdentity,\n} from \"@mostra/protocol/operator\";\nimport type * as z from \"zod\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\n\n/** What `limits` decided: allowed, refused with the operator's words, or no answer in time. */\nexport type LimitVerdict =\n | { readonly allowed: true }\n | {\n readonly allowed: false;\n readonly code: string;\n readonly message: string;\n readonly retryAfterMs?: number;\n }\n | { readonly allowed: \"unavailable\" };\n\n/** What `accounts.resolve` decided, or that the server's own accounts decide (no port). */\nexport type ResolveVerdict = AccountResolution | { readonly default: true } | \"unavailable\";\n\n/** The operator module at run time. */\nexport interface Operator {\n /** Which ports the module implements. */\n readonly has: {\n readonly limits: boolean;\n readonly metering: boolean;\n readonly accounts: boolean;\n readonly authenticate: boolean;\n readonly status: boolean;\n readonly abuse: boolean;\n readonly pushed: boolean;\n readonly policy: boolean;\n readonly routing: boolean;\n readonly linkHost: boolean;\n readonly events: boolean;\n readonly identity: boolean;\n readonly invitations: boolean;\n };\n limit(q: LimitQuery): Promise<LimitVerdict>;\n linkPolicy(q: LinkQuery): Promise<LinkPolicy>;\n chatHost(client: { name: string; redirectHost?: string }): Promise<ChatHostPolicy | null>;\n /** The operator's answer for a host the server doesn't serve itself, or `unavailable`. */\n route(host: string): Promise<RoutingAnswer | \"unavailable\">;\n /** The shell host a new link of a route is minted on; `null` for the active domain. */\n linkHost(q: { account: string; home: string; routeId: string }): Promise<string | null>;\n /** The identity providers the module supplies now (none on failure). */\n providers(): Promise<readonly IdentityProvider[]>;\n resolve(identity: SignInIdentity, steps: number): Promise<ResolveVerdict>;\n /** An operator-issued credential, or `null` (unknown, refused, or no answer). */\n authenticate(\n bearer: string,\n resource: CredentialResource,\n ): Promise<z.infer<typeof AuthenticatedCredential>>;\n /** An account's status as the operator says, or `undefined` with no answer. */\n status(account: string): Promise<\"active\" | \"suspended\" | undefined>;\n report(r: Parameters<NonNullable<OperatorPorts[\"abuse\"]>[\"report\"]>[0]): Promise<void>;\n /** The after-push hook: never blocks serving; its answer may quarantine the version after. */\n pushed(v: PushedVersion, quarantine: (reason: string) => Promise<void>): void;\n /** Keeps an outbound delivery durably, to deliver at least once (INTERFACES §18.6). */\n enqueue(\n item:\n | { readonly port: \"events\"; readonly event: OperatorEvent }\n | { readonly port: \"metering\"; readonly batch: MeterBatch }\n | { readonly port: \"invitations\"; readonly invitation: QueuedInvitation },\n ): void;\n /** Delivers what waits now (tests; the dispatcher does it on its own). */\n flush(): Promise<void>;\n stop(): void;\n}\n\n/** Options for {@link loadOperator}. */\nexport interface OperatorOptions {\n /** The module's path (`operator` in the configuration), or `undefined` for none. */\n readonly path: string | undefined;\n readonly handle: ServerHandle;\n readonly directory: Ledger;\n readonly log: Log;\n readonly now?: () => number;\n /** How often the outbound dispatcher looks for work; tests shorten it. */\n readonly dispatchMs?: number;\n /**\n * A personal link's URL, built from its token when an invitation is handed over (D168), or\n * `undefined` when the link no longer works (revoked, expired, replaced): the queue never holds\n * the URL, whose fragment is the link's secret.\n */\n readonly invitationLink?: (\n home: string,\n tokenId: string,\n ) => Promise<{ readonly url: string; readonly expiresAt?: string } | undefined>;\n}\n\n/** An invitation as the outbound queue keeps it: its link's token, never the link (D168). */\nexport type QueuedInvitation = Omit<Invitation, \"url\" | \"expiresAt\"> & { readonly tokenId: string };\n\nfunction configInvalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_REMOTE_CONFIG_INVALID\", { message }));\n}\n\nclass Timeout extends Error {}\n\n/** Races a call against its time limit. */\nasync function within<T>(limitMs: number, call: () => T | Promise<T>): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n Promise.resolve().then(call),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Timeout(`no answer within ${limitMs} ms`)), limitMs);\n timer.unref();\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/** The longest an outbound delivery waits between attempts. */\nconst OUTBOUND_MAX_BACKOFF_MS = 5 * 60_000;\n\n/**\n * Loads the operator module a configuration names and starts its outbound dispatcher. A module\n * that can't be loaded, or whose default export isn't a function, stops the server before it\n * serves anything (`MOSTRA_REMOTE_CONFIG_INVALID`, naming `operator`).\n */\nexport async function loadOperator(options: OperatorOptions): Promise<Operator> {\n const { log, directory } = options;\n const now = options.now ?? (() => Date.now());\n let ports: OperatorPorts = {};\n if (options.path !== undefined) {\n let loaded: { default?: unknown };\n try {\n loaded = (await import(pathToFileURL(options.path).href)) as { default?: unknown };\n } catch (error) {\n throw configInvalid(\n `The configuration key \\`operator\\` names a module that can't be loaded: ${(error as Error).message}.`,\n );\n }\n if (typeof loaded.default !== \"function\") {\n throw configInvalid(\n \"The configuration key `operator` names a module whose default export isn't a function of the server's handle.\",\n );\n }\n try {\n ports = ((await (loaded.default as (server: ServerHandle) => unknown)(options.handle)) ??\n {}) as OperatorPorts;\n } catch (error) {\n throw configInvalid(\n `The operator module's default export failed: ${(error as Error).message}.`,\n );\n }\n if (typeof ports !== \"object\") {\n throw configInvalid(\"The operator module's default export didn't return its ports.\");\n }\n log.info(\"operator.loaded\", {\n ports: Object.keys(ports).filter((key) => (ports as Record<string, unknown>)[key]),\n });\n }\n\n /** One call into the module: time-limited, its answer checked; `undefined` for no answer. */\n const ask = async <T>(\n port: string,\n limitMs: number,\n schema: z.ZodType<T>,\n call: () => unknown,\n ): Promise<{ readonly value: T } | undefined> => {\n try {\n const answer = await within(limitMs, call);\n const checked = schema.safeParse(answer);\n if (!checked.success) {\n log.warn(\"operator.answer_refused\", {\n port,\n issue: checked.error.issues[0]?.message ?? \"invalid\",\n });\n return undefined;\n }\n return { value: checked.data };\n } catch (error) {\n log.warn(\"operator.no_answer\", {\n port,\n why: error instanceof Timeout ? \"timeout\" : \"error\",\n message: (error as Error).message,\n });\n return undefined;\n }\n };\n\n /** Answers the operator allowed to keep, by key, until their time. */\n const cache = new Map<string, { readonly value: unknown; readonly until: number }>();\n const cached = <T>(key: string): T | undefined => {\n const hit = cache.get(key);\n if (!hit) return undefined;\n if (hit.until <= now()) {\n cache.delete(key);\n return undefined;\n }\n return hit.value as T;\n };\n const keep = (key: string, value: unknown, forMs: number | undefined): void => {\n if (forMs === undefined || forMs <= 0) return;\n if (cache.size >= 10_000) cache.delete(cache.keys().next().value as string);\n cache.set(key, { value, until: now() + forMs });\n };\n\n // ── outbound ────────────────────────────────────────────────────────────────────────────\n\n let dispatching: Promise<void> | undefined;\n const deliverOne = async (row: {\n id: string;\n port: string;\n payload_json: string;\n attempts: number;\n }): Promise<void> => {\n const payload = JSON.parse(row.payload_json) as unknown;\n try {\n if (row.port === \"invitations\") {\n const { tokenId, ...invitation } = payload as QueuedInvitation;\n // Building the link opens its home: bounded like the hand-over, so a home that hangs\n // can't stall the dispatcher (Opus review 4).\n const link = await within(OPERATOR_TIME_LIMITS.outbound, () =>\n options.invitationLink?.(invitation.home, tokenId),\n );\n if (link === undefined) {\n // The link stopped working before it was handed over: inviting with it would mail a\n // dead link, and a later one gets an invitation of its own.\n directory.write((db) => db.run(\"DELETE FROM outbound WHERE id = ?\", row.id));\n log.info(\"operator.invitation_dropped\", { invitationId: invitation.invitationId });\n return;\n }\n await within(OPERATOR_TIME_LIMITS.outbound, () =>\n ports.invitations?.send({\n ...invitation,\n url: link.url,\n ...(link.expiresAt !== undefined ? { expiresAt: link.expiresAt } : {}),\n }),\n );\n } else {\n await within(OPERATOR_TIME_LIMITS.outbound, () =>\n row.port === \"events\"\n ? ports.events?.deliver(payload as OperatorEvent)\n : ports.metering?.record(payload as MeterBatch),\n );\n }\n directory.write((db) => db.run(\"DELETE FROM outbound WHERE id = ?\", row.id));\n } catch (error) {\n const delay = Math.min(OUTBOUND_MAX_BACKOFF_MS, 1_000 * 2 ** Math.min(row.attempts, 20));\n directory.write((db) =>\n db.run(\n \"UPDATE outbound SET attempts = attempts + 1, next_attempt_at = ? WHERE id = ?\",\n new Date(now() + delay).toISOString(),\n row.id,\n ),\n );\n log.warn(\"operator.outbound_failed\", {\n port: row.port,\n attempts: row.attempts + 1,\n message: (error as Error).message,\n });\n }\n };\n const dispatch = (): Promise<void> => {\n dispatching ??= (async () => {\n // Yield first: a turn that found nothing would otherwise end, and clear `dispatching`,\n // before `??=` stored it, leaving a finished turn registered for ever (WP-29 met the same).\n await Promise.resolve();\n try {\n for (;;) {\n // The oldest rows of each ordered port, due or not: a port whose oldest delivery waits\n // for its retry waits whole, so an operator sees a home's events in the order they\n // happened. Invitations have no order: each waits for its own retry and none holds\n // another back, so one home that can't build its links never stops the server's\n // other invitations (Opus review 4).\n const due = new Date(now()).toISOString();\n type Row = {\n id: string;\n port: string;\n payload_json: string;\n attempts: number;\n next_attempt_at: string;\n };\n const rows = directory.read((db) => [\n ...([\"events\", \"metering\"] as const).flatMap((port) =>\n db.all<Row>(\n \"SELECT id, port, payload_json, attempts, next_attempt_at FROM outbound WHERE port = ? ORDER BY rowid LIMIT 50\",\n port,\n ),\n ),\n ...db.all<Row>(\n \"SELECT id, port, payload_json, attempts, next_attempt_at FROM outbound WHERE port = 'invitations' AND next_attempt_at <= ? ORDER BY rowid LIMIT 50\",\n due,\n ),\n ]);\n if (rows.every((row) => row.next_attempt_at > due)) return;\n const blocked = new Set<string>();\n let delivered = 0;\n for (const row of rows) {\n if (blocked.has(row.port)) continue;\n if (row.next_attempt_at > due) {\n blocked.add(row.port);\n continue;\n }\n const before = row.attempts;\n await deliverOne(row);\n const still = directory.read((db) =>\n db.get<{ attempts: number }>(\"SELECT attempts FROM outbound WHERE id = ?\", row.id),\n );\n if (still && still.attempts > before) {\n if (row.port !== \"invitations\") blocked.add(row.port);\n } else delivered += 1;\n }\n if (delivered === 0) return;\n }\n } finally {\n dispatching = undefined;\n }\n })();\n return dispatching;\n };\n const timer =\n ports.events || ports.metering || ports.invitations\n ? setInterval(() => void dispatch(), options.dispatchMs ?? 1_000)\n : undefined;\n timer?.unref();\n\n const has = {\n limits: typeof ports.limits?.check === \"function\",\n metering: typeof ports.metering?.record === \"function\",\n accounts: typeof ports.accounts?.resolve === \"function\",\n authenticate: typeof ports.accounts?.authenticate === \"function\",\n status: typeof ports.accounts?.status === \"function\",\n abuse: typeof ports.abuse?.report === \"function\",\n pushed: typeof ports.abuse?.pushed === \"function\",\n policy: typeof ports.policy?.link === \"function\",\n routing: typeof ports.routing?.resolve === \"function\",\n linkHost: typeof ports.routing?.linkHost === \"function\",\n events: typeof ports.events?.deliver === \"function\",\n identity: typeof ports.identity?.providers === \"function\",\n invitations: typeof ports.invitations?.send === \"function\",\n };\n\n return {\n has,\n\n async limit(q) {\n if (!has.limits) return { allowed: true };\n const key = `limits\\u0000${JSON.stringify(q)}`;\n const hit = cached<LimitVerdict>(key);\n if (hit) return hit;\n const answer = await ask(\"limits\", OPERATOR_TIME_LIMITS.limits, LimitAnswer, () =>\n ports.limits?.check(q),\n );\n if (!answer) return { allowed: \"unavailable\" };\n const verdict: LimitVerdict = answer.value.allowed\n ? { allowed: true }\n : {\n allowed: false,\n code: answer.value.code,\n message: answer.value.message,\n ...(answer.value.retryAfterMs !== undefined\n ? { retryAfterMs: answer.value.retryAfterMs }\n : {}),\n };\n keep(key, verdict, answer.value.cacheForMs);\n return verdict;\n },\n\n async linkPolicy(q) {\n if (!has.policy) return {};\n const key = `policy\\u0000${q.routeId}\\u0000${q.tokenId ?? \"\"}`;\n const hit = cached<LinkPolicy>(key);\n if (hit) return hit;\n const answer = await ask(\"policy\", OPERATOR_TIME_LIMITS.policy, LinkPolicy, () =>\n ports.policy?.link(q),\n );\n if (!answer) return {};\n keep(key, answer.value, answer.value.cacheForMs);\n return answer.value;\n },\n\n async chatHost(client) {\n if (typeof ports.policy?.chatHost !== \"function\") return null;\n const answer = await ask(\n \"policy.chatHost\",\n OPERATOR_TIME_LIMITS.policy,\n ChatHostPolicySchema.nullable(),\n () => ports.policy?.chatHost?.(client),\n );\n return answer?.value ?? null;\n },\n\n async route(host) {\n if (!has.routing) return null;\n const key = `routing\\u0000${host}`;\n const hit = cache.get(key);\n if (hit && hit.until > now()) return hit.value as RoutingAnswer;\n const answer = await ask(\"routing\", OPERATOR_TIME_LIMITS.routing, RoutingAnswer, () =>\n ports.routing?.resolve(host),\n );\n if (!answer) return \"unavailable\";\n keep(key, answer.value, answer.value?.cacheForMs);\n return answer.value;\n },\n\n async linkHost(q) {\n if (!has.linkHost) return null;\n const answer = await ask(\"routing.linkHost\", OPERATOR_TIME_LIMITS.routing, LinkHost, () =>\n ports.routing?.linkHost?.(q),\n );\n return answer?.value ?? null;\n },\n\n async providers() {\n if (!has.identity) return [];\n try {\n const found = await within(OPERATOR_TIME_LIMITS.identity, () =>\n ports.identity?.providers(),\n );\n return (Array.isArray(found) ? found : []).filter(\n (provider: IdentityProvider) =>\n typeof provider?.id === \"string\" &&\n /^[a-z][a-z0-9-]{0,31}$/.test(provider.id) &&\n typeof provider.authorize === \"function\" &&\n typeof provider.callback === \"function\",\n );\n } catch (error) {\n log.warn(\"operator.no_answer\", { port: \"identity\", message: (error as Error).message });\n return [];\n }\n },\n\n async resolve(identity, steps) {\n if (!has.accounts) return { default: true };\n const answer = await ask(\n \"accounts.resolve\",\n OPERATOR_TIME_LIMITS.accounts,\n AccountResolution,\n () => ports.accounts?.resolve(identity, { steps }),\n );\n return answer ? answer.value : \"unavailable\";\n },\n\n async authenticate(bearer, resource) {\n if (!has.authenticate) return null;\n const answer = await ask(\n \"accounts.authenticate\",\n OPERATOR_TIME_LIMITS.authenticate,\n AuthenticatedCredential,\n () => ports.accounts?.authenticate?.(bearer, { resource }),\n );\n return answer?.value ?? null;\n },\n\n async status(account) {\n if (typeof ports.accounts?.status !== \"function\") return undefined;\n try {\n const found = await within(OPERATOR_TIME_LIMITS.accounts, () =>\n ports.accounts?.status?.(account),\n );\n return found === \"active\" || found === \"suspended\" ? found : undefined;\n } catch {\n return undefined;\n }\n },\n\n async report(r) {\n if (!has.abuse) return;\n try {\n await within(OPERATOR_TIME_LIMITS.policy * 5, () => ports.abuse?.report(r));\n } catch (error) {\n log.warn(\"operator.no_answer\", { port: \"abuse.report\", message: (error as Error).message });\n }\n },\n\n pushed(v, quarantine) {\n if (!has.pushed) return;\n void ask(\"abuse.pushed\", OPERATOR_TIME_LIMITS.pushed, PushedAnswer, () =>\n ports.abuse?.pushed?.(v),\n ).then(async (answer) => {\n const reason = answer?.value?.quarantine?.reason;\n if (reason !== undefined) {\n await quarantine(reason).catch((error: unknown) =>\n log.error(\"operator.quarantine_failed\", { error }),\n );\n }\n });\n },\n\n enqueue(item) {\n if (!has[item.port]) return;\n const id =\n item.port === \"events\"\n ? item.event.eventId\n : item.port === \"metering\"\n ? item.batch.batchId\n : item.invitation.invitationId;\n const payload =\n item.port === \"events\"\n ? item.event\n : item.port === \"metering\"\n ? item.batch\n : item.invitation;\n directory.write((db) =>\n db.run(\n \"INSERT OR IGNORE INTO outbound (id, port, payload_json, attempts, next_attempt_at) VALUES (?, ?, ?, 0, ?)\",\n `${item.port}:${id}`,\n item.port,\n JSON.stringify(payload),\n new Date(now()).toISOString(),\n ),\n );\n void dispatch();\n },\n\n flush: () => dispatch(),\n\n stop() {\n if (timer) clearInterval(timer);\n },\n };\n}\n","/**\n * The remote server's identity providers (INTERFACES §18.5, D165 item 8): the sign-in port's\n * built-in adapters, configured in `identityProviders`, beside those an operator module supplies\n * (asked at every sign-in, so its set can change while the server runs, D167):\n *\n * - `oidc`: any OpenID Connect provider, by its issuer's discovery document; the authorization\n * code flow with PKCE (S256) and a nonce, and the ID token checked (signature, issuer, audience,\n * expiry, nonce) by `openid-client`.\n * - `github`: GitHub's OAuth web flow with PKCE, then `GET /user` for the account's stable ID, its\n * login and name, and its age (`facts.createdAt`) for an operator's policy.\n * - `development`: a page that asks for a name and trusts it, for tests and a self-hoster's first\n * run; its names are never shown as verified.\n *\n * A provider's client secret is read from `clientSecretFile`, never from the configuration itself,\n * and is never logged.\n */\nimport { readFileSync } from \"node:fs\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type {\n IdentityProvider,\n SignInContext,\n SignInIdentity,\n SignInPkce,\n} from \"@mostra/protocol/operator\";\nimport * as oidc from \"openid-client\";\nimport type { Environment, Log } from \"../log.ts\";\nimport type { IdentityProviderConfig } from \"./config.ts\";\n\n/** How long a provider's discovery, token exchange or user lookup may take. */\nconst PROVIDER_TIMEOUT_MS = 8_000;\n\n/** GitHub's endpoints (VERIFIED_FACTS, WP-30). */\nconst GITHUB = {\n authorize: \"https://github.com/login/oauth/authorize\",\n token: \"https://github.com/login/oauth/access_token\",\n user: \"https://api.github.com/user\",\n} as const;\n\n/** A built-in provider: the port's shape, and whether its names are verified. */\nexport interface BuiltInProvider extends IdentityProvider {\n readonly kind: IdentityProviderConfig[\"kind\"];\n /** Whether the names it gives are verified by someone (all but `development`). */\n readonly verifies: boolean;\n}\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_REMOTE_CONFIG_INVALID\", { message }));\n}\n\nfunction secretOf(config: IdentityProviderConfig): string {\n if (config.clientSecretFile === undefined) {\n throw invalid(\n `The identity provider \\`${config.id}\\` needs \\`clientSecretFile\\`, a file holding its client secret.`,\n );\n }\n try {\n const secret = readFileSync(config.clientSecretFile, \"utf8\").trim();\n if (secret === \"\") throw new Error(\"empty\");\n return secret;\n } catch {\n throw invalid(\n `The identity provider \\`${config.id}\\`'s \\`clientSecretFile\\` (${config.clientSecretFile}) can't be read, or is empty.`,\n );\n }\n}\n\n/** A fetch bounded in time, for a provider's own endpoints. */\nasync function timedFetch(url: string, init: RequestInit): Promise<Response> {\n return fetch(url, { ...init, signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS) });\n}\n\n/** The OpenID Connect adapter. Discovery happens at the first sign-in and is kept. */\nfunction oidcProvider(config: IdentityProviderConfig, env: Environment): BuiltInProvider {\n if (config.issuer === undefined || config.clientId === undefined) {\n throw invalid(\n `The identity provider \\`${config.id}\\` (oidc) needs \\`issuer\\` and \\`clientId\\`.`,\n );\n }\n const secret = secretOf(config);\n const issuer = new URL(config.issuer);\n // A test provider on loopback speaks http; nothing else may.\n const insecure =\n issuer.protocol === \"http:\" &&\n env[\"MOSTRA_TEST_OIDC_INSECURE\"] === \"1\" &&\n (issuer.hostname === \"127.0.0.1\" || issuer.hostname === \"localhost\");\n if (issuer.protocol !== \"https:\" && !insecure) {\n throw invalid(`The identity provider \\`${config.id}\\`'s \\`issuer\\` must be an https: URL.`);\n }\n let discovered: Promise<oidc.Configuration> | undefined;\n const configuration = (): Promise<oidc.Configuration> => {\n discovered ??= oidc\n .discovery(\n issuer,\n config.clientId as string,\n undefined,\n oidc.ClientSecretPost(secret),\n insecure ? { execute: [oidc.allowInsecureRequests], timeout: 8 } : { timeout: 8 },\n )\n .catch((error: unknown) => {\n discovered = undefined;\n throw error;\n });\n return discovered;\n };\n return {\n id: config.id,\n label: config.label ?? config.id,\n kind: \"oidc\",\n verifies: true,\n async authorize(state: string, pkce: SignInPkce, context: SignInContext) {\n const url = oidc.buildAuthorizationUrl(await configuration(), {\n redirect_uri: context.redirectUri,\n scope: \"openid email profile\",\n state,\n nonce: context.nonce,\n code_challenge: pkce.challenge,\n code_challenge_method: \"S256\",\n });\n return url.href;\n },\n async callback(params, context) {\n const current = new URL(context.redirectUri);\n for (const [key, value] of Object.entries(params)) current.searchParams.set(key, value);\n const tokens = await oidc.authorizationCodeGrant(await configuration(), current, {\n pkceCodeVerifier: context.pkce.verifier,\n expectedState: context.state,\n expectedNonce: context.nonce,\n idTokenExpected: true,\n });\n const claims = tokens.claims();\n if (!claims) throw new Error(\"The provider sent no ID token.\");\n const name =\n typeof claims[\"name\"] === \"string\"\n ? claims[\"name\"]\n : typeof claims[\"preferred_username\"] === \"string\"\n ? claims[\"preferred_username\"]\n : undefined;\n const identity: SignInIdentity = {\n provider: config.id,\n subject: claims.sub,\n ...(typeof claims[\"email\"] === \"string\" ? { email: claims[\"email\"] } : {}),\n ...(typeof claims[\"email_verified\"] === \"boolean\"\n ? { emailVerified: claims[\"email_verified\"] }\n : {}),\n ...(name !== undefined ? { name } : {}),\n };\n return identity;\n },\n };\n}\n\n/** The GitHub adapter: an OAuth app's web flow with PKCE (VERIFIED_FACTS, WP-30). */\nfunction githubProvider(config: IdentityProviderConfig, env: Environment): BuiltInProvider {\n if (config.clientId === undefined) {\n throw invalid(`The identity provider \\`${config.id}\\` (github) needs \\`clientId\\`.`);\n }\n const secret = secretOf(config);\n // Tests point the adapter at a fake GitHub on loopback; nothing else may.\n const base = env[\"MOSTRA_TEST_GITHUB_BASE\"];\n const endpoints =\n base !== undefined && /^http:\\/\\/(127\\.0\\.0\\.1|localhost):\\d+$/.test(base)\n ? {\n authorize: `${base}/login/oauth/authorize`,\n token: `${base}/login/oauth/access_token`,\n user: `${base}/user`,\n }\n : GITHUB;\n return {\n id: config.id,\n label: config.label ?? \"GitHub\",\n kind: \"github\",\n verifies: true,\n authorize(state, pkce, context) {\n const url = new URL(endpoints.authorize);\n url.searchParams.set(\"client_id\", config.clientId as string);\n url.searchParams.set(\"redirect_uri\", context.redirectUri);\n url.searchParams.set(\"state\", state);\n url.searchParams.set(\"scope\", \"\");\n url.searchParams.set(\"allow_signup\", \"true\");\n url.searchParams.set(\"code_challenge\", pkce.challenge);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n return url.href;\n },\n async callback(params, context) {\n if (params[\"error\"] !== undefined) {\n throw new Error(`GitHub refused the sign-in (${params[\"error\"]}).`);\n }\n const code = params[\"code\"];\n if (code === undefined) throw new Error(\"GitHub sent no code.\");\n const exchanged = await timedFetch(endpoints.token, {\n method: \"POST\",\n headers: {\n accept: \"application/json\",\n \"content-type\": \"application/x-www-form-urlencoded\",\n },\n body: new URLSearchParams({\n client_id: config.clientId as string,\n client_secret: secret,\n code,\n redirect_uri: context.redirectUri,\n code_verifier: context.pkce.verifier,\n }).toString(),\n });\n const token = (await exchanged.json().catch(() => ({}))) as {\n access_token?: string;\n error?: string;\n };\n if (!exchanged.ok || typeof token.access_token !== \"string\") {\n throw new Error(`GitHub's code exchange failed (${token.error ?? exchanged.status}).`);\n }\n const user = await timedFetch(endpoints.user, {\n headers: {\n accept: \"application/vnd.github+json\",\n authorization: `Bearer ${token.access_token}`,\n \"user-agent\": \"mostra-remote-server\",\n },\n });\n const found = (await user.json().catch(() => ({}))) as {\n id?: number;\n login?: string;\n name?: string | null;\n email?: string | null;\n created_at?: string;\n };\n if (!user.ok || typeof found.id !== \"number\") {\n throw new Error(`GitHub's user lookup failed (${user.status}).`);\n }\n return {\n provider: config.id,\n // The numeric ID: a login can be renamed and then taken by someone else.\n subject: String(found.id),\n ...(typeof found.email === \"string\" ? { email: found.email } : {}),\n name: found.name ?? found.login ?? String(found.id),\n facts: {\n login: found.login ?? null,\n ...(found.created_at !== undefined ? { createdAt: found.created_at } : {}),\n },\n };\n },\n };\n}\n\n/**\n * The development adapter: the device page and the sign-in page ask for a name and trust it\n * (D166 item 4). Its `authorize` sends the person to the server's own name page.\n */\nfunction developmentProvider(config: IdentityProviderConfig, apiOrigin: string): BuiltInProvider {\n return {\n id: config.id,\n label: config.label ?? \"Development sign-in\",\n kind: \"development\",\n verifies: false,\n authorize(state) {\n const url = new URL(`${apiOrigin}/signin/${config.id}/name`);\n url.searchParams.set(\"state\", state);\n return url.href;\n },\n async callback(params) {\n const name = (params[\"name\"] ?? \"\").trim().slice(0, 64);\n if (name === \"\") throw new Error(\"No name was given.\");\n return { provider: config.id, subject: name.toLowerCase(), name };\n },\n };\n}\n\n/** Builds the configured providers; a provider it can't use stops the server, naming it. */\nexport function builtInProviders(\n configs: readonly IdentityProviderConfig[],\n options: { readonly apiOrigin: string; readonly env: Environment; readonly log: Log },\n): BuiltInProvider[] {\n const seen = new Set<string>();\n return configs.map((config) => {\n if (seen.has(config.id)) throw invalid(`Two identity providers are named \\`${config.id}\\`.`);\n seen.add(config.id);\n const provider =\n config.kind === \"oidc\"\n ? oidcProvider(config, options.env)\n : config.kind === \"github\"\n ? githubProvider(config, options.env)\n : developmentProvider(config, options.apiOrigin);\n options.log.info(\"signin.provider\", { id: config.id, kind: config.kind });\n return provider;\n });\n}\n","/**\n * Where a request goes, by its exact `Host` (INTERFACES §18.4, D165 item 7, D167): the API origin;\n * a configured user-content domain's apex, the hosted shell; a route's label under a configured\n * domain, or under a domain an operator supplies, the route's frames; a host an operator supplies\n * (`routing.resolve`), a hosted shell for one home or one route; and anything else, nothing (421).\n *\n * A host an operator supplies is recorded the first time it is served (`operator_host` and\n * `label_issued`, kind `operator`), bound to its home forever: an answer that would move it to\n * another home is refused and logged, so no origin, nor the browser storage it holds, passes to\n * another tenant. The operator is asked again for a recorded host as its answer's cache allows,\n * and a host it no longer answers for gets nothing; when it doesn't answer in time, the recorded\n * binding is served, since views proceed without the operator (D165 item 9).\n */\nimport type { RoutingAnswer } from \"@mostra/protocol/operator\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport type { Operator } from \"./operator.ts\";\n\n/** The server's own labels: 26 lower-case Crockford base32 characters (§18.4). */\nexport const SERVER_LABEL: RegExp = /^[0-9a-hjkmnp-tv-z]{26}$/;\n\n/** Where one request goes. */\nexport type Destination =\n | { readonly kind: \"api\" }\n | {\n /** A hosted shell: a configured apex (any home's routes), or an operator's host. */\n readonly kind: \"shell\";\n readonly host: string;\n readonly frameDomain: string;\n /** The one home an operator's host serves; absent on a configured apex. */\n readonly homeId?: string;\n /** The one route an operator's host serves. */\n readonly routeId?: string;\n }\n | {\n readonly kind: \"frame\";\n readonly frameDomain: string;\n readonly route: { readonly id: string; readonly homeId: string };\n }\n | { readonly kind: \"none\" };\n\n/** A recorded operator host. */\ninterface HostRow {\n readonly host: string;\n readonly home_id: string;\n readonly route_id: string | null;\n readonly frame_domain: string;\n}\n\n/** Options for {@link createRouting}. */\nexport interface RoutingOptions {\n readonly apiHost: string;\n /** The configured user-content domains (D137). */\n readonly domains: () => readonly string[];\n /** The active one, under which a chosen route's frames sit. */\n readonly active: () => string;\n readonly directory: Ledger;\n readonly operator: Operator;\n readonly log: Log;\n}\n\n/** The server's routing. */\nexport interface Routing {\n /** Where a request for `host` goes. */\n destination(host: string): Promise<Destination>;\n /**\n * An operator host for one home's links (`routing.linkHost`): resolved and recorded when it is\n * new, and given only when it serves that home (and route); `undefined` otherwise.\n */\n linkHost(homeId: string, routeId: string, host: string): Promise<string | undefined>;\n /** Whether `host` is a shell of this home: a configured apex, or one of its operator hosts. */\n servesShell(homeId: string, host: string): boolean;\n /** The frame domain of a shell host for a route of a home, or `undefined`. */\n frameDomainOf(homeId: string, routeId: string, shellHost: string): string | undefined;\n /** The shell hosts that may frame a route's pages on a frame domain (`frame-ancestors`). */\n ancestorsOf(homeId: string, routeId: string, frameDomain: string): string[];\n}\n\n/** Builds the routing over the directory and the operator. */\nexport function createRouting(options: RoutingOptions): Routing {\n const { directory, operator, log } = options;\n const configured = (host: string): boolean => options.domains().includes(host);\n const configuredParent = (host: string): string | undefined =>\n options.domains().find((domain) => host.endsWith(`.${domain}`));\n\n const recorded = (host: string): HostRow | undefined =>\n directory.read((db) => db.get<HostRow>(\"SELECT * FROM operator_host WHERE host = ?\", host));\n\n const routeByLabel = (label: string): { id: string; home_id: string } | undefined =>\n directory.read((db) =>\n db.get<{ id: string; home_id: string }>(\n \"SELECT id, home_id FROM artifact_route WHERE label = ? AND removing_json IS NULL\",\n label,\n ),\n );\n\n /** Whether an operator's answer may bind `host` at all: never the server's own names. */\n const bindable = (host: string): boolean => {\n if (host === options.apiHost || configured(host)) return false;\n const parent = configuredParent(host);\n if (parent !== undefined) {\n const label = host.slice(0, host.length - parent.length - 1);\n // One label under a configured domain, and never one the server could issue itself.\n if (label.includes(\".\") || SERVER_LABEL.test(label)) return false;\n }\n return true;\n };\n\n /** Records an operator's answer for a new host; `undefined` when it can't be bound. */\n const record = (host: string, answer: NonNullable<RoutingAnswer>): HostRow | undefined => {\n if (!bindable(host)) {\n log.warn(\"routing.answer_refused\", { host, why: \"reserved\" });\n return undefined;\n }\n const at = new Date().toISOString();\n return directory.write((db) => {\n let row: HostRow;\n if (\"shell\" in answer) {\n if (!db.get(\"SELECT 1 FROM home WHERE id = ?\", answer.shell.home)) return undefined;\n // A frame domain is configured, or one of the operator's own; never the API origin's.\n if (answer.shell.domain === options.apiHost) return undefined;\n row = {\n host,\n home_id: answer.shell.home,\n route_id: null,\n frame_domain: answer.shell.domain,\n };\n } else {\n const found = db.get<{ home_id: string }>(\n \"SELECT home_id FROM artifact_route WHERE id = ? AND home_id = ? AND removing_json IS NULL\",\n answer.route.routeId,\n answer.route.home,\n );\n if (!found) return undefined;\n row = {\n host,\n home_id: answer.route.home,\n route_id: answer.route.routeId,\n frame_domain: options.active(),\n };\n }\n const issued = db.get<{ home_id: string }>(\n \"SELECT home_id FROM label_issued WHERE label = ?\",\n host,\n );\n if (issued && issued.home_id !== row.home_id) {\n log.warn(\"routing.answer_refused\", { host, why: \"issued-to-another-home\" });\n return undefined;\n }\n if (!issued) {\n db.run(\n \"INSERT INTO label_issued (label, home_id, route_id, kind, issued_at) VALUES (?, ?, ?, 'operator', ?)\",\n host,\n row.home_id,\n row.route_id,\n at,\n );\n }\n db.run(\n \"INSERT INTO operator_host (host, home_id, route_id, frame_domain, recorded_at) VALUES (?, ?, ?, ?, ?)\",\n row.host,\n row.home_id,\n row.route_id,\n row.frame_domain,\n at,\n );\n log.info(\"routing.host_recorded\", { host, home: row.home_id });\n return row;\n });\n };\n\n /** Whether an operator's answer agrees with a recorded host's binding. */\n const agrees = (row: HostRow, answer: NonNullable<RoutingAnswer>): boolean =>\n \"shell\" in answer\n ? answer.shell.home === row.home_id &&\n row.route_id === null &&\n answer.shell.domain === row.frame_domain\n : answer.route.home === row.home_id && answer.route.routeId === row.route_id;\n\n /** The operator's host for `host`, asked and recorded, or `undefined`. */\n const operatorHost = async (host: string): Promise<HostRow | undefined> => {\n const row = recorded(host);\n if (!operator.has.routing) return undefined;\n const answer = await operator.route(host);\n if (answer === \"unavailable\") return row;\n if (answer === null) return undefined;\n if (row) {\n if (agrees(row, answer)) return row;\n log.warn(\"routing.answer_refused\", { host, why: \"moved\" });\n return undefined;\n }\n return record(host, answer);\n };\n\n const asShell = (row: HostRow): Destination => ({\n kind: \"shell\",\n host: row.host,\n frameDomain: row.frame_domain,\n homeId: row.home_id,\n ...(row.route_id !== null ? { routeId: row.route_id } : {}),\n });\n\n /** A route's frames on `<label>.<domain>`, when the label is the route's and the domain serves it. */\n const frame = (host: string): Destination | undefined => {\n const dot = host.indexOf(\".\");\n if (dot <= 0) return undefined;\n const label = host.slice(0, dot);\n const domain = host.slice(dot + 1);\n if (!SERVER_LABEL.test(label)) return undefined;\n const route = routeByLabel(label);\n if (!route) return undefined;\n if (configured(domain)) {\n return { kind: \"frame\", frameDomain: domain, route: { id: route.id, homeId: route.home_id } };\n }\n // An operator's frame domain serves only the routes of the homes it was given for.\n const served = directory.read((db) =>\n db.get(\n \"SELECT 1 FROM operator_host WHERE frame_domain = ? AND home_id = ? AND (route_id IS NULL OR route_id = ?)\",\n domain,\n route.home_id,\n route.id,\n ),\n );\n return served\n ? { kind: \"frame\", frameDomain: domain, route: { id: route.id, homeId: route.home_id } }\n : undefined;\n };\n\n return {\n async destination(host) {\n if (host === options.apiHost) return { kind: \"api\" };\n if (configured(host)) return { kind: \"shell\", host, frameDomain: host };\n const framed = frame(host);\n if (framed) return framed;\n const row = await operatorHost(host);\n return row ? asShell(row) : { kind: \"none\" };\n },\n\n async linkHost(homeId, routeId, host) {\n const row = await operatorHost(host.toLowerCase());\n if (!row || row.home_id !== homeId) return undefined;\n if (row.route_id !== null && row.route_id !== routeId) return undefined;\n return row.host;\n },\n\n servesShell(homeId, host) {\n if (configured(host)) return true;\n const row = recorded(host);\n return row !== undefined && row.home_id === homeId;\n },\n\n frameDomainOf(homeId, routeId, shellHost) {\n if (configured(shellHost)) return shellHost;\n const row = recorded(shellHost);\n if (!row || row.home_id !== homeId) return undefined;\n if (row.route_id !== null && row.route_id !== routeId) return undefined;\n return row.frame_domain;\n },\n\n ancestorsOf(homeId, routeId, frameDomain) {\n const hosts = configured(frameDomain) ? [frameDomain] : [];\n for (const row of directory.read((db) =>\n db.all<{ host: string }>(\n \"SELECT host FROM operator_host WHERE frame_domain = ? AND home_id = ? AND (route_id IS NULL OR route_id = ?) ORDER BY host\",\n frameDomain,\n homeId,\n routeId,\n ),\n )) {\n hosts.push(row.host);\n }\n return hosts;\n },\n };\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\";\nimport { validProxies } from \"./clients.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 const proxy = validProxies(config.trustedProxies ?? []);\n if (proxy !== undefined) {\n throw invalid(\n `The configuration key \\`trustedProxies\\` names ${JSON.stringify(proxy)}, which is neither an address nor a CIDR block.`,\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 */\n\nimport { readFileSync } from \"node:fs\";\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 { faultsFrom } from \"../faults.ts\";\nimport {\n BASE_HEADERS,\n documentHeaders,\n locateShell,\n resetOnClose,\n shellAssetResponse,\n} 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 Authorize, createAuthorize } from \"./authorize.ts\";\nimport { clientAddresses, RateLimiter } from \"./clients.ts\";\nimport type { RemoteServerConfig } from \"./config.ts\";\nimport { type DataDirectory, type HomeAssembler, openDataDirectory } from \"./data.ts\";\nimport { createHandle } from \"./handle.ts\";\nimport { type HostedHome, type HostedServices, openHostedHome } from \"./hosted.ts\";\nimport { type HomeOwner, homeUnavailable } from \"./hosted-pages.ts\";\nimport { createRemoteMcp, serverDocs } from \"./mcp.ts\";\nimport { createMeter, type Meter } from \"./metering.ts\";\nimport { createClients } from \"./oauth-clients.ts\";\nimport { loadOperator, type Operator } from \"./operator.ts\";\nimport { type BuiltInProvider, builtInProviders } from \"./providers.ts\";\nimport { createRouting, type Destination, type Routing } from \"./routing.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 and the operator module are made once the directory is open; homes\n // open only after both.\n let auth: Authorization | undefined;\n let operator: Operator | undefined;\n let meter: Meter | undefined;\n let routing: Routing;\n let authorizer: Authorize | undefined;\n let api: Api | undefined;\n const shellDir = locateShell(options.env);\n const clients = clientAddresses({\n trustedProxies: config.trustedProxies,\n ipv6Prefix: config.rateLimits?.ipv6Prefix,\n });\n const rates = new RateLimiter();\n const faults = faultsFrom(options.env);\n const rateOf = (rate: { count: number; per: string } | undefined) =>\n rate === undefined ? undefined : { count: rate.count, perMs: durationMs(rate.per as Duration) };\n /**\n * `rateLimits.perIp.requests`: every request to the server, from one client address (IPv6 per\n * /64), API origin and hosted hosts alike, before anything else is read (D165 item 13). A\n * health check is never counted. Without the setting there is no limit.\n */\n const perIpRequests = rateOf(config.rateLimits?.perIp?.requests);\n /** Who owns a home, as its pages' sender line names them (D161). */\n const ownerOf = (homeId: string): HomeOwner => {\n const row = data.directory.read((db) =>\n db.get<{ account: string; name: string | null; provider: string | null }>(\n `SELECT a.id AS account, a.name, (SELECT i.provider FROM identity i WHERE i.account_id = a.id\n ORDER BY i.linked_at LIMIT 1) AS provider\n FROM home h JOIN account a ON a.id = h.owner_account_id WHERE h.id = ?`,\n homeId,\n ),\n );\n if (!row) return { account: \"\" };\n const provider = config.identityProviders?.find((candidate) => candidate.id === row.provider);\n // A name the development provider took on trust is unverified (D161).\n const verifiedBy =\n provider && provider.kind !== \"development\"\n ? (provider.label ?? (provider.kind === \"github\" ? \"GitHub\" : provider.id))\n : undefined;\n return {\n account: row.account,\n ...(row.name !== null ? { name: row.name } : {}),\n ...(verifiedBy !== undefined ? { verifiedBy } : {}),\n };\n };\n const services = (): HostedServices => ({\n operator: operator as Operator,\n clients,\n rates,\n rateLimits: {\n perIpSubmissions: rateOf(config.rateLimits?.perIp?.submissions),\n perLinkSubmissions: rateOf(config.rateLimits?.perLink?.submissions),\n },\n owner: ownerOf,\n meter: meter as Meter,\n routing,\n signin: {\n start: (signin, challenge) => (authorizer as Authorize).startViewerSignin(signin, challenge),\n finish: (input) => (authorizer as Authorize).finishViewerSignin(input),\n },\n signInOffered: () =>\n (config.identityProviders?.length ?? 0) > 0 || (operator?.has.identity ?? false),\n });\n const assembler: HomeAssembler<HostedHome> = {\n assemble: (home) =>\n openHostedHome({\n faults,\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 services: services(),\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 const handle = createHandle({\n apiOrigin: config.apiOrigin,\n data: () => data,\n directory: () => data.directory,\n suspended: (homeId) => api?.closeHome(homeId),\n log,\n });\n try {\n operator = await loadOperator({\n path: config.operator,\n handle,\n directory: data.directory,\n log,\n // An invitation's link is built when it is handed over, never kept in the queue (D168).\n invitationLink: async (homeId, tokenId) => {\n // A home the directory no longer has can't build a link: its invitations go, while one\n // that is only closed, drained or failing to open is tried again later.\n const known = data.directory.read((db) =>\n db.get(\"SELECT 1 FROM home WHERE id = ?\", homeId),\n );\n if (known === undefined) return undefined;\n return (await data.home(homeId)).assembled.invitationLink(tokenId);\n },\n ...(Number(options.env[\"MOSTRA_TEST_OPERATOR_DISPATCH_MS\"]) > 0\n ? { dispatchMs: Number(options.env[\"MOSTRA_TEST_OPERATOR_DISPATCH_MS\"]) }\n : {}),\n });\n } catch (error) {\n await data.close();\n throw error;\n }\n routing = createRouting({\n apiHost: new URL(config.apiOrigin).host,\n domains: () => [config.domains.active, ...(config.domains.spares ?? [])],\n active: () => config.domains.active,\n directory: data.directory,\n operator,\n log,\n });\n meter = createMeter({\n operator,\n keysDir: join(options.data, \"keys\"),\n log,\n ...(Number(options.env[\"MOSTRA_TEST_METER_WINDOW_MS\"]) > 0\n ? { windowMs: Number(options.env[\"MOSTRA_TEST_METER_WINDOW_MS\"]) }\n : {}),\n activeHomes: () => data.open().map((home) => ({ home, account: ownerOf(home).account })),\n });\n auth = createAuthorization({\n directory: data.directory,\n config,\n log,\n operator,\n ...(Number(options.env[\"MOSTRA_TEST_ACCESS_TTL_MS\"]) > 0\n ? { accessTtlMs: Number(options.env[\"MOSTRA_TEST_ACCESS_TTL_MS\"]) }\n : {}),\n ...(Number(options.env[\"MOSTRA_TEST_ROTATION_GRACE_MS\"]) > 0\n ? { rotationGraceMs: Number(options.env[\"MOSTRA_TEST_ROTATION_GRACE_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 // The authorization server's clients and browser pages (INTERFACES §18.5).\n const scheme = config.scheme ?? \"https\";\n const oauthClients = createClients({\n directory: data.directory,\n log,\n env: options.env,\n isShellOrigin: (origin) => {\n if (!origin.startsWith(`${scheme}://`)) return false;\n const host = origin.slice(scheme.length + 3);\n if (domains.includes(host)) return true;\n return (\n data.directory.read((db) => db.get(\"SELECT 1 FROM operator_host WHERE host = ?\", host)) !==\n undefined\n );\n },\n });\n let providers: BuiltInProvider[];\n try {\n providers = builtInProviders(config.identityProviders ?? [], {\n apiOrigin: config.apiOrigin,\n env: options.env,\n log,\n });\n } catch (error) {\n operator?.stop();\n await data.close();\n throw error;\n }\n const authorize = createAuthorize({\n apiOrigin: config.apiOrigin,\n directory: data.directory,\n auth,\n clients: oauthClients,\n operator,\n providers,\n ownerName: (homeId) => ownerOf(homeId).name,\n log,\n });\n authorizer = authorize;\n const mcp = createRemoteMcp({\n apiOrigin: config.apiOrigin,\n version: options.runtimeVersion,\n docs: serverDocs(),\n log,\n operator,\n meter,\n home: async (id) => (await data.home(id)).assembled,\n ensureHome: (accountId) => (auth as Authorization).ensureHome(accountId),\n });\n api = createApi({\n config,\n auth,\n mcp,\n authorize,\n clients: oauthClients,\n registrations: { addresses: clients, rates },\n operator,\n log,\n filesDir: join(options.data, \"files\"),\n home: async (id) => (await data.home(id)).assembled,\n touch: (id) => data.touch(id),\n suspended: (id) => suspendedHome(id),\n message: (id) => meter?.add(\"relay.messages\", { account: ownerOf(id).account, home: id }),\n stored: (id, bytes) =>\n meter?.add(\"bytes.stored\", { account: ownerOf(id).account, home: id }, bytes),\n ...(Number(options.env[\"MOSTRA_TEST_GRANT_RECHECK_MS\"]) > 0\n ? { recheckMs: Number(options.env[\"MOSTRA_TEST_GRANT_RECHECK_MS\"]) }\n : {}),\n });\n const served: Api = api;\n const apiHost = new URL(config.apiOrigin).host;\n const domains = [config.domains.active, ...(config.domains.spares ?? [])];\n\n const onRequest = (request: IncomingMessage, response: ServerResponse): void => {\n const host = (request.headers.host ?? \"\").toLowerCase();\n const path = (request.url ?? \"/\").split(\"?\")[0] ?? \"/\";\n // Cookies never reach anything on a hosted host (D165 item 8): dropped before routing. Only\n // the API origin's own sign-in pages read the cookies it set itself.\n if (host !== apiHost) delete request.headers.cookie;\n if (host === apiHost && request.method === \"GET\" && path === \"/health\") {\n json(response, 200, { status: \"ok\", homes: data.open().length });\n return;\n }\n if (perIpRequests) {\n const taken = rates.take(`request-ip:${clients.keyOf(clients.of(request))}`, perIpRequests);\n if (!taken.ok) {\n response.setHeader(\"retry-after\", String(taken.retryAfterS));\n refusal(\n response,\n 429,\n createDiagnostic(\"MOSTRA_REMOTE_RATE_LIMITED\", {\n message: \"Too many requests from this address; try again shortly.\",\n }),\n );\n return;\n }\n }\n if (host === apiHost) {\n served.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 hostRefused = (): void =>\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 // An empty or malformed Host gets nothing, and is never asked of an operator.\n if (!/^[a-z0-9.-]{1,253}(:\\d{1,5})?$/.test(host)) {\n hostRefused();\n return;\n }\n routing\n .destination(host)\n .then(async (destination) => {\n if (destination.kind === \"none\" || destination.kind === \"api\") {\n hostRefused();\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 await hosted(request, response, destination, path);\n })\n .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 /** Whether the operator suspended a home (`ServerHandle.suspendHome`). */\n const suspendedHome = (homeId: string): boolean =>\n data.directory.read(\n (db) =>\n db.get<{ suspended_at: string | null }>(\n \"SELECT suspended_at FROM home WHERE id = ?\",\n homeId,\n )?.suspended_at != null,\n );\n\n /**\n * A home whose pages are served now: a suspended one answers 403 and one being moved 503,\n * each with its diagnostic, and nothing of it is opened for a page (D165 item 9).\n */\n const pagesOf = async (homeId: string, response: ServerResponse) => {\n if (suspendedHome(homeId)) {\n refusal(response, 403, homeUnavailable(\"suspended\"));\n return undefined;\n }\n try {\n const opened = await data.home(homeId);\n // Requests and the bytes they sent count against the home's owner (metering, §18.6): one\n // HTTP/1.1 connection answers one request at a time, so its written bytes are this one's.\n if (meter?.on) {\n const socket = response.socket;\n const before = socket?.bytesWritten ?? 0;\n response.once(\"finish\", () => {\n const account = ownerOf(homeId).account;\n meter?.add(\"requests\", { account, home: homeId });\n meter?.add(\n \"bytes.egress\",\n { account, home: homeId },\n Math.max(0, (socket?.bytesWritten ?? before) - before),\n );\n });\n }\n return opened;\n } catch (error) {\n if (error instanceof RpcError && error.diagnostic.code === \"MOSTRA_REMOTE_HOME_MOVING\") {\n response.setHeader(\"retry-after\", \"30\");\n refusal(response, 503, error.diagnostic);\n return undefined;\n }\n throw error;\n }\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} = ? AND removing_json IS NULL`,\n value,\n ),\n );\n\n /**\n * A hosted request (§18.4): a shell (a configured apex, or an operator's host for one home or\n * one route) serves only `/a/<routeId>` of the routes it may show and the shell's files; a\n * route's label serves that route's frames.\n */\n const hosted = async (\n request: IncomingMessage,\n response: ServerResponse,\n destination: Exclude<Destination, { kind: \"none\" | \"api\" }>,\n path: string,\n ): Promise<void> => {\n if (destination.kind === \"shell\") {\n if (path.startsWith(\"/_mostra/shell/assets/\")) {\n await assets(request, response);\n return;\n }\n // Where a page's sign-in returns (INTERFACES §18.4): the shell's own page, which finishes it\n // for the route that started it. It reads only the fragment and query it was sent.\n if (path === \"/_mostra/signin\" && (request.method === \"GET\" || request.method === \"HEAD\")) {\n if (shellDir === undefined) {\n notServed(response);\n return;\n }\n const html = readFileSync(join(shellDir, \"index.html\"));\n response.writeHead(200, {\n ...BASE_HEADERS,\n ...documentHeaders({ kind: \"shell\", origin: \"\", shellOrigin: \"\" }, \"'none'\"),\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n response.end(request.method === \"HEAD\" ? undefined : html);\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 // An operator's host shows only its own home's routes, or its one route.\n if (\n !route ||\n (destination.homeId !== undefined && route.home_id !== destination.homeId) ||\n (destination.routeId !== undefined && route.id !== destination.routeId)\n ) {\n notServed(response);\n return;\n }\n const home = await pagesOf(route.home_id, response);\n if (!home) return;\n await home.assembled.serve(request, response, {\n kind: \"shell\",\n domain: destination.host,\n routeId: route.id,\n });\n return;\n }\n const home = await pagesOf(destination.route.homeId, response);\n if (!home) return;\n await home.assembled.serve(request, response, {\n kind: \"frame\",\n domain: destination.frameDomain,\n routeId: destination.route.id,\n });\n };\n\n // Up to 1 MiB of headers (D98 item 9): a sibling tenant page can fill the parent domain's cookie\n // jar (180 cookies of 4 KiB, no public-suffix entry, D137), and its cookies, dropped unread here,\n // must never cost another page its session (D165 item 8).\n const listener: Server = createServer({ maxHeaderSize: 1024 * 1024 }, onRequest);\n // Stopping resets its connections, so none stays in TIME_WAIT on the server's port (#132).\n const stopListener = resetOnClose(listener);\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 served.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 served.close();\n await mcp.close().catch(() => undefined);\n // What the operator hasn't taken yet stays queued in the directory for the next start.\n meter?.stop();\n operator?.stop();\n await stopListener();\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,KAAi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