@mostra/runtime 0.10.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 (245) hide show
  1. package/dist/bin.js +4058 -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-DCiUHvgZ.js} +682 -47
  6. package/dist/instance-DCiUHvgZ.js.map +1 -0
  7. package/dist/reference/cli.md +1322 -0
  8. package/dist/reference/diagnostics.json +1552 -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_TYPE_ERROR.md +23 -0
  172. package/dist/reference/errors/MOSTRA_TYPE_UNTYPED_PACKAGE.md +23 -0
  173. package/dist/reference/errors/MOSTRA_VERIFY_ACTION_SKIPPED.md +23 -0
  174. package/dist/reference/errors/MOSTRA_VERIFY_BASELINE_MISSING.md +23 -0
  175. package/dist/reference/errors/MOSTRA_VERIFY_CRASHED.md +23 -0
  176. package/dist/reference/errors/MOSTRA_VERIFY_LIVE_FAILED.md +23 -0
  177. package/dist/reference/errors/MOSTRA_VERIFY_NO_BASELINE.md +23 -0
  178. package/dist/reference/errors/MOSTRA_VERIFY_SECRET_MISSING.md +23 -0
  179. package/dist/reference/errors/MOSTRA_VERIFY_SKIP_CONSEQUENCE.md +23 -0
  180. package/dist/reference/errors/MOSTRA_VERIFY_TIMEOUT.md +23 -0
  181. package/dist/reference/self-hosting.md +130 -0
  182. package/dist/reference/telemetry.md +84 -0
  183. package/dist/skill/SKILL.md +122 -0
  184. package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
  185. package/dist/skill/assets/examples/dashboard/live.ts +25 -0
  186. package/dist/skill/assets/examples/dashboard/styles.css +125 -0
  187. package/dist/skill/assets/examples/decision/index.tsx +95 -0
  188. package/dist/skill/assets/examples/decision/styles.css +125 -0
  189. package/dist/skill/assets/examples/inbox/actions.ts +23 -0
  190. package/dist/skill/assets/examples/inbox/index.tsx +109 -0
  191. package/dist/skill/assets/examples/inbox/styles.css +125 -0
  192. package/dist/skill/assets/studio.css +125 -0
  193. package/dist/skill/references/answers.md +217 -0
  194. package/dist/skill/references/design.md +154 -0
  195. package/dist/skill/references/libraries.md +167 -0
  196. package/dist/skill/references/long-lived.md +148 -0
  197. package/dist/skill/references/mcp.md +68 -0
  198. package/dist/skill/references/page.md +131 -0
  199. package/dist/skill/references/server.md +146 -0
  200. package/dist/skill/references/sharing.md +123 -0
  201. package/dist/skill/references/verify.md +71 -0
  202. package/package.json +10 -5
  203. package/src/gateway/actions.ts +20 -0
  204. package/src/gateway/browser.ts +44 -0
  205. package/src/gateway/capabilities.ts +8 -0
  206. package/src/gateway/http.ts +12 -1
  207. package/src/gateway/index.ts +170 -5
  208. package/src/gateway/listener.ts +31 -6
  209. package/src/gateway/routes.ts +8 -0
  210. package/src/gc/index.ts +5 -0
  211. package/src/instance/index.ts +20 -1
  212. package/src/interaction/index.ts +60 -0
  213. package/src/interaction/pause.ts +106 -0
  214. package/src/interaction/submissions.ts +42 -1
  215. package/src/interaction/viewers.ts +34 -1
  216. package/src/ledger/index.ts +20 -1
  217. package/src/ledger/migrations.ts +51 -0
  218. package/src/link/author.ts +215 -0
  219. package/src/link/hosted.ts +37 -1
  220. package/src/link/http.ts +6 -1
  221. package/src/link/index.ts +3 -1
  222. package/src/link/manager.ts +138 -34
  223. package/src/protocol-server/client.ts +53 -0
  224. package/src/protocol-server/index.ts +1 -1
  225. package/src/server/api.ts +514 -72
  226. package/src/server/auth.ts +600 -74
  227. package/src/server/authorize.ts +816 -0
  228. package/src/server/clients.ts +235 -0
  229. package/src/server/config.ts +7 -0
  230. package/src/server/data.ts +59 -1
  231. package/src/server/directory.ts +69 -0
  232. package/src/server/feed.ts +191 -0
  233. package/src/server/handle.ts +172 -0
  234. package/src/server/hosted-pages.ts +532 -0
  235. package/src/server/hosted.ts +519 -18
  236. package/src/server/index.ts +343 -61
  237. package/src/server/mcp.ts +330 -0
  238. package/src/server/metering.ts +156 -0
  239. package/src/server/oauth-clients.ts +510 -0
  240. package/src/server/operator.ts +498 -0
  241. package/src/server/providers.ts +284 -0
  242. package/src/server/remove.ts +148 -0
  243. package/src/server/routing.ts +275 -0
  244. package/src/verify/runner.ts +23 -2
  245. 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,55 @@ 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
