@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
@@ -11,6 +11,8 @@
11
11
  * await server.close();
12
12
  * ```
13
13
  */
14
+
15
+ import { readFileSync } from "node:fs";
14
16
  import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
15
17
  import type { AddressInfo } from "node:net";
16
18
  import { join } from "node:path";
@@ -24,15 +26,32 @@ import {
24
26
  RouteId,
25
27
  RpcError,
26
28
  } from "@mostra/protocol";
27
- import { locateShell, shellAssetResponse } from "../gateway/index.ts";
29
+ import { faultsFrom } from "../faults.ts";
30
+ import {
31
+ BASE_HEADERS,
32
+ documentHeaders,
33
+ locateShell,
34
+ resetOnClose,
35
+ shellAssetResponse,
36
+ } from "../gateway/index.ts";
28
37
  import { appendEvent } from "../interaction/index.ts";
29
38
  import type { LedgerOwner } from "../ledger/index.ts";
30
39
  import type { Environment, Log } from "../log.ts";
31
40
  import { type Api, createApi } from "./api.ts";
32
41
  import { type Authorization, createAuthorization } from "./auth.ts";
42
+ import { type Authorize, createAuthorize } from "./authorize.ts";
43
+ import { clientAddresses, RateLimiter } from "./clients.ts";
33
44
  import type { RemoteServerConfig } from "./config.ts";
34
45
  import { type DataDirectory, type HomeAssembler, openDataDirectory } from "./data.ts";
35
- import { type HostedHome, openHostedHome } from "./hosted.ts";
46
+ import { createHandle } from "./handle.ts";
47
+ import { type HostedHome, type HostedServices, openHostedHome } from "./hosted.ts";
48
+ import { type HomeOwner, homeUnavailable } from "./hosted-pages.ts";
49
+ import { createRemoteMcp, serverDocs } from "./mcp.ts";
50
+ import { createMeter, type Meter } from "./metering.ts";
51
+ import { createClients } from "./oauth-clients.ts";
52
+ import { loadOperator, type Operator } from "./operator.ts";
53
+ import { type BuiltInProvider, builtInProviders } from "./providers.ts";
54
+ import { createRouting, type Destination, type Routing } from "./routing.ts";
36
55
 
37
56
  export { type RemoteServerConfig, readServerConfig } from "./config.ts";
38
57
 
@@ -94,12 +113,74 @@ function parseListen(listen: string): { host: string; port: number } {
94
113
  /** Starts the remote server: its data directory, then its listener. */
95
114
  export async function startServer(options: ServerOptions): Promise<RemoteServer> {
96
115
  const { config, log } = options;
97
- // The authorization server is made once the directory is open; homes open only after that.
116
+ // The authorization server and the operator module are made once the directory is open; homes
117
+ // open only after both.
98
118
  let auth: Authorization | undefined;
119
+ let operator: Operator | undefined;
120
+ let meter: Meter | undefined;
121
+ let routing: Routing;
122
+ let authorizer: Authorize | undefined;
123
+ let api: Api | undefined;
99
124
  const shellDir = locateShell(options.env);
125
+ const clients = clientAddresses({
126
+ trustedProxies: config.trustedProxies,
127
+ ipv6Prefix: config.rateLimits?.ipv6Prefix,
128
+ });
129
+ const rates = new RateLimiter();
130
+ const faults = faultsFrom(options.env);
131
+ const rateOf = (rate: { count: number; per: string } | undefined) =>
132
+ rate === undefined ? undefined : { count: rate.count, perMs: durationMs(rate.per as Duration) };
133
+ /**
134
+ * `rateLimits.perIp.requests`: every request to the server, from one client address (IPv6 per
135
+ * /64), API origin and hosted hosts alike, before anything else is read (D165 item 13). A
136
+ * health check is never counted. Without the setting there is no limit.
137
+ */
138
+ const perIpRequests = rateOf(config.rateLimits?.perIp?.requests);
139
+ /** Who owns a home, as its pages' sender line names them (D161). */
140
+ const ownerOf = (homeId: string): HomeOwner => {
141
+ const row = data.directory.read((db) =>
142
+ db.get<{ account: string; name: string | null; provider: string | null }>(
143
+ `SELECT a.id AS account, a.name, (SELECT i.provider FROM identity i WHERE i.account_id = a.id
144
+ ORDER BY i.linked_at LIMIT 1) AS provider
145
+ FROM home h JOIN account a ON a.id = h.owner_account_id WHERE h.id = ?`,
146
+ homeId,
147
+ ),
148
+ );
149
+ if (!row) return { account: "" };
150
+ const provider = config.identityProviders?.find((candidate) => candidate.id === row.provider);
151
+ // A name the development provider took on trust is unverified (D161).
152
+ const verifiedBy =
153
+ provider && provider.kind !== "development"
154
+ ? (provider.label ?? (provider.kind === "github" ? "GitHub" : provider.id))
155
+ : undefined;
156
+ return {
157
+ account: row.account,
158
+ ...(row.name !== null ? { name: row.name } : {}),
159
+ ...(verifiedBy !== undefined ? { verifiedBy } : {}),
160
+ };
161
+ };
162
+ const services = (): HostedServices => ({
163
+ operator: operator as Operator,
164
+ clients,
165
+ rates,
166
+ rateLimits: {
167
+ perIpSubmissions: rateOf(config.rateLimits?.perIp?.submissions),
168
+ perLinkSubmissions: rateOf(config.rateLimits?.perLink?.submissions),
169
+ },
170
+ owner: ownerOf,
171
+ meter: meter as Meter,
172
+ routing,
173
+ signin: {
174
+ start: (signin, challenge) => (authorizer as Authorize).startViewerSignin(signin, challenge),
175
+ finish: (input) => (authorizer as Authorize).finishViewerSignin(input),
176
+ },
177
+ signInOffered: () =>
178
+ (config.identityProviders?.length ?? 0) > 0 || (operator?.has.identity ?? false),
179
+ });
100
180
  const assembler: HomeAssembler<HostedHome> = {
101
181
  assemble: (home) =>
102
182
  openHostedHome({
183
+ faults,
103
184
  id: home.id,
104
185
  dir: home.dir,
105
186
  ledger: home.ledger,
@@ -112,6 +193,7 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
112
193
  scheme: config.scheme ?? "https",
113
194
  domains: { active: config.domains.active, spares: config.domains.spares ?? [] },
114
195
  shellDir,
196
+ services: services(),
115
197
  relay: {
116
198
  waitingRunsPerArtifact: config.relay?.waitingRunsPerArtifact,
117
199
  drainPerSecond: config.relay?.drainPerSecond,
@@ -150,13 +232,65 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
150
232
  ? { walAutocheckpoint: config.ledger.walAutocheckpoint }
151
233
  : {}),
152
234
  });
235
+ const handle = createHandle({
236
+ apiOrigin: config.apiOrigin,
237
+ data: () => data,
238
+ directory: () => data.directory,
239
+ suspended: (homeId) => api?.closeHome(homeId),
240
+ log,
241
+ });
242
+ try {
243
+ operator = await loadOperator({
244
+ path: config.operator,
245
+ handle,
246
+ directory: data.directory,
247
+ log,
248
+ // An invitation's link is built when it is handed over, never kept in the queue (D168).
249
+ invitationLink: async (homeId, tokenId) => {
250
+ // A home the directory no longer has can't build a link: its invitations go, while one
251
+ // that is only closed, drained or failing to open is tried again later.
252
+ const known = data.directory.read((db) =>
253
+ db.get("SELECT 1 FROM home WHERE id = ?", homeId),
254
+ );
255
+ if (known === undefined) return undefined;
256
+ return (await data.home(homeId)).assembled.invitationLink(tokenId);
257
+ },
258
+ ...(Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) > 0
259
+ ? { dispatchMs: Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) }
260
+ : {}),
261
+ });
262
+ } catch (error) {
263
+ await data.close();
264
+ throw error;
265
+ }
266
+ routing = createRouting({
267
+ apiHost: new URL(config.apiOrigin).host,
268
+ domains: () => [config.domains.active, ...(config.domains.spares ?? [])],
269
+ active: () => config.domains.active,
270
+ directory: data.directory,
271
+ operator,
272
+ log,
273
+ });
274
+ meter = createMeter({
275
+ operator,
276
+ keysDir: join(options.data, "keys"),
277
+ log,
278
+ ...(Number(options.env["MOSTRA_TEST_METER_WINDOW_MS"]) > 0
279
+ ? { windowMs: Number(options.env["MOSTRA_TEST_METER_WINDOW_MS"]) }
280
+ : {}),
281
+ activeHomes: () => data.open().map((home) => ({ home, account: ownerOf(home).account })),
282
+ });
153
283
  auth = createAuthorization({
154
284
  directory: data.directory,
155
285
  config,
156
286
  log,
287
+ operator,
157
288
  ...(Number(options.env["MOSTRA_TEST_ACCESS_TTL_MS"]) > 0
158
289
  ? { accessTtlMs: Number(options.env["MOSTRA_TEST_ACCESS_TTL_MS"]) }
159
290
  : {}),
291
+ ...(Number(options.env["MOSTRA_TEST_ROTATION_GRACE_MS"]) > 0
292
+ ? { rotationGraceMs: Number(options.env["MOSTRA_TEST_ROTATION_GRACE_MS"]) }
293
+ : {}),
160
294
  // A new instance link is a hosted event the account's instances see (§18.5).
161
295
  linked: ({ homeId, linkId, name }) => {
162
296
  void data.home(homeId).then(
@@ -173,31 +307,105 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
173
307
  );
174
308
  },
175
309
  });
176
- const api: Api = createApi({
310
+ // The authorization server's clients and browser pages (INTERFACES §18.5).
311
+ const scheme = config.scheme ?? "https";
312
+ const oauthClients = createClients({
313
+ directory: data.directory,
314
+ log,
315
+ env: options.env,
316
+ isShellOrigin: (origin) => {
317
+ if (!origin.startsWith(`${scheme}://`)) return false;
318
+ const host = origin.slice(scheme.length + 3);
319
+ if (domains.includes(host)) return true;
320
+ return (
321
+ data.directory.read((db) => db.get("SELECT 1 FROM operator_host WHERE host = ?", host)) !==
322
+ undefined
323
+ );
324
+ },
325
+ });
326
+ let providers: BuiltInProvider[];
327
+ try {
328
+ providers = builtInProviders(config.identityProviders ?? [], {
329
+ apiOrigin: config.apiOrigin,
330
+ env: options.env,
331
+ log,
332
+ });
333
+ } catch (error) {
334
+ operator?.stop();
335
+ await data.close();
336
+ throw error;
337
+ }
338
+ const authorize = createAuthorize({
339
+ apiOrigin: config.apiOrigin,
340
+ directory: data.directory,
341
+ auth,
342
+ clients: oauthClients,
343
+ operator,
344
+ providers,
345
+ ownerName: (homeId) => ownerOf(homeId).name,
346
+ log,
347
+ });
348
+ authorizer = authorize;
349
+ const mcp = createRemoteMcp({
350
+ apiOrigin: config.apiOrigin,
351
+ version: options.runtimeVersion,
352
+ docs: serverDocs(),
353
+ log,
354
+ operator,
355
+ meter,
356
+ home: async (id) => (await data.home(id)).assembled,
357
+ ensureHome: (accountId) => (auth as Authorization).ensureHome(accountId),
358
+ });
359
+ api = createApi({
177
360
  config,
178
361
  auth,
362
+ mcp,
363
+ authorize,
364
+ clients: oauthClients,
365
+ registrations: { addresses: clients, rates },
366
+ operator,
179
367
  log,
180
368
  filesDir: join(options.data, "files"),
181
369
  home: async (id) => (await data.home(id)).assembled,
182
370
  touch: (id) => data.touch(id),
371
+ suspended: (id) => suspendedHome(id),
372
+ message: (id) => meter?.add("relay.messages", { account: ownerOf(id).account, home: id }),
373
+ stored: (id, bytes) =>
374
+ meter?.add("bytes.stored", { account: ownerOf(id).account, home: id }, bytes),
183
375
  ...(Number(options.env["MOSTRA_TEST_GRANT_RECHECK_MS"]) > 0
184
376
  ? { recheckMs: Number(options.env["MOSTRA_TEST_GRANT_RECHECK_MS"]) }
185
377
  : {}),
186
378
  });
