@mostra/runtime 0.9.0 → 0.11.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 (279) hide show
  1. package/dist/bin.js +6628 -9
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +2 -2
  4. package/dist/{child-Chiavhdx.js → child-BmNZ4a70.js} +2 -2
  5. package/dist/{child-Chiavhdx.js.map → child-BmNZ4a70.js.map} +1 -1
  6. package/dist/deps/child/install.js +1 -1
  7. package/dist/{directories-mJ1qlVht.js → directories-BLJjeSPD.js} +5 -5
  8. package/dist/directories-BLJjeSPD.js.map +1 -0
  9. package/dist/{files-FygSJIzK.js → files-DGeWuE4I.js} +2 -2
  10. package/dist/{files-FygSJIzK.js.map → files-DGeWuE4I.js.map} +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{instance-EnaZPs14.js → instance-DCiUHvgZ.js} +3835 -255
  15. package/dist/instance-DCiUHvgZ.js.map +1 -0
  16. package/dist/reference/cli.md +1322 -0
  17. package/dist/reference/diagnostics.json +1552 -0
  18. package/dist/reference/errors/MOSTRA_A11Y_MINOR.md +23 -0
  19. package/dist/reference/errors/MOSTRA_A11Y_SERIOUS.md +23 -0
  20. package/dist/reference/errors/MOSTRA_ACTION_CANCELLED.md +23 -0
  21. package/dist/reference/errors/MOSTRA_ACTION_EVENT_INVALID.md +23 -0
  22. package/dist/reference/errors/MOSTRA_ACTION_EXPORT_INVALID.md +23 -0
  23. package/dist/reference/errors/MOSTRA_ACTION_INTERRUPTED.md +23 -0
  24. package/dist/reference/errors/MOSTRA_ACTION_PAUSED.md +23 -0
  25. package/dist/reference/errors/MOSTRA_ACTION_RUN_NOT_FOUND.md +23 -0
  26. package/dist/reference/errors/MOSTRA_ACTION_THREW.md +23 -0
  27. package/dist/reference/errors/MOSTRA_ACTION_TOO_LARGE.md +23 -0
  28. package/dist/reference/errors/MOSTRA_ACTION_UNKNOWN_FUNCTION.md +23 -0
  29. package/dist/reference/errors/MOSTRA_ACTION_UNSERIALIZABLE.md +23 -0
  30. package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
  31. package/dist/reference/errors/MOSTRA_ARTIFACT_DIR_NOT_EMPTY.md +23 -0
  32. package/dist/reference/errors/MOSTRA_ARTIFACT_ENTRY_AMBIGUOUS.md +23 -0
  33. package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
  34. package/dist/reference/errors/MOSTRA_ARTIFACT_NOT_FOUND.md +23 -0
  35. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_ENTRY.md +23 -0
  36. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_PAGE.md +23 -0
  37. package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
  38. package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
  39. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_MISSING.md +23 -0
  40. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_UNREADABLE.md +23 -0
  41. package/dist/reference/errors/MOSTRA_ARTIFACT_TEMPLATE_UNKNOWN.md +23 -0
  42. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_COLLECTED.md +23 -0
  43. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_NOT_FOUND.md +23 -0
  44. package/dist/reference/errors/MOSTRA_BUILD_CRASHED.md +23 -0
  45. package/dist/reference/errors/MOSTRA_BUILD_FAILED.md +23 -0
  46. package/dist/reference/errors/MOSTRA_BUILD_TIMEOUT.md +23 -0
  47. package/dist/reference/errors/MOSTRA_BUILD_UNRESOLVED.md +23 -0
  48. package/dist/reference/errors/MOSTRA_CLI_CONFIG_UNWRITABLE.md +23 -0
  49. package/dist/reference/errors/MOSTRA_CLI_UNKNOWN_COMMAND.md +23 -0
  50. package/dist/reference/errors/MOSTRA_CLI_USAGE.md +23 -0
  51. package/dist/reference/errors/MOSTRA_CONSOLE_ERROR.md +23 -0
  52. package/dist/reference/errors/MOSTRA_CONSOLE_WARNING.md +23 -0
  53. package/dist/reference/errors/MOSTRA_DEP_INSTALL_FAILED.md +23 -0
  54. package/dist/reference/errors/MOSTRA_DEP_MISSING.md +23 -0
  55. package/dist/reference/errors/MOSTRA_DEP_NOT_FOUND.md +23 -0
  56. package/dist/reference/errors/MOSTRA_DEP_OFFLINE.md +23 -0
  57. package/dist/reference/errors/MOSTRA_DEP_SPEC_INVALID.md +23 -0
  58. package/dist/reference/errors/MOSTRA_DEP_TIMEOUT.md +23 -0
  59. package/dist/reference/errors/MOSTRA_DEP_WARM_CONFLICT.md +23 -0
  60. package/dist/reference/errors/MOSTRA_ENV_BIND_FAILED.md +23 -0
  61. package/dist/reference/errors/MOSTRA_ENV_BROWSER_MISSING.md +23 -0
  62. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED.md +23 -0
  63. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_INVALID.md +23 -0
  64. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_UNAVAILABLE.md +23 -0
  65. package/dist/reference/errors/MOSTRA_ENV_HELPER_MISSING.md +23 -0
  66. package/dist/reference/errors/MOSTRA_ENV_NODE_UNSUPPORTED.md +23 -0
  67. package/dist/reference/errors/MOSTRA_ENV_PORT_TAKEN.md +23 -0
  68. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
  69. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_MISSING.md +23 -0
  70. package/dist/reference/errors/MOSTRA_ENV_SERVICE_FAILED.md +23 -0
  71. package/dist/reference/errors/MOSTRA_ENV_SHELL_MISSING.md +23 -0
  72. package/dist/reference/errors/MOSTRA_ENV_WARM_MISSING.md +23 -0
  73. package/dist/reference/errors/MOSTRA_FIELD_CONFLICT.md +23 -0
  74. package/dist/reference/errors/MOSTRA_FIELD_DUPLICATE_ID.md +23 -0
  75. package/dist/reference/errors/MOSTRA_FIELD_ID_INVALID.md +23 -0
  76. package/dist/reference/errors/MOSTRA_FIELD_ID_UNSTABLE.md +23 -0
  77. package/dist/reference/errors/MOSTRA_FIELD_MUTATION_ID_REUSED.md +23 -0
  78. package/dist/reference/errors/MOSTRA_FIELD_SHARED.md +23 -0
  79. package/dist/reference/errors/MOSTRA_FIELD_TOO_LARGE.md +23 -0
  80. package/dist/reference/errors/MOSTRA_FIELD_UNBOUND.md +23 -0
  81. package/dist/reference/errors/MOSTRA_HOME_DISK_FULL.md +23 -0
  82. package/dist/reference/errors/MOSTRA_HOME_GC_INCOMPLETE.md +23 -0
  83. package/dist/reference/errors/MOSTRA_HOME_GONE.md +23 -0
  84. package/dist/reference/errors/MOSTRA_HOME_INTEGRITY.md +23 -0
  85. package/dist/reference/errors/MOSTRA_HOME_LEDGER_UNREADABLE.md +23 -0
  86. package/dist/reference/errors/MOSTRA_HOME_LOCKED.md +23 -0
  87. package/dist/reference/errors/MOSTRA_HOME_MISMATCH.md +23 -0
  88. package/dist/reference/errors/MOSTRA_HOME_NETWORK_FILESYSTEM.md +23 -0
  89. package/dist/reference/errors/MOSTRA_HOME_NOT_ALWAYS_ON.md +23 -0
  90. package/dist/reference/errors/MOSTRA_HOME_NOT_OWNED.md +23 -0
  91. package/dist/reference/errors/MOSTRA_HOME_SOCKET_TOO_LONG.md +23 -0
  92. package/dist/reference/errors/MOSTRA_HOME_TOO_NEW.md +23 -0
  93. package/dist/reference/errors/MOSTRA_HOST_CONNECTION_CLOSED.md +23 -0
  94. package/dist/reference/errors/MOSTRA_HOST_CURSOR_COMPACTED.md +23 -0
  95. package/dist/reference/errors/MOSTRA_HOST_IDENTITY_UNAVAILABLE.md +23 -0
  96. package/dist/reference/errors/MOSTRA_HOST_INITIALIZE_ORDER.md +23 -0
  97. package/dist/reference/errors/MOSTRA_HOST_INTERNAL_ERROR.md +23 -0
  98. package/dist/reference/errors/MOSTRA_HOST_INVALID_PARAMS.md +23 -0
  99. package/dist/reference/errors/MOSTRA_HOST_MALFORMED.md +23 -0
  100. package/dist/reference/errors/MOSTRA_HOST_MESSAGE_TOO_LARGE.md +23 -0
  101. package/dist/reference/errors/MOSTRA_HOST_METHOD_UNKNOWN.md +23 -0
  102. package/dist/reference/errors/MOSTRA_HOST_NOTIFICATION_UNSUPPORTED.md +23 -0
  103. package/dist/reference/errors/MOSTRA_HOST_PORT_UNSUPPORTED.md +23 -0
  104. package/dist/reference/errors/MOSTRA_HOST_REQUEST_ID_REUSED.md +23 -0
  105. package/dist/reference/errors/MOSTRA_HOST_REVISION_UNSUPPORTED.md +23 -0
  106. package/dist/reference/errors/MOSTRA_HOST_SHUTDOWN_REFUSED.md +23 -0
  107. package/dist/reference/errors/MOSTRA_HOST_SUBSCRIPTION_UNKNOWN.md +23 -0
  108. package/dist/reference/errors/MOSTRA_HOST_TIMEOUT.md +23 -0
  109. package/dist/reference/errors/MOSTRA_HYGIENE_CONTENT_TYPE.md +23 -0
  110. package/dist/reference/errors/MOSTRA_HYGIENE_CSRF_MISSING.md +23 -0
  111. package/dist/reference/errors/MOSTRA_HYGIENE_FRAME_SESSION.md +23 -0
  112. package/dist/reference/errors/MOSTRA_HYGIENE_HEADERS_TOO_LARGE.md +23 -0
  113. package/dist/reference/errors/MOSTRA_HYGIENE_HOST_REFUSED.md +23 -0
  114. package/dist/reference/errors/MOSTRA_HYGIENE_NOT_SERVED.md +23 -0
  115. package/dist/reference/errors/MOSTRA_HYGIENE_ORIGIN_REFUSED.md +23 -0
  116. package/dist/reference/errors/MOSTRA_HYGIENE_RATE_LIMITED.md +23 -0
  117. package/dist/reference/errors/MOSTRA_HYGIENE_REQUEST_MALFORMED.md +23 -0
  118. package/dist/reference/errors/MOSTRA_HYGIENE_SCOPE_DENIED.md +23 -0
  119. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_CONFLICT.md +23 -0
  120. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_MISSING.md +23 -0
  121. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_INVALID.md +23 -0
  122. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_REVOKED.md +23 -0
  123. package/dist/reference/errors/MOSTRA_LIVE_SOURCE_FAILED.md +23 -0
  124. package/dist/reference/errors/MOSTRA_LIVE_TOO_LARGE.md +23 -0
  125. package/dist/reference/errors/MOSTRA_MANIFEST_INVALID.md +23 -0
  126. package/dist/reference/errors/MOSTRA_MANIFEST_NOT_LITERAL.md +23 -0
  127. package/dist/reference/errors/MOSTRA_MANIFEST_UNKNOWN_KEY.md +23 -0
  128. package/dist/reference/errors/MOSTRA_NETWORK_EXTERNAL_FAILED.md +23 -0
  129. package/dist/reference/errors/MOSTRA_NETWORK_REQUEST_FAILED.md +23 -0
  130. package/dist/reference/errors/MOSTRA_PLATFORM_UNSUPPORTED.md +23 -0
  131. package/dist/reference/errors/MOSTRA_PUBLISH_ID_CONFLICT.md +23 -0
  132. package/dist/reference/errors/MOSTRA_PUBLISH_SOURCE_CHANGED.md +23 -0
  133. package/dist/reference/errors/MOSTRA_PUBLISH_VERIFY_FAILED.md +23 -0
  134. package/dist/reference/errors/MOSTRA_REGRESSION_ACTION_REMOVED.md +23 -0
  135. package/dist/reference/errors/MOSTRA_REGRESSION_ARIA.md +23 -0
  136. package/dist/reference/errors/MOSTRA_REGRESSION_FIELD_REMOVED.md +23 -0
  137. package/dist/reference/errors/MOSTRA_REGRESSION_LIVE_REMOVED.md +23 -0
  138. package/dist/reference/errors/MOSTRA_REGRESSION_PAGE_REMOVED.md +23 -0
  139. package/dist/reference/errors/MOSTRA_REGRESSION_PIXELS.md +23 -0
  140. package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
  141. package/dist/reference/errors/MOSTRA_REMOTE_HOME_MOVING.md +23 -0
  142. package/dist/reference/errors/MOSTRA_REMOTE_HOME_SUSPENDED.md +23 -0
  143. package/dist/reference/errors/MOSTRA_REMOTE_LIMIT_REACHED.md +23 -0
  144. package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
  145. package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
  146. package/dist/reference/errors/MOSTRA_REMOTE_NO_INSTANCE.md +23 -0
  147. package/dist/reference/errors/MOSTRA_REMOTE_OPERATOR_UNAVAILABLE.md +23 -0
  148. package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
  149. package/dist/reference/errors/MOSTRA_REMOTE_PAUSED_BY_OPERATOR.md +23 -0
  150. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
  151. package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
  152. package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
  153. package/dist/reference/errors/MOSTRA_REMOTE_UNDER_REVIEW.md +23 -0
  154. package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
  155. package/dist/reference/errors/MOSTRA_RUNTIME_BLANK.md +23 -0
  156. package/dist/reference/errors/MOSTRA_RUNTIME_NOT_READY.md +23 -0
  157. package/dist/reference/errors/MOSTRA_RUNTIME_PAGE_ERROR.md +23 -0
  158. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_CRASHED.md +23 -0
  159. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_PARKED.md +23 -0
  160. package/dist/reference/errors/MOSTRA_SECRET_MISSING.md +23 -0
  161. package/dist/reference/errors/MOSTRA_SHARE_NOT_ENABLED.md +23 -0
  162. package/dist/reference/errors/MOSTRA_SHARE_NOT_FOUND.md +23 -0
  163. package/dist/reference/errors/MOSTRA_SHARE_PORTS_EXHAUSTED.md +23 -0
  164. package/dist/reference/errors/MOSTRA_SHARE_TOOL_MISSING.md +23 -0
  165. package/dist/reference/errors/MOSTRA_SHARE_TOOL_NOT_READY.md +23 -0
  166. package/dist/reference/errors/MOSTRA_SHARE_TTL_INVALID.md +23 -0
  167. package/dist/reference/errors/MOSTRA_SHARE_TUNNEL_FAILED.md +23 -0
  168. package/dist/reference/errors/MOSTRA_SMOKE_BUDGET.md +23 -0
  169. package/dist/reference/errors/MOSTRA_SMOKE_NO_EFFECT.md +23 -0
  170. package/dist/reference/errors/MOSTRA_SUBMIT_ALREADY.md +23 -0
  171. package/dist/reference/errors/MOSTRA_SUBMIT_BLOCKED.md +23 -0
  172. package/dist/reference/errors/MOSTRA_SUBMIT_CHANNEL_DENIED.md +23 -0
  173. package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +23 -0
  174. package/dist/reference/errors/MOSTRA_SUBMIT_PAUSED.md +23 -0
  175. package/dist/reference/errors/MOSTRA_SUBMIT_POLICY_NONE.md +23 -0
  176. package/dist/reference/errors/MOSTRA_SUBMIT_REVISION_MOVED.md +23 -0
  177. package/dist/reference/errors/MOSTRA_SUBMIT_SIGNAL_INVALID.md +23 -0
  178. package/dist/reference/errors/MOSTRA_SUBMIT_VIEW_INVALID.md +23 -0
  179. package/dist/reference/errors/MOSTRA_TARGET_UNAVAILABLE.md +23 -0
  180. package/dist/reference/errors/MOSTRA_TYPE_ERROR.md +23 -0
  181. package/dist/reference/errors/MOSTRA_TYPE_UNTYPED_PACKAGE.md +23 -0
  182. package/dist/reference/errors/MOSTRA_VERIFY_ACTION_SKIPPED.md +23 -0
  183. package/dist/reference/errors/MOSTRA_VERIFY_BASELINE_MISSING.md +23 -0
  184. package/dist/reference/errors/MOSTRA_VERIFY_CRASHED.md +23 -0
  185. package/dist/reference/errors/MOSTRA_VERIFY_LIVE_FAILED.md +23 -0
  186. package/dist/reference/errors/MOSTRA_VERIFY_NO_BASELINE.md +23 -0
  187. package/dist/reference/errors/MOSTRA_VERIFY_SECRET_MISSING.md +23 -0
  188. package/dist/reference/errors/MOSTRA_VERIFY_SKIP_CONSEQUENCE.md +23 -0
  189. package/dist/reference/errors/MOSTRA_VERIFY_TIMEOUT.md +23 -0
  190. package/dist/reference/self-hosting.md +130 -0
  191. package/dist/reference/telemetry.md +84 -0
  192. package/dist/skill/SKILL.md +122 -0
  193. package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
  194. package/dist/skill/assets/examples/dashboard/live.ts +25 -0
  195. package/dist/skill/assets/examples/dashboard/styles.css +125 -0
  196. package/dist/skill/assets/examples/decision/index.tsx +95 -0
  197. package/dist/skill/assets/examples/decision/styles.css +125 -0
  198. package/dist/skill/assets/examples/inbox/actions.ts +23 -0
  199. package/dist/skill/assets/examples/inbox/index.tsx +109 -0
  200. package/dist/skill/assets/examples/inbox/styles.css +125 -0
  201. package/dist/skill/assets/studio.css +125 -0
  202. package/dist/skill/references/answers.md +217 -0
  203. package/dist/skill/references/design.md +154 -0
  204. package/dist/skill/references/libraries.md +167 -0
  205. package/dist/skill/references/long-lived.md +148 -0
  206. package/dist/skill/references/mcp.md +68 -0
  207. package/dist/skill/references/page.md +131 -0
  208. package/dist/skill/references/server.md +146 -0
  209. package/dist/skill/references/sharing.md +123 -0
  210. package/dist/skill/references/verify.md +71 -0
  211. package/package.json +12 -5
  212. package/src/actions/index.ts +163 -10
  213. package/src/bin.ts +78 -1
  214. package/src/gateway/actions.ts +40 -4
  215. package/src/gateway/browser.ts +162 -95
  216. package/src/gateway/capabilities.ts +23 -6
  217. package/src/gateway/http.ts +12 -1
  218. package/src/gateway/index.ts +282 -20
  219. package/src/gateway/listener.ts +31 -6
  220. package/src/gateway/routes.ts +23 -7
  221. package/src/gc/index.ts +19 -0
  222. package/src/instance/index.ts +60 -2
  223. package/src/interaction/ephemeral.ts +32 -23
  224. package/src/interaction/events.ts +21 -1
  225. package/src/interaction/imports.ts +317 -0
  226. package/src/interaction/index.ts +228 -15
  227. package/src/interaction/outbox.ts +9 -0
  228. package/src/interaction/pause.ts +106 -0
  229. package/src/interaction/results.ts +8 -1
  230. package/src/interaction/runs.ts +52 -2
  231. package/src/interaction/submissions.ts +59 -2
  232. package/src/interaction/tally.ts +129 -0
  233. package/src/interaction/viewers.ts +34 -1
  234. package/src/ledger/index.ts +124 -10
  235. package/src/ledger/migrations.ts +234 -0
  236. package/src/ledger/types.ts +8 -0
  237. package/src/link/author.ts +215 -0
  238. package/src/link/binding.ts +289 -0
  239. package/src/link/hosted.ts +101 -0
  240. package/src/link/http.ts +141 -0
  241. package/src/link/index.ts +10 -0
  242. package/src/link/manager.ts +1489 -0
  243. package/src/link/relay.ts +512 -0
  244. package/src/live/index.ts +112 -2
  245. package/src/platform/filesystems.ts +78 -0
  246. package/src/platform/index.ts +1 -0
  247. package/src/protocol-server/client.ts +53 -0
  248. package/src/protocol-server/index.ts +19 -2
  249. package/src/protocol-server/server.ts +38 -7
  250. package/src/protocol-server/websocket.ts +161 -0
  251. package/src/publish/bundle.ts +398 -0
  252. package/src/publish/manifest.ts +9 -0
  253. package/src/publish/methods.ts +12 -1
  254. package/src/publish/publisher.ts +127 -0
  255. package/src/registry/index.ts +35 -14
  256. package/src/server/api.ts +881 -0
  257. package/src/server/auth.ts +1139 -0
  258. package/src/server/authorize.ts +816 -0
  259. package/src/server/clients.ts +235 -0
  260. package/src/server/config.ts +228 -0
  261. package/src/server/data.ts +427 -0
  262. package/src/server/directory.ts +210 -0
  263. package/src/server/feed.ts +191 -0
  264. package/src/server/handle.ts +172 -0
  265. package/src/server/hosted-pages.ts +532 -0
  266. package/src/server/hosted.ts +1323 -0
  267. package/src/server/index.ts +650 -0
  268. package/src/server/mcp.ts +330 -0
  269. package/src/server/metering.ts +156 -0
  270. package/src/server/oauth-clients.ts +510 -0
  271. package/src/server/operator.ts +498 -0
  272. package/src/server/providers.ts +284 -0
  273. package/src/server/relay.ts +1163 -0
  274. package/src/server/remove.ts +148 -0
  275. package/src/server/routing.ts +275 -0
  276. package/src/share/index.ts +110 -6
  277. package/src/verify/runner.ts +23 -2
  278. package/dist/directories-mJ1qlVht.js.map +0 -1
  279. package/dist/instance-EnaZPs14.js.map +0 -1