+ ...(Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) > 0
249
+ ? { dispatchMs: Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) }
250
+ : {}),
251
+ });
252
+ } catch (error) {
253
+ await data.close();
254
+ throw error;
255
+ }
256
+ routing = createRouting({
257
+ apiHost: new URL(config.apiOrigin).host,
258
+ domains: () => [config.domains.active, ...(config.domains.spares ?? [])],
259
+ active: () => config.domains.active,
260
+ directory: data.directory,
261
+ operator,
262
+ log,
263
+ });
264
+ meter = createMeter({
265
+ operator,
266
+ keysDir: join(options.data, "keys"),
267
+ log,
268
+ ...(Number(options.env["MOSTRA_TEST_METER_WINDOW_MS"]) > 0
269
+ ? { windowMs: Number(options.env["MOSTRA_TEST_METER_WINDOW_MS"]) }
270
+ : {}),
271
+ activeHomes: () => data.open().map((home) => ({ home, account: ownerOf(home).account })),
272
+ });
153
273
  auth = createAuthorization({
154
274
  directory: data.directory,
155
275
  config,
156
276
  log,
277
+ operator,
157
278
  ...(Number(options.env["MOSTRA_TEST_ACCESS_TTL_MS"]) > 0
158
279
  ? { accessTtlMs: Number(options.env["MOSTRA_TEST_ACCESS_TTL_MS"]) }
159
280
  : {}),
281
+ ...(Number(options.env["MOSTRA_TEST_ROTATION_GRACE_MS"]) > 0
282
+ ? { rotationGraceMs: Number(options.env["MOSTRA_TEST_ROTATION_GRACE_MS"]) }
283
+ : {}),
160
284
  // A new instance link is a hosted event the account's instances see (§18.5).
161
285
  linked: ({ homeId, linkId, name }) => {
162
286
  void data.home(homeId).then(
@@ -173,31 +297,105 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
173
297
  );
174
298
  },
175
299
  });