379
+ const served: Api = api;
187
380
  const apiHost = new URL(config.apiOrigin).host;
188
- const domains = new Set([config.domains.active, ...(config.domains.spares ?? [])]);
381
+ const domains = [config.domains.active, ...(config.domains.spares ?? [])];
189
382
 
190
383
  const onRequest = (request: IncomingMessage, response: ServerResponse): void => {
191
384
  const host = (request.headers.host ?? "").toLowerCase();
192
- // Cookies never reach anything on a hosted host (D165 item 8): dropped before routing.
193
- delete request.headers.cookie;
194
385
  const path = (request.url ?? "/").split("?")[0] ?? "/";
195
- if (host === apiHost) {
196
- if (request.method === "GET" && path === "/health") {
197
- json(response, 200, { status: "ok", homes: data.open().length });
386
+ // Cookies never reach anything on a hosted host (D165 item 8): dropped before routing. Only
387
+ // the API origin's own sign-in pages read the cookies it set itself.
388
+ if (host !== apiHost) delete request.headers.cookie;
389
+ if (host === apiHost && request.method === "GET" && path === "/health") {
390
+ json(response, 200, { status: "ok", homes: data.open().length });
391
+ return;
392
+ }
393
+ if (perIpRequests) {
394
+ const taken = rates.take(`request-ip:${clients.keyOf(clients.of(request))}`, perIpRequests);
395
+ if (!taken.ok) {
396
+ response.setHeader("retry-after", String(taken.retryAfterS));
397
+ refusal(
398
+ response,
399
+ 429,
400
+ createDiagnostic("MOSTRA_REMOTE_RATE_LIMITED", {
401
+ message: "Too many requests from this address; try again shortly.",
402
+ }),
403
+ );
198
404
  return;
199
405
  }
200
- api.request(request, response, path).catch((error: unknown) => {
406
+ }
407
+ if (host === apiHost) {
408
+ served.request(request, response, path).catch((error: unknown) => {
201
409
  log.error("server.api_failed", { path, error });
202
410
  if (!response.headersSent) {
203
411
  refusal(
@@ -211,10 +419,7 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
211
419
  });
212
420
  return;
213
421
  }
214
- const domain = [...domains].find(
215
- (candidate) => host === candidate || host.endsWith(`.${candidate}`),
216
- );
217
- if (domain === undefined) {
422
+ const hostRefused = (): void =>
218
423
  refusal(
219
424
  response,
220
425
  421,
@@ -222,24 +427,36 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
222
427
  message: "This server serves no pages at this host.",
223
428
  }),
224
429
  );
430
+ // An empty or malformed Host gets nothing, and is never asked of an operator.
431
+ if (!/^[a-z0-9.-]{1,253}(:\d{1,5})?$/.test(host)) {
432
+ hostRefused();
225
433
  return;
226
434
  }
227
- // Every hosted answer keeps its page in an agent cluster of its own and out of indexes
228
- // (ARCHITECTURE §15.6, D161).
229
- response.setHeader("origin-agent-cluster", "?1");
230
- response.setHeader("x-robots-tag", "noindex");
231
- hosted(request, response, host, domain, path).catch((error: unknown) => {
232
- log.error("server.hosted_failed", { error });
233
- if (!response.headersSent) {
234
- refusal(
235
- response,
236
- 500,
237
- createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", {
238
- message: "The server failed to answer.",
239
- }),
240
- );
241
- } else response.destroy();
242
- });
435
+ routing
436
+ .destination(host)
437
+ .then(async (destination) => {
438
+ if (destination.kind === "none" || destination.kind === "api") {
439
+ hostRefused();
440
+ return;
441
+ }
442
+ // Every hosted answer keeps its page in an agent cluster of its own and out of indexes
443
+ // (ARCHITECTURE §15.6, D161).
444
+ response.setHeader("origin-agent-cluster", "?1");
445
+ response.setHeader("x-robots-tag", "noindex");
446
+ await hosted(request, response, destination, path);
447
+ })
448
+ .catch((error: unknown) => {
449
+ log.error("server.hosted_failed", { error });
450
+ if (!response.headersSent) {
451
+ refusal(
452
+ response,
453
+ 500,
454
+ createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", {
455
+ message: "The server failed to answer.",
456
+ }),
457
+ );
458
+ } else response.destroy();
459
+ });
243
460
  };
244
461
 
245
462
  const notServed = (response: ServerResponse): void =>
@@ -265,57 +482,131 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
265
482
  { overrideGlobalObjects: false },
266
483
  );