@@ -0,0 +1,881 @@
1
+ /**
2
+ * The remote server's API origin (INTERFACES §18.2, §18.5): the authorization server's device
3
+ * grant (`/oauth/device`, `/oauth/token`, `/oauth/revoke`, its metadata and the device page), the
4
+ * network binding (`/host`, JSON-RPC over WebSocket with a bearer token) and version files
5
+ * (`PUT /files/<sha256>`). Never on a user-content domain (D165 item 7).
6
+ */
7
+ import { createHash, randomBytes } from "node:crypto";
8
+ import { createWriteStream, existsSync, renameSync } from "node:fs";
9
+ import { rm } from "node:fs/promises";
10
+ import type { IncomingMessage, ServerResponse } from "node:http";
11
+ import { join } from "node:path";
12
+ import type { Duplex } from "node:stream";
13
+ import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
14
+ import type { CredentialResource } from "@mostra/protocol/operator";
15
+ import { type WebSocket, WebSocketServer } from "ws";
16
+ import type { Log } from "../log.ts";
17
+ import { BINDING_SUBPROTOCOL, MAX_FRAME_BYTES, serveWebSocket } from "../protocol-server/index.ts";
18
+ import type { Authenticated, Authorization } from "./auth.ts";
19
+ import type { Authorize } from "./authorize.ts";
20
+ import type { ClientAddresses, RateLimiter } from "./clients.ts";
21
+ import type { RemoteServerConfig } from "./config.ts";
22
+ import type { HostedHome } from "./hosted.ts";
23
+ import type { RemoteMcp } from "./mcp.ts";
24
+ import type { Clients } from "./oauth-clients.ts";
25
+ import type { Operator } from "./operator.ts";
26
+
27
+ /** How often an open binding's grant is checked again: a revocation closes it within 60 s. */
28
+ const GRANT_RECHECK_MS = 30_000;
29
+
30
+ /** How often the operator is asked again whether an account is suspended (`accounts.status`). */
31
+ const STATUS_RECHECK_MS = 30_000;
32
+
33
+ /** Dynamic Client Registrations an address may make a minute (D167). */
34
+ const REGISTRATIONS_PER_MINUTE = 10;
35
+
36
+ /** The largest version file accepted (per file; an operator's storage limit is WP-30's). */
37
+ const MAX_FILE_BYTES = 256 * 1024 * 1024;
38
+
39
+ const BASE_HEADERS = {
40
+ "cache-control": "no-store",
41
+ "cross-origin-resource-policy": "same-origin",
42
+ "referrer-policy": "no-referrer",
43
+ "x-content-type-options": "nosniff",
44
+ } as const;
45
+
46
+ function send(
47
+ response: ServerResponse,
48
+ status: number,
49
+ body: unknown,
50
+ headers: Record<string, string> = {},
51
+ ): void {
52
+ const text = JSON.stringify(body);
53
+ response.writeHead(status, {
54
+ ...BASE_HEADERS,
55
+ "content-type": "application/json; charset=utf-8",
56
+ "content-length": String(Buffer.byteLength(text)),
57
+ ...headers,
58
+ });
59
+ response.end(text);
60
+ }
61
+
62
+ function page(response: ServerResponse, status: number, html: string): void {
63
+ response.writeHead(status, {
64
+ ...BASE_HEADERS,
65
+ "content-type": "text/html; charset=utf-8",
66
+ "content-security-policy":
67
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
68
+ "x-frame-options": "DENY",
69
+ // The device page posts its own form, whose `Origin` the server checks: under `no-referrer`
70
+ // browsers send `Origin: null` for a form's POST, so this page sends origins to itself only.
71
+ "referrer-policy": "same-origin",
72
+ });
73
+ response.end(html);
74
+ }
75
+
76
+ async function readBody(request: IncomingMessage, limit: number): Promise<Buffer | undefined> {
77
+ const chunks: Buffer[] = [];
78
+ let size = 0;
79
+ for await (const chunk of request) {
80
+ size += (chunk as Buffer).length;
81
+ if (size > limit) return undefined;
82
+ chunks.push(chunk as Buffer);
83
+ }
84
+ return Buffer.concat(chunks);
85
+ }
86
+
87
+ function escapeHtml(text: string): string {
88
+ return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
89
+ }
90
+
91
+ /** Options for {@link createApi}. */
92
+ export interface ApiOptions {
93
+ readonly config: RemoteServerConfig;
94
+ readonly auth: Authorization;
95
+ readonly log: Log;
96
+ readonly filesDir: string;
97
+ /** The hosted home an account's token names, opened on demand. */
98
+ readonly home: (homeId: string) => Promise<HostedHome>;
99
+ /** Notes a home was used, so it isn't closed while used. */
100
+ readonly touch: (homeId: string) => void;
101
+ /** Told each message a home's binding carried in (relay and sync traffic), for metering. */
102
+ readonly message?: (homeId: string) => void;
103
+ /** Told the bytes a home stored (an upload it hadn't stored before), for metering. */
104
+ readonly stored?: (homeId: string, bytes: number) => void;
105
+ /** The remote MCP endpoint (`/mcp`, INTERFACES §18.8). */
106
+ readonly mcp?: RemoteMcp;
107
+ /** The authorization server's browser pages (sign-in, consent, viewer sign-in). */
108
+ readonly authorize: Authorize;
109
+ /** Its clients, for Dynamic Client Registration. */
110
+ readonly clients: Clients;
111
+ /**
112
+ * Where a request comes from, and the rate its registrations count against (D167): Dynamic
113
+ * Client Registration takes no credential, so each address may register a few clients a minute.
114
+ */
115
+ readonly registrations?: {
116
+ readonly addresses: ClientAddresses;
117
+ readonly rates: RateLimiter;
118
+ };
119
+ /** The operator module: its `accounts.authenticate` admits credentials it issued. */
120
+ readonly operator?: Operator;
121
+ /** Whether the operator suspended a home: its bindings and uploads are refused (D165 item 9). */
122
+ readonly suspended?: (homeId: string) => boolean;
123
+ /** How often an open binding's token and grant are checked; tests shorten it. */
124
+ readonly recheckMs?: number;
125
+ }
126
+
127
+ /** The API origin's request and upgrade handlers. */
128
+ export interface Api {
129
+ request(request: IncomingMessage, response: ServerResponse, path: string): Promise<void>;
130
+ upgrade(request: IncomingMessage, socket: Duplex, head: Buffer, path: string): void;
131
+ /** Closes every binding of a home now (a suspension or a move, 4403). */
132
+ closeHome(homeId: string): void;
133
+ close(): void;
134
+ }
135
+
136
+ /** The development identity provider, when the configuration names one (§18.5, WP-29). */
137
+ function developmentProvider(
138
+ config: RemoteServerConfig,
139
+ ): { id: string; label: string } | undefined {
140
+ const provider = config.identityProviders?.find((candidate) => candidate.kind === "development");
141
+ return provider ? { id: provider.id, label: provider.label ?? "Development sign-in" } : undefined;
142
+ }
143
+
144
+ /** The device page: the code, the warning, and the development provider's sign-in. */
145
+ function devicePage(options: {
146
+ readonly code: string;
147
+ readonly provider: { id: string; label: string } | undefined;
148
+ readonly message?: string;
149
+ readonly done?: boolean;
150
+ }): string {
151
+ const body = options.done
152
+ ? `<p>${escapeHtml(options.message ?? "Done.")}</p><p>You can close this page.</p>`
153
+ : `${options.message ? `<p role="alert">${escapeHtml(options.message)}</p>` : ""}
154
+ <p><strong>Approving links a machine to your account.</strong> That machine's Mostra can then host
155
+ pages under your account and receives their answers. Continue only if you started this sign-in
156
+ yourself, on that machine.</p>
157
+ ${
158
+ options.provider
159
+ ? `<form method="post" action="/device">
160
+ <label>Code <input name="user_code" value="${escapeHtml(options.code)}" autocomplete="off" required></label>
161
+ <p>${escapeHtml(options.provider.label)}: this server signs people in with a development provider,
162
+ which trusts the name you type. Use it only on a server you run for yourself or for tests.</p>
163
+ <label>Your name <input name="name" required maxlength="64"></label>
164
+ <input type="hidden" name="provider" value="${escapeHtml(options.provider.id)}">
165
+ <p><button name="decision" value="approve">Approve this machine</button>
166
+ <button name="decision" value="deny">Refuse</button></p>
167
+ </form>`
168
+ : "<p>This server has no identity provider configured, so nobody can sign in yet.</p>"
169
+ }`;
170
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="robots" content="noindex">
171
+ <meta name="viewport" content="width=device-width, initial-scale=1"><title>Link a machine to Mostra</title>
172
+ <style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
173
+ input{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>
174
+ <body><h1>Link a machine to Mostra</h1>${body}</body></html>`;
175
+ }
176
+
177
+ /** The device page for a browser already signed in: approving links a machine (§18.5). */
178
+ function deviceApproval(options: {
179
+ readonly code: string;
180
+ readonly name: string;
181
+ readonly csrf: string;
182
+ }): string {
183
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="robots" content="noindex">
184
+ <meta name="viewport" content="width=device-width, initial-scale=1"><title>Link a machine to Mostra</title>
185
+ <style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}
186
+ input{font:inherit;padding:.3rem}button{font:inherit;padding:.4rem .9rem;margin-right:.5rem}</style></head>
187
+ <body><h1>Link a machine to Mostra</h1>
188
+ <p><strong>Approving links a machine to your account, ${escapeHtml(options.name)}.</strong> That machine's
189
+ Mostra can then host pages under your account and receives their answers. Continue only if you started
190
+ this sign-in yourself, on that machine.</p>
191
+ <form method="post" action="/device"><input type="hidden" name="csrf" value="${escapeHtml(options.csrf)}">
192
+ <label>Code <input name="user_code" value="${escapeHtml(options.code)}" autocomplete="off" required></label>
193
+ <p><button name="session_decision" value="approve">Approve this machine</button>
194
+ <button name="session_decision" value="deny">Refuse</button></p></form></body></html>`;
195
+ }
196
+
197
+ /** Creates the API origin. */
198
+ export function createApi(options: ApiOptions): Api {
199
+ const { config, auth, log } = options;
200
+ const apiOrigin = config.apiOrigin;
201
+ const sockets = new WebSocketServer({
202
+ noServer: true,
203
+ maxPayload: MAX_FRAME_BYTES,
204
+ perMessageDeflate: false,
205
+ handleProtocols: (protocols) =>
206
+ protocols.has(BINDING_SUBPROTOCOL) ? BINDING_SUBPROTOCOL : false,
207
+ });
208
+ const bindings = new Set<WebSocket>();
209
+ const bindingHomes = new Map<WebSocket, string>();
210
+
211
+ /**
212
+ * Whether the device page offers the development provider's form (D166 item 4): only while it is
213
+ * the one provider a sign-in may use now, none other configured and none the operator supplies.
214
+ * The page's GET and its POST judge by this one rule.
215
+ */
216
+ const devFormOffered = async (): Promise<boolean> => {
217
+ const development = developmentProvider(config);
218
+ if (development === undefined) return false;
219
+ const offered = await options.authorize.providers();
220
+ return offered.length === 1 && offered[0]?.id === development.id;
221
+ };
222
+
223
+ /**
224
+ * The operator's word on accounts (`accounts.status`, §18.6), asked at most every 30 s per
225
+ * account and written into the directory, so a suspension reaches every grant: its refreshes, its
226
+ * bindings, its MCP calls (Fable review of WP-30, 6). An operator that doesn't answer leaves the
227
+ * last word standing.
228
+ */
229
+ const statusAsked = new Map<string, number>();
230
+ const accountStanding = async (accountId: string): Promise<"active" | "suspended"> => {
231
+ if (options.operator?.has.status === true) {
232
+ const last = statusAsked.get(accountId);
233
+ const every = Math.min(STATUS_RECHECK_MS, options.recheckMs ?? STATUS_RECHECK_MS);
234
+ if (last === undefined || Date.now() - last >= every) {
235
+ statusAsked.set(accountId, Date.now());
236
+ if (statusAsked.size > 10_000)
237
+ statusAsked.delete(statusAsked.keys().next().value as string);
238
+ const said = await options.operator.status(accountId);
239
+ if (said !== undefined) auth.setAccountStatus(accountId, said);
240
+ }
241
+ }
242
+ return auth.accountStatus(accountId);
243
+ };
244
+
245
+ /**
246
+ * Whether an authenticated caller may act now: its home not suspended by the operator, its
247
+ * account not suspended (D165 item 9). One place for `/host`, `/files`, `/mcp` and `/link`
248
+ * (Fable review of WP-30, 1).
249
+ */
250
+ const standing = async (who: Authenticated): Promise<Diagnostic | undefined> => {
251
+ if (options.suspended?.(who.homeId) || (await accountStanding(who.accountId)) === "suspended") {
252
+ return createDiagnostic("MOSTRA_REMOTE_HOME_SUSPENDED", {
253
+ message: "This account's pages are suspended by the server's operator.",
254
+ });
255
+ }
256
+ return undefined;
257
+ };
258
+
259
+ /**
260
+ * The account a bearer token names for one resource (`host`, `files` or `mcp`): a token this
261
+ * server issued for exactly that audience (RFC 8707; a token for `/mcp` opens no binding), or a
262
+ * credential the operator issued (`accounts.authenticate`, §18.6); or why it may not act now.
263
+ */
264
+ const bearer = async (
265
+ request: IncomingMessage,
266
+ resource: CredentialResource,
267
+ ): Promise<Authenticated | { readonly refused: Diagnostic } | undefined> => {
268
+ const header = request.headers.authorization ?? "";
269
+ const match = /^bearer\s+(\S+)$/i.exec(header);
270
+ if (!match) return undefined;
271
+ const token = match[1] as string;
272
+ const audience = `${apiOrigin}/${resource === "files" ? "host" : resource}`;
273
+ const issued = auth.authenticate(token);
274
+ let who: Authenticated | undefined;
275
+ if (issued) {
276
+ if (issued.resource !== audience) return undefined;
277
+ who = issued;
278
+ } else {
279
+ if (!options.operator?.has.authenticate) return undefined;
280
+ const credential = await options.operator.authenticate(token, resource);
281
+ if (!credential?.scope.includes("mostra")) return undefined;
282
+ who = auth.credentialSession({
283
+ account: credential.account,
284
+ subject: credential.subject ?? "default",
285
+ resource: audience,
286
+ // Only the binding links an instance; a key used on /mcp or /files names none.
287
+ link: resource === "host",
288
+ });
289
+ }
290
+ const refused = await standing(who);
291
+ return refused ? { refused } : who;
292
+ };
293
+
294
+ const unauthorized = (response: ServerResponse, message: string): void =>
295
+ send(
296
+ response,
297
+ 401,
298
+ { code: "MOSTRA_REMOTE_LOGIN_FAILED", message },
299
+ {
300
+ "www-authenticate": `Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"`,
301
+ },
302
+ );
303
+
304
+ /**
305
+ * RFC 8414 metadata (INTERFACES §18.5): Client ID Metadata Documents with `none` among the token
306
+ * endpoint's methods, which Claude needs before it uses one, Dynamic Client Registration as the
307
+ * fallback, PKCE S256, `iss` in responses, and `offline_access` for rotating refresh tokens.
308
+ */
309
+ const metadata = () => ({
310
+ issuer: apiOrigin,
311
+ authorization_endpoint: `${apiOrigin}/oauth/authorize`,
312
+ token_endpoint: `${apiOrigin}/oauth/token`,
313
+ registration_endpoint: `${apiOrigin}/oauth/register`,
314
+ device_authorization_endpoint: `${apiOrigin}/oauth/device`,
315
+ revocation_endpoint: `${apiOrigin}/oauth/revoke`,
316
+ response_types_supported: ["code"],
317
+ response_modes_supported: ["query"],
318
+ grant_types_supported: [
319
+ "authorization_code",
320
+ "refresh_token",
321
+ "urn:ietf:params:oauth:grant-type:device_code",
322
+ ],
323
+ token_endpoint_auth_methods_supported: ["none"],
324
+ revocation_endpoint_auth_methods_supported: ["none"],
325
+ code_challenge_methods_supported: ["S256"],
326
+ scopes_supported: ["mostra", "offline_access"],
327
+ client_id_metadata_document_supported: true,
328
+ authorization_response_iss_parameter_supported: true,
329
+ });
330
+
331
+ const sessionDevicePage = (code: string, signed: { accountId: string; hash: string }): string =>
332
+ deviceApproval({
333
+ code,
334
+ name: auth.accountName(signed.accountId).name ?? "your account",
335
+ csrf: options.authorize.csrf(signed.hash, "device"),
336
+ });
337
+
338
+ const form = async (request: IncomingMessage): Promise<URLSearchParams | undefined> => {
339
+ const type = request.headers["content-type"] ?? "";
340
+ if (!type.startsWith("application/x-www-form-urlencoded")) return undefined;
341
+ const body = await readBody(request, 64 * 1024);
342
+ return body === undefined ? undefined : new URLSearchParams(body.toString("utf8"));
343
+ };
344
+
345
+ const upload = async (
346
+ request: IncomingMessage,
347
+ response: ServerResponse,
348
+ sha: string,
349
+ ): Promise<void> => {
350
+ const who = await bearer(request, "files");
351
+ if (!who) {
352
+ unauthorized(response, "Version files need the binding's access token.");
353
+ return;
354
+ }
355
+ if ("refused" in who) {
356
+ send(response, 403, who.refused);
357
+ return;
358
+ }
359
+ const home = await options.home(who.homeId);
360
+ options.touch(who.homeId);
361
+ // A file is accepted only for a pending push of this home that names it as missing, so no
362
+ // home stores bytes nobody asked for, nor learns what another home holds (§18.2).
363
+ const declared = home.wanted(sha);
364
+ if (declared === undefined) {
365
+ send(response, 409, {
366
+ code: "MOSTRA_HOME_INTEGRITY",
367
+ message: "No pending push of this home names that file as missing.",
368
+ });
369
+ return;
370
+ }
371
+ /** Refuses the upload and closes its connection once the answer is out: the rest isn't read. */
372
+ const refuseUpload = (status: number, message: string): void => {
373
+ response.once("finish", () => request.destroy());
374
+ send(response, status, { code: "MOSTRA_HOME_INTEGRITY", message }, { connection: "close" });
375
+ };
376
+ const sizeMessage = "The file's bytes aren't the size its push gave them.";
377
+ // A body announced at another size than its push gave is refused before any byte is read.
378
+ const announced = request.headers["content-length"];
379
+ if (announced !== undefined && Number(announced) !== declared) {
380
+ refuseUpload(declared > MAX_FILE_BYTES ? 413 : 400, sizeMessage);
381
+ return;
382
+ }
383
+ const target = join(options.filesDir, sha);
384
+ const scratch = join(options.filesDir, `.upload-${randomBytes(8).toString("hex")}`);
385
+ const hash = createHash("sha256");
386
+ let size = 0;
387
+ let tooLarge = false;
388
+ await new Promise<void>((resolve, reject) => {
389
+ const out = createWriteStream(scratch, { mode: 0o600 });
390
+ const onData = (chunk: Buffer): void => {
391
+ size += chunk.length;
392
+ // Past the size its push gave it, or the cap: no more of it is read.
393
+ if (size > MAX_FILE_BYTES || size > declared) {
394
+ tooLarge = true;
395
+ request.off("data", onData);
396
+ request.pause();
397
+ out.end(() => resolve());
398
+ return;
399
+ }
400
+ hash.update(chunk);
401
+ out.write(chunk);
402
+ };
403
+ request.on("data", onData);
404
+ request.on("end", () => {
405
+ if (!tooLarge) out.end(() => resolve());
406
+ });
407
+ request.on("error", reject);
408
+ request.on("close", () => out.end(() => resolve()));
409
+ }).catch(() => undefined);
410
+ const shortOrLong = !tooLarge && size !== declared;
411
+ if (tooLarge || shortOrLong || hash.digest("hex") !== sha) {
412
+ await rm(scratch, { force: true });
413
+ refuseUpload(
414
+ tooLarge && size > MAX_FILE_BYTES ? 413 : 400,
415
+ tooLarge || shortOrLong ? sizeMessage : "The bytes don't hash to the file's name.",
416
+ );
417
+ return;
418
+ }
419
+ if (existsSync(target)) await rm(scratch, { force: true });
420
+ else renameSync(scratch, target);
421
+ home.uploaded(sha);
422
+ options.stored?.(who.homeId, size);
423
+ send(response, 201, { sha256: sha, size });
424
+ };
425
+
426
+ return {
427
+ async request(request, response, path) {
428
+ const method = request.method ?? "GET";
429
+ if (method === "GET" && path === "/.well-known/oauth-authorization-server") {
430
+ send(response, 200, metadata());
431
+ return;
432
+ }
433
+ if (await options.authorize.handle(request, response, path)) return;
434
+ if (method === "GET" && path === "/.well-known/oauth-protected-resource/mcp") {
435
+ send(response, 200, {
436
+ resource: `${apiOrigin}/mcp`,
437
+ authorization_servers: [apiOrigin],
438
+ scopes_supported: ["mostra"],
439
+ bearer_methods_supported: ["header"],
440
+ resource_name: "Mostra",
441
+ });
442
+ return;
443
+ }
444
+ if (method === "POST" && path === "/link") {
445
+ // What a binding's credential links (D167): the account, the instance link it binds and
446
+ // whether that instance is the account's default; `default=1` makes it so. A person's
447
+ // device-grant token and an operator-issued key alike, for the binding's own resource.
448
+ const who = await bearer(request, "host");
449
+ if (who && "refused" in who) {
450
+ send(response, 403, who.refused);
451
+ return;
452
+ }
453
+ if (!who || who.linkId === undefined) {
454
+ unauthorized(response, "This credential links no instance on this server.");
455
+ return;
456
+ }
457
+ const body = await form(request);
458
+ const linked = auth.linkState(who.linkId, body?.get("default") === "1");
459
+ send(response, 200, {
460
+ account: {
461
+ id: who.accountId,
462
+ ...(who.accountName !== undefined ? { name: who.accountName } : {}),
463
+ },
464
+ instanceId: who.linkId,
465
+ default: linked.default,
466
+ });
467
+ return;
468
+ }
469
+ if (method === "POST" && path === "/oauth/register") {
470
+ // Dynamic Client Registration (RFC 7591): JSON in, the client's record out.
471
+ if (!(request.headers["content-type"] ?? "").startsWith("application/json")) {
472
+ send(response, 400, {
473
+ error: "invalid_client_metadata",
474
+ error_description: "Send JSON.",
475
+ });
476
+ return;
477
+ }
478
+ const body = await readBody(request, 64 * 1024);
479
+ let metadata: unknown;
480
+ try {
481
+ metadata = JSON.parse(body?.toString("utf8") ?? "");
482
+ } catch {
483
+ send(response, 400, {
484
+ error: "invalid_client_metadata",
485
+ error_description: "Send JSON.",
486
+ });
487
+ return;
488
+ }
489
+ // A registration takes no credential: an address registers a few a minute, so nobody fills
490
+ // the directory with clients (each is removed after 30 days unused).
491
+ if (options.registrations) {
492
+ const { addresses, rates } = options.registrations;
493
+ const taken = rates.take(`register:${addresses.keyOf(addresses.of(request))}`, {
494
+ count: REGISTRATIONS_PER_MINUTE,
495
+ perMs: 60_000,
496
+ });
497
+ if (!taken.ok) {
498
+ send(
499
+ response,
500
+ 429,
501
+ {
502
+ error: "slow_down",
503
+ error_description: "Too many registrations from this address; try again shortly.",
504
+ },
505
+ { "retry-after": String(taken.retryAfterS) },
506
+ );
507
+ return;
508
+ }
509
+ }
510
+ const registered = options.clients.register(metadata);
511
+ if ("error" in registered && "description" in registered) {
512
+ send(response, 400, {
513
+ error: registered["error"],
514
+ error_description: registered["description"],
515
+ });
516
+ return;
517
+ }
518
+ send(response, 201, registered);
519
+ return;
520
+ }
521
+ if (method === "GET" && path === "/.well-known/oauth-protected-resource/host") {
522
+ send(response, 200, {
523
+ resource: `${apiOrigin}/host`,
524
+ authorization_servers: [apiOrigin],
525
+ scopes_supported: ["mostra"],
526
+ });
527
+ return;
528
+ }
529
+ if (method === "POST" && path === "/oauth/device") {
530
+ const body = await form(request);
531
+ if (!body) {
532
+ send(response, 400, { error: "invalid_request", error_description: "Send a form." });
533
+ return;
534
+ }
535
+ const answer = auth.device(body);
536
+ if ("error" in answer && typeof answer["status"] === "number") {
537
+ const failed = answer as unknown as {
538
+ status: number;
539
+ error: string;
540
+ description: string;
541
+ };
542
+ send(response, failed.status, {
543
+ error: failed.error,
544
+ error_description: failed.description,
545
+ });
546
+ return;
547
+ }
548
+ send(response, 200, answer);
549
+ return;
550
+ }
551
+ if (method === "POST" && path === "/oauth/token") {
552
+ const body = await form(request);
553
+ if (!body) {
554
+ send(response, 400, { error: "invalid_request", error_description: "Send a form." });
555
+ return;
556
+ }
557
+ // A refresh asks the operator's word on its account first: a suspended account refreshes
558
+ // nothing, and one the operator lifted refreshes again (`accounts.status`, §18.6).
559
+ if (body.get("grant_type") === "refresh_token") {
560
+ const account = auth.refreshAccount(body.get("refresh_token") ?? "");
561
+ if (account !== undefined) await accountStanding(account);
562
+ }
563
+ const answer = auth.token(body);
564
+ if ("error" in answer) {
565
+ send(response, answer.status, {
566
+ error: answer.error,
567
+ error_description: answer.description,
568
+ });
569
+ return;
570
+ }
571
+ send(response, 200, answer);
572
+ return;
573
+ }
574
+ if (method === "POST" && path === "/oauth/revoke") {
575
+ const body = await form(request);
576
+ if (body) auth.revoke(body);
577
+ send(response, 200, {});
578
+ return;
579
+ }
580
+ if (path === "/device") {
581
+ const provider = developmentProvider(config);
582
+ const signed = options.authorize.sessionAccount(request);
583
+ if (method === "GET") {
584
+ const code = new URL(request.url ?? "/", apiOrigin).searchParams.get("user_code") ?? "";
585
+ if (signed) {
586
+ page(response, 200, sessionDevicePage(code, signed));
587
+ return;
588
+ }
589
+ // Real providers sign the person in first; the development one asks on this page, when it
590
+ // is the only one: none other configured, and no operator that supplies its own (D167).
591
+ if (!(await devFormOffered())) {
592
+ await options.authorize.signInPage(
593
+ response,
594
+ `/device?user_code=${encodeURIComponent(code)}`,
595
+ );
596
+ return;
597
+ }
598
+ page(response, 200, devicePage({ code, provider }));
599
+ return;
600
+ }
601
+ // The body is read once, for either form.
602
+ let posted: URLSearchParams | undefined;
603
+ if (method === "POST" && signed && request.headers.origin === apiOrigin) {
604
+ const body = await form(request);
605
+ posted = body;
606
+ const decision = body?.get("session_decision");
607
+ if (body && decision !== null && decision !== undefined) {
608
+ const code = body.get("user_code") ?? "";
609
+ if (body.get("csrf") !== options.authorize.csrf(signed.hash, "device")) {
610
+ page(
611
+ response,
612
+ 403,
613
+ devicePage({
614
+ code: "",
615
+ provider,
616
+ message: "This form must be sent from this page.",
617
+ }),
618
+ );
619
+ return;
620
+ }
621
+ const approve = decision === "approve";
622
+ const decided = auth.decideFor({ code, approve, accountId: signed.accountId });
623
+ page(
624
+ response,
625
+ decided.ok ? 200 : 400,
626
+ devicePage({
627
+ code,
628
+ provider,
629
+ ...(decided.ok
630
+ ? {
631
+ done: true,
632
+ message: approve
633
+ ? "The machine is linked to your account."
634
+ : "The sign-in was refused.",
635
+ }
636
+ : { message: decided.reason }),
637
+ }),
638
+ );
639
+ return;
640
+ }
641
+ }
642
+ if (method === "POST") {
643
+ // The page's own form only: a cross-site form post approves nothing.
644
+ if (request.headers.origin !== apiOrigin) {
645
+ page(
646
+ response,
647
+ 403,
648
+ devicePage({ code: "", provider, message: "This form must be sent from this page." }),
649
+ );
650
+ return;
651
+ }
652
+ const body = posted ?? (await form(request));
653
+ const code = body?.get("user_code") ?? "";
654
+ const name = (body?.get("name") ?? "").trim().slice(0, 64);
655
+ // Only where the page offers the development form: a server with real providers, or an
656
+ // operator's, signs people in through them alone (Fable review of WP-30, 5).
657
+ if (
658
+ !body ||
659
+ !provider ||
660
+ !(await devFormOffered()) ||
661
+ body.get("provider") !== provider.id ||
662
+ name === ""
663
+ ) {
664
+ page(
665
+ response,
666
+ 400,
667
+ devicePage({ code, provider, message: "Enter the code and your name." }),
668
+ );
669
+ return;
670
+ }
671
+ const approve = body.get("decision") === "approve";
672
+ // The code first, read only: a made-up code resolves nobody, makes no account and asks
673
+ // the operator nothing (second Fable review of WP-30, 5).
674
+ const pending = auth.pendingCode(code);
675
+ if (!pending.ok) {
676
+ page(response, 400, devicePage({ code, provider, message: pending.reason }));
677
+ return;
678
+ }
679
+ // The typed name is an identity like any provider's: the operator's `accounts.resolve`
680
+ // decides its account, its refusals, suspensions and first steps (D165 item 9).
681
+ const identity = { provider: provider.id, subject: name.toLowerCase(), name };
682
+ let decided: { readonly ok: true } | { readonly ok: false; readonly reason: string };
683
+ if (!approve) decided = auth.decide({ code, approve: false, identity });
684
+ else {
685
+ const account = await auth.resolveAccount(identity, 0);
686
+ if (account.kind !== "account") {
687
+ const reason =
688
+ account.kind === "unavailable"
689
+ ? "Sign-in is unavailable for a moment; try again shortly."
690
+ : account.kind === "refused"
691
+ ? account.message
692
+ : account.kind === "suspended"
693
+ ? "This account is suspended."
694
+ : "This server asks for a step before a first sign-in, which the development sign-in can't take.";
695
+ page(
696
+ response,
697
+ account.kind === "unavailable" ? 503 : 403,
698
+ devicePage({ code, provider, message: reason }),
699
+ );
700
+ return;
701
+ }
702
+ decided = auth.decideFor({ code, approve: true, accountId: account.accountId });
703
+ }
704
+ if (!decided.ok) {
705
+ page(response, 400, devicePage({ code, provider, message: decided.reason }));
706
+ return;
707
+ }
708
+ page(
709
+ response,
710
+ 200,
711
+ devicePage({
712
+ code,
713
+ provider,
714
+ done: true,
715
+ message: approve
716
+ ? "The machine is linked to your account."
717
+ : "The sign-in was refused.",
718
+ }),
719
+ );
720
+ return;
721
+ }
722
+ }
723
+ if (path === "/mcp" && options.mcp) {
724
+ const who = await bearer(request, "mcp");
725
+ const challenge = `Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/mcp"`;
726
+ if (!who) {
727
+ // A 401 with resource_metadata is how an MCP client finds the authorization server
728
+ // (RFC 9728; Claude starts sign-in only from it).
729
+ send(
730
+ response,
731
+ 401,
732
+ { error: "invalid_token", error_description: "Sign in to use Mostra here." },
733
+ { "www-authenticate": challenge },
734
+ );
735
+ return;
736
+ }
737
+ if ("refused" in who) {
738
+ send(response, 403, who.refused);
739
+ return;
740
+ }
741
+ if (!who.scope.split(" ").includes("mostra")) {
742
+ send(
743
+ response,
744
+ 403,
745
+ { error: "insufficient_scope", error_description: "The token lacks the mostra scope." },
746
+ { "www-authenticate": `${challenge}, error="insufficient_scope", scope="mostra"` },
747
+ );
748
+ return;
749
+ }
750
+ await options.mcp.handle(request, response, who);
751
+ return;
752
+ }
753
+ const file = /^\/files\/([0-9a-f]{64})$/.exec(path);
754
+ if (file && method === "PUT") {
755
+ await upload(request, response, file[1] as string);
756
+ return;
757
+ }
758
+ send(response, 404, {
759
+ code: "MOSTRA_HYGIENE_NOT_SERVED",
760
+ message: "Nothing is served at this path.",
761
+ });
762
+ },
763
+
764
+ upgrade(request, socket, head, path) {
765
+ const refuse = (status: number, text: string, extra = ""): void => {
766
+ socket.end(
767
+ `HTTP/1.1 ${status} ${text}\r\nconnection: close\r\ncontent-length: 0\r\n${extra}\r\n`,
768
+ );
769
+ };
770
+ if (path !== "/host") {
771
+ refuse(404, "Not Found");
772
+ return;
773
+ }
774
+ void bearer(request, "host").then(
775
+ (who) => upgradeFor(who),
776
+ (error: unknown) => {
777
+ log.error("binding.auth_failed", { error });
778
+ refuse(503, "Service Unavailable");
779
+ },
780
+ );
781
+ const upgradeFor = (
782
+ who: Authenticated | { readonly refused: Diagnostic } | undefined,
783
+ ): void => {
784
+ if (who && "refused" in who) {
785
+ refuse(403, "Forbidden");
786
+ return;
787
+ }
788
+ if (!who) {
789
+ refuse(
790
+ 401,
791
+ "Unauthorized",
792
+ `www-authenticate: Bearer resource_metadata="${apiOrigin}/.well-known/oauth-protected-resource/host"\r\n`,
793
+ );
794
+ return;
795
+ }
796
+ void options.home(who.homeId).then(
797
+ (home) => {
798
+ sockets.handleUpgrade(request, socket, head, (ws) => {
799
+ bindings.add(ws);
800
+ bindingHomes.set(ws, who.homeId);
801
+ let expiresAt = who.expiresAt;
802
+ const attributes = {
803
+ accountId: who.accountId,
804
+ grantId: who.grantId,
805
+ homeId: who.homeId,
806
+ linkId: who.linkId,
807
+ replaceToken: (next: number) => {
808
+ expiresAt = next;
809
+ },
810
+ };
811
+ // The binding ends at its token's expiry unless refreshed in band (`remote/token`), and
812
+ // within 60 s of the grant's revocation or the account's suspension (§18.2).
813
+ const watch = setInterval(
814
+ () => {
815
+ if (Date.now() >= expiresAt) {
816
+ log.info("binding.token_expired", { home: who.homeId });
817
+ ws.close(4401, "token expired");
818
+ } else if (who.grantId.startsWith("credential:")) {
819
+ // An operator's credential: the operator is asked again; a key it revoked, or
820
+ // an account it suspended, closes the binding within the bound.
821
+ void bearer(request, "host").then(
822
+ (still) => {
823
+ if (!still || "refused" in still) {
824
+ log.info("binding.credential_revoked", { home: who.homeId });
825
+ ws.close(4403, "credential revoked");
826
+ } else expiresAt = still.expiresAt;
827
+ },
828
+ () => undefined,
829
+ );
830
+ } else if (!auth.grantLive(who.grantId)) {
831
+ log.info("binding.grant_revoked", { home: who.homeId });
832
+ ws.close(4403, "grant revoked");
833
+ } else {
834
+ // The operator may have suspended the account since: asked within the bound.
835
+ void standing(who).then(
836
+ (refused) => {
837
+ if (refused) {
838
+ log.info("binding.account_suspended", { home: who.homeId });
839
+ ws.close(4403, "account suspended");
840
+ }
841
+ },
842
+ () => undefined,
843
+ );
844
+ }
845
+ },
846
+ Math.min(GRANT_RECHECK_MS, options.recheckMs ?? GRANT_RECHECK_MS),
847
+ );
848
+ watch.unref();
849
+ ws.once("close", () => {
850
+ clearInterval(watch);
851
+ bindings.delete(ws);
852
+ bindingHomes.delete(ws);
853
+ });
854
+ ws.on("message", () => {
855
+ options.touch(who.homeId);
856
+ options.message?.(who.homeId);
857
+ });
858
+ serveWebSocket(home.protocol, ws, { attributes, log });
859
+ log.info("binding.opened", { home: who.homeId, link: who.linkId });
860
+ });
861
+ },
862
+ (error: unknown) => {
863
+ log.error("binding.home_failed", { home: who.homeId, error });
864
+ refuse(503, "Service Unavailable");
865
+ },
866
+ );
867
+ };
868
+ },
869
+
870
+ closeHome(homeId) {
871
+ for (const [ws, home] of bindingHomes) {
872
+ if (home === homeId) ws.close(4403, "home unavailable");
873
+ }
874
+ },
875
+
876
+ close() {
877
+ for (const ws of bindings) ws.terminate();
878
+ sockets.close();
879
+ },
880
+ };
881
+ }