176
- const api: Api = createApi({
300
+ // The authorization server's clients and browser pages (INTERFACES §18.5).
301
+ const scheme = config.scheme ?? "https";
302
+ const oauthClients = createClients({
303
+ directory: data.directory,
304
+ log,
305
+ env: options.env,
306
+ isShellOrigin: (origin) => {
307
+ if (!origin.startsWith(`${scheme}://`)) return false;
308
+ const host = origin.slice(scheme.length + 3);
309
+ if (domains.includes(host)) return true;
310
+ return (
311
+ data.directory.read((db) => db.get("SELECT 1 FROM operator_host WHERE host = ?", host)) !==
312
+ undefined
313
+ );
314
+ },
315
+ });
316
+ let providers: BuiltInProvider[];
317
+ try {
318
+ providers = builtInProviders(config.identityProviders ?? [], {
319
+ apiOrigin: config.apiOrigin,
320
+ env: options.env,
321
+ log,
322
+ });
323
+ } catch (error) {
324
+ operator?.stop();
325
+ await data.close();
326
+ throw error;
327
+ }
328
+ const authorize = createAuthorize({
329
+ apiOrigin: config.apiOrigin,
330
+ directory: data.directory,
331
+ auth,
332
+ clients: oauthClients,
333
+ operator,
334
+ providers,
335
+ ownerName: (homeId) => ownerOf(homeId).name,
336
+ log,
337
+ });
338
+ authorizer = authorize;
339
+ const mcp = createRemoteMcp({
340
+ apiOrigin: config.apiOrigin,
341
+ version: options.runtimeVersion,
342
+ docs: serverDocs(),
343
+ log,
344
+ operator,
345
+ meter,
346
+ home: async (id) => (await data.home(id)).assembled,
347
+ ensureHome: (accountId) => (auth as Authorization).ensureHome(accountId),
348
+ });
349
+ api = createApi({
177
350
  config,
178
351
  auth,
352
+ mcp,
353
+ authorize,
354
+ clients: oauthClients,
355
+ registrations: { addresses: clients, rates },
356
+ operator,
179
357
  log,
180
358
  filesDir: join(options.data, "files"),
181
359
  home: async (id) => (await data.home(id)).assembled,
182
360
  touch: (id) => data.touch(id),
361
+ suspended: (id) => suspendedHome(id),
362
+ message: (id) => meter?.add("relay.messages", { account: ownerOf(id).account, home: id }),
363
+ stored: (id, bytes) =>
364
+ meter?.add("bytes.stored", { account: ownerOf(id).account, home: id }, bytes),
183
365
  ...(Number(options.env["MOSTRA_TEST_GRANT_RECHECK_MS"]) > 0
184
366
  ? { recheckMs: Number(options.env["MOSTRA_TEST_GRANT_RECHECK_MS"]) }
185
367
  : {}),
186
368
  });
369
+ const served: Api = api;
187
370
  const apiHost = new URL(config.apiOrigin).host;
188
- const domains = new Set([config.domains.active, ...(config.domains.spares ?? [])]);
371
+ const domains = [config.domains.active, ...(config.domains.spares ?? [])];
189
372
 
190
373
  const onRequest = (request: IncomingMessage, response: ServerResponse): void => {
191
374
  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
375
  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 });
376
+ // Cookies never reach anything on a hosted host (D165 item 8): dropped before routing. Only
377
+ // the API origin's own sign-in pages read the cookies it set itself.
378
+ if (host !== apiHost) delete request.headers.cookie;
379
+ if (host === apiHost && request.method === "GET" && path === "/health") {
380
+ json(response, 200, { status: "ok", homes: data.open().length });
381
+ return;
382
+ }
383
+ if (perIpRequests) {
384
+ const taken = rates.take(`request-ip:${clients.keyOf(clients.of(request))}`, perIpRequests);
385
+ if (!taken.ok) {
386
+ response.setHeader("retry-after", String(taken.retryAfterS));
387
+ refusal(
388
+ response,
389
+ 429,
390
+ createDiagnostic("MOSTRA_REMOTE_RATE_LIMITED", {
391
+ message: "Too many requests from this address; try again shortly.",
392
+ }),
393
+ );
198
394
  return;
199
395
  }
200
- api.request(request, response, path).catch((error: unknown) => {
396
+ }
397
+ if (host === apiHost) {
398
+ served.request(request, response, path).catch((error: unknown) => {
201
399
  log.error("server.api_failed", { path, error });
202
400
  if (!response.headersSent) {
203
401
  refusal(
@@ -211,10 +409,7 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
211
409
  });
212
410
  return;
213
411
  }
214
- const domain = [...domains].find(
215
- (candidate) => host === candidate || host.endsWith(`.${candidate}`),
216
- );
217
- if (domain === undefined) {
412
+ const hostRefused = (): void =>
218
413
  refusal(
219
414
  response,
220
415
  421,
@@ -222,24 +417,36 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
222
417
  message: "This server serves no pages at this host.",
223
418
  }),
224
419
  );
420
+ // An empty or malformed Host gets nothing, and is never asked of an operator.
421
+ if (!/^[a-z0-9.-]{1,253}(:\d{1,5})?$/.test(host)) {
422
+ hostRefused();
225
423
  return;
226
424
  }
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
- });
425
+ routing
426
+ .destination(host)
427
+ .then(async (destination) => {
428
+ if (destination.kind === "none" || destination.kind === "api") {
429
+ hostRefused();
430
+ return;
431
+ }
432
+ // Every hosted answer keeps its page in an agent cluster of its own and out of indexes
433
+ // (ARCHITECTURE §15.6, D161).
434
+ response.setHeader("origin-agent-cluster", "?1");
435
+ response.setHeader("x-robots-tag", "noindex");
436
+ await hosted(request, response, destination, path);
437
+ })
438
+ .catch((error: unknown) => {
439
+ log.error("server.hosted_failed", { error });
440
+ if (!response.headersSent) {
441
+ refusal(
442
+ response,
443
+ 500,
444
+ createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", {
445
+ message: "The server failed to answer.",
446
+ }),
447
+ );
448
+ } else response.destroy();
449
+ });
243
450
  };