267
484
 
485
+ /** Whether the operator suspended a home (`ServerHandle.suspendHome`). */
486
+ const suspendedHome = (homeId: string): boolean =>
487
+ data.directory.read(
488
+ (db) =>
489
+ db.get<{ suspended_at: string | null }>(
490
+ "SELECT suspended_at FROM home WHERE id = ?",
491
+ homeId,
492
+ )?.suspended_at != null,
493
+ );
494
+
495
+ /**
496
+ * A home whose pages are served now: a suspended one answers 403 and one being moved 503,
497
+ * each with its diagnostic, and nothing of it is opened for a page (D165 item 9).
498
+ */
499
+ const pagesOf = async (homeId: string, response: ServerResponse) => {
500
+ if (suspendedHome(homeId)) {
501
+ refusal(response, 403, homeUnavailable("suspended"));
502
+ return undefined;
503
+ }
504
+ try {
505
+ const opened = await data.home(homeId);
506
+ // Requests and the bytes they sent count against the home's owner (metering, §18.6): one
507
+ // HTTP/1.1 connection answers one request at a time, so its written bytes are this one's.
508
+ if (meter?.on) {
509
+ const socket = response.socket;
510
+ const before = socket?.bytesWritten ?? 0;
511
+ response.once("finish", () => {
512
+ const account = ownerOf(homeId).account;
513
+ meter?.add("requests", { account, home: homeId });
514
+ meter?.add(
515
+ "bytes.egress",
516
+ { account, home: homeId },
517
+ Math.max(0, (socket?.bytesWritten ?? before) - before),
518
+ );
519
+ });
520
+ }
521
+ return opened;
522
+ } catch (error) {
523
+ if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_REMOTE_HOME_MOVING") {
524
+ response.setHeader("retry-after", "30");
525
+ refusal(response, 503, error.diagnostic);
526
+ return undefined;
527
+ }
528
+ throw error;
529
+ }
530
+ };
531
+
268
532
  /** A route of the directory: its home and ID, by ID or by label. */