244
451
 
245
452
  const notServed = (response: ServerResponse): void =>
@@ -265,57 +472,131 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
265
472
  { overrideGlobalObjects: false },
266
473
  );
267
474
 
475
+ /** Whether the operator suspended a home (`ServerHandle.suspendHome`). */
476
+ const suspendedHome = (homeId: string): boolean =>
477
+ data.directory.read(
478
+ (db) =>
479
+ db.get<{ suspended_at: string | null }>(
480
+ "SELECT suspended_at FROM home WHERE id = ?",
481
+ homeId,
482
+ )?.suspended_at != null,
483
+ );
484
+
485
+ /**
486
+ * A home whose pages are served now: a suspended one answers 403 and one being moved 503,
487
+ * each with its diagnostic, and nothing of it is opened for a page (D165 item 9).
488
+ */
489
+ const pagesOf = async (homeId: string, response: ServerResponse) => {
490
+ if (suspendedHome(homeId)) {
491
+ refusal(response, 403, homeUnavailable("suspended"));
492
+ return undefined;
493
+ }
494
+ try {
495
+ const opened = await data.home(homeId);
496
+ // Requests and the bytes they sent count against the home's owner (metering, §18.6): one
497
+ // HTTP/1.1 connection answers one request at a time, so its written bytes are this one's.
498
+ if (meter?.on) {
499
+ const socket = response.socket;
500
+ const before = socket?.bytesWritten ?? 0;
501
+ response.once("finish", () => {
502
+ const account = ownerOf(homeId).account;
503
+ meter?.add("requests", { account, home: homeId });
504
+ meter?.add(
505
+ "bytes.egress",
506
+ { account, home: homeId },
507
+ Math.max(0, (socket?.bytesWritten ?? before) - before),
508
+ );
509
+ });
510
+ }
511
+ return opened;
512
+ } catch (error) {
513
+ if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_REMOTE_HOME_MOVING") {
514
+ response.setHeader("retry-after", "30");
515
+ refusal(response, 503, error.diagnostic);
516
+ return undefined;
517
+ }
518
+ throw error;
519
+ }
520
+ };
521
+
268
522
  /** A route of the directory: its home and ID, by ID or by label. */
269
523
  const routeBy = (column: "id" | "label", value: string) =>
270
524
  data.directory.read((db) =>
271
525
  db.get<{ id: string; home_id: string }>(
272
- `SELECT id, home_id FROM artifact_route WHERE ${column} = ?`,
526
+ `SELECT id, home_id FROM artifact_route WHERE ${column} = ? AND removing_json IS NULL`,
273
527
  value,
274
528
  ),
275
529
  );
276
530
 