269
533
  const routeBy = (column: "id" | "label", value: string) =>
270
534
  data.directory.read((db) =>
271
535
  db.get<{ id: string; home_id: string }>(
272
- `SELECT id, home_id FROM artifact_route WHERE ${column} = ?`,
536
+ `SELECT id, home_id FROM artifact_route WHERE ${column} = ? AND removing_json IS NULL`,
273
537
  value,
274
538
  ),
275
539
  );
276
540
 
277
- /** A request on a user-content domain: the shell on its apex, a route's frames on its label. */
541
+ /**
542
+ * A hosted request (§18.4): a shell (a configured apex, or an operator's host for one home or
543
+ * one route) serves only `/a/<routeId>` of the routes it may show and the shell's files; a
544
+ * route's label serves that route's frames.
545
+ */
278
546
  const hosted = async (
279
547
  request: IncomingMessage,
280
548
  response: ServerResponse,
281
- host: string,
282
- domain: string,
549
+ destination: Exclude<Destination, { kind: "none" | "api" }>,
283
550
  path: string,
284
551
  ): Promise<void> => {
285
- if (host === domain) {
552
+ if (destination.kind === "shell") {
286
553
  if (path.startsWith("/_mostra/shell/assets/")) {
287
554
  await assets(request, response);
288
555
  return;
289
556
  }
557
+ // Where a page's sign-in returns (INTERFACES §18.4): the shell's own page, which finishes it
558
+ // for the route that started it. It reads only the fragment and query it was sent.
559
+ if (path === "/_mostra/signin" && (request.method === "GET" || request.method === "HEAD")) {
560
+ if (shellDir === undefined) {
561
+ notServed(response);
562
+ return;
563
+ }
564
+ const html = readFileSync(join(shellDir, "index.html"));
565
+ response.writeHead(200, {
566
+ ...BASE_HEADERS,
567
+ ...documentHeaders({ kind: "shell", origin: "", shellOrigin: "" }, "'none'"),
568
+ "content-type": "text/html; charset=utf-8",
569
+ "cache-control": "no-store",
570
+ });
571
+ response.end(request.method === "HEAD" ? undefined : html);
572
+ return;
573
+ }
290
574
  const match = /^\/a\/(rte_[0-9A-HJKMNP-TV-Z]{26})(?:\/|$)/.exec(path);
291
575
  const route =
292
576
  match?.[1] !== undefined && RouteId.is(match[1]) ? routeBy("id", match[1]) : undefined;
293
- if (!route) {
577
+ // An operator's host shows only its own home's routes, or its one route.
578
+ if (
579
+ !route ||
580
+ (destination.homeId !== undefined && route.home_id !== destination.homeId) ||
581
+ (destination.routeId !== undefined && route.id !== destination.routeId)
582
+ ) {
294
583
  notServed(response);
295
584
  return;
296
585
  }
297
- const home = await data.home(route.home_id);
298
- await home.assembled.serve(request, response, { kind: "shell", domain, routeId: route.id });
299
- return;
300
- }
301
- // One DNS label under the domain: a route's label, never issued twice (§18.4).
302
- const label = host.slice(0, host.length - domain.length - 1);
303
- const route = /^[0-9a-hjkmnp-tv-z]{26}$/.test(label) ? routeBy("label", label) : undefined;
304
- if (!route) {
305
- refusal(
306
- response,
307
- 421,
308
- createDiagnostic("MOSTRA_HYGIENE_HOST_REFUSED", {
309
- message: "This server serves no pages at this host.",
310
- }),
311
- );
586
+ const home = await pagesOf(route.home_id, response);
587
+ if (!home) return;
588
+ await home.assembled.serve(request, response, {
589
+ kind: "shell",
590
+ domain: destination.host,
591
+ routeId: route.id,
592
+ });
312
593
  return;
313
594
  }
314
- const home = await data.home(route.home_id);
315
- await home.assembled.serve(request, response, { kind: "frame", domain, routeId: route.id });
595
+ const home = await pagesOf(destination.route.homeId, response);
596
+ if (!home) return;
597
+ await home.assembled.serve(request, response, {
598
+ kind: "frame",
599
+ domain: destination.frameDomain,
600
+ routeId: destination.route.id,
601
+ });
316
602
  };
317
603
 
318
- const listener: Server = createServer({ maxHeaderSize: 64 * 1024 }, onRequest);
604
+ // Up to 1 MiB of headers (D98 item 9): a sibling tenant page can fill the parent domain's cookie
605
+ // jar (180 cookies of 4 KiB, no public-suffix entry, D137), and its cookies, dropped unread here,
606
+ // must never cost another page its session (D165 item 8).
607
+ const listener: Server = createServer({ maxHeaderSize: 1024 * 1024 }, onRequest);
608
+ // Stopping resets its connections, so none stays in TIME_WAIT on the server's port (#132).
609
+ const stopListener = resetOnClose(listener);
319
610
  listener.keepAliveTimeout = 305_000;
320
611
  listener.headersTimeout = 30_000;
321
612
  listener.requestTimeout = 120_000;
@@ -323,7 +614,7 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
323
614
  const host = (request.headers.host ?? "").toLowerCase();
324
615
  const path = (request.url ?? "/").split("?")[0] ?? "/";
325
616
  if (host === apiHost) {
326
- api.upgrade(request, socket, head, path);
617
+ served.upgrade(request, socket, head, path);
327
618
  return;
328
619
  }
329
620
  socket.end("HTTP/1.1 404 Not Found\r\nconnection: close\r\ncontent-length: 0\r\n\r\n");
@@ -354,11 +645,12 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
354
645
  config,
355
646
  close() {
356
647
  closing ??= (async () => {
357
- api.close();
358
- await new Promise<void>((resolve) => {
359
- listener.close(() => resolve());
360
- listener.closeAllConnections();
361
- });
648
+ served.close();
649
+ await mcp.close().catch(() => undefined);
650
+ // What the operator hasn't taken yet stays queued in the directory for the next start.
651
+ meter?.stop();
652
+ operator?.stop();
653
+ await stopListener();
362
654
  await data.close();
363
655
  log.info("server.stopped", {});
364
656
  })();