277
- /** A request on a user-content domain: the shell on its apex, a route's frames on its label. */
531
+ /**
532
+ * A hosted request (§18.4): a shell (a configured apex, or an operator's host for one home or
533
+ * one route) serves only `/a/<routeId>` of the routes it may show and the shell's files; a
534
+ * route's label serves that route's frames.
535
+ */
278
536
  const hosted = async (
279
537
  request: IncomingMessage,
280
538
  response: ServerResponse,
281
- host: string,
282
- domain: string,
539
+ destination: Exclude<Destination, { kind: "none" | "api" }>,
283
540
  path: string,
284
541
  ): Promise<void> => {
285
- if (host === domain) {
542
+ if (destination.kind === "shell") {
286
543
  if (path.startsWith("/_mostra/shell/assets/")) {
287
544
  await assets(request, response);
288
545
  return;
289
546
  }
547
+ // Where a page's sign-in returns (INTERFACES §18.4): the shell's own page, which finishes it
548
+ // for the route that started it. It reads only the fragment and query it was sent.
549
+ if (path === "/_mostra/signin" && (request.method === "GET" || request.method === "HEAD")) {
550
+ if (shellDir === undefined) {
551
+ notServed(response);
552
+ return;
553
+ }
554
+ const html = readFileSync(join(shellDir, "index.html"));
555
+ response.writeHead(200, {
556
+ ...BASE_HEADERS,
557
+ ...documentHeaders({ kind: "shell", origin: "", shellOrigin: "" }, "'none'"),
558
+ "content-type": "text/html; charset=utf-8",
559
+ "cache-control": "no-store",
560
+ });
561
+ response.end(request.method === "HEAD" ? undefined : html);
562
+ return;
563
+ }
290
564
  const match = /^\/a\/(rte_[0-9A-HJKMNP-TV-Z]{26})(?:\/|$)/.exec(path);
291
565
  const route =
292
566
  match?.[1] !== undefined && RouteId.is(match[1]) ? routeBy("id", match[1]) : undefined;
293
- if (!route) {
567
+ // An operator's host shows only its own home's routes, or its one route.
568
+ if (
569
+ !route ||
570
+ (destination.homeId !== undefined && route.home_id !== destination.homeId) ||
571
+ (destination.routeId !== undefined && route.id !== destination.routeId)
572
+ ) {
294
573
  notServed(response);
295
574
  return;
296
575
  }
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
- );
576
+ const home = await pagesOf(route.home_id, response);
577
+ if (!home) return;
578
+ await home.assembled.serve(request, response, {
579
+ kind: "shell",
580
+ domain: destination.host,
581
+ routeId: route.id,
582
+ });
312
583
  return;
313
584
  }
314
- const home = await data.home(route.home_id);
315
- await home.assembled.serve(request, response, { kind: "frame", domain, routeId: route.id });
585
+ const home = await pagesOf(destination.route.homeId, response);
586
+ if (!home) return;
587
+ await home.assembled.serve(request, response, {
588
+ kind: "frame",
589
+ domain: destination.frameDomain,
590
+ routeId: destination.route.id,
591
+ });
316
592
  };
317
593
 
318
- const listener: Server = createServer({ maxHeaderSize: 64 * 1024 }, onRequest);
594
+ // Up to 1 MiB of headers (D98 item 9): a sibling tenant page can fill the parent domain's cookie
595
+ // jar (180 cookies of 4 KiB, no public-suffix entry, D137), and its cookies, dropped unread here,
596
+ // must never cost another page its session (D165 item 8).
597
+ const listener: Server = createServer({ maxHeaderSize: 1024 * 1024 }, onRequest);
598
+ // Stopping resets its connections, so none stays in TIME_WAIT on the server's port (#132).
599
+ const stopListener = resetOnClose(listener);
319
600
  listener.keepAliveTimeout = 305_000;
320
601
  listener.headersTimeout = 30_000;
321
602
  listener.requestTimeout = 120_000;
@@ -323,7 +604,7 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
323
604
  const host = (request.headers.host ?? "").toLowerCase();
324
605
  const path = (request.url ?? "/").split("?")[0] ?? "/";
325
606
  if (host === apiHost) {
326
- api.upgrade(request, socket, head, path);
607
+ served.upgrade(request, socket, head, path);
327
608
  return;
328
609
  }
329
610
  socket.end("HTTP/1.1 404 Not Found\r\nconnection: close\r\ncontent-length: 0\r\n\r\n");
@@ -354,11 +635,12 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
354
635
  config,
355
636
  close() {
356
637
  closing ??= (async () => {
357
- api.close();
358
- await new Promise<void>((resolve) => {
359
- listener.close(() => resolve());
360
- listener.closeAllConnections();
361
- });
638
+ served.close();
639
+ await mcp.close().catch(() => undefined);
640
+ // What the operator hasn't taken yet stays queued in the directory for the next start.
641
+ meter?.stop();
642
+ operator?.stop();
643
+ await stopListener();
362
644
  await data.close();
363
645
  log.info("server.stopped", {});
364
646
  })();