@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,1139 @@
1
+ /**
2
+ * The remote server's authorization server, as far as WP-29 builds it (INTERFACES §18.5, D165
3
+ * items 2, 8): the OAuth 2.0 device authorization grant (RFC 8628) behind `mostra login`, with
4
+ * rotating refresh tokens and revocation, and a development identity provider for tests and a
5
+ * self-hoster's first run. WP-30 adds the real identity providers, viewer sign-in and the MCP
6
+ * clients' flows on the same tables.
7
+ *
8
+ * Every token is an opaque random secret, stored only as its SHA-256 (DATA_MODEL §7.1): a copy of
9
+ * the directory grants nothing. Access tokens last an hour; a refresh token rotates on every use,
10
+ * returns the same successor for 30 s after it was used, so parallel refreshes don't collide, and a
11
+ * use after that revokes its grant. The device page says that approving links a machine to the
12
+ * account, and a new link is the hosted event `instance.linked`.
13
+ */
14
+ import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
15
+ import { AccountId, HomeId, LinkId } from "@mostra/protocol";
16
+ import type { SignInIdentity } from "@mostra/protocol/operator";
17
+ import type { Ledger, LedgerDb } from "../ledger/index.ts";
18
+ import type { Log } from "../log.ts";
19
+ import type { RemoteServerConfig } from "./config.ts";
20
+ import type { Operator } from "./operator.ts";
21
+
22
+ /** The CLI's client ID: a first-party public client (§18.5). */
23
+ export const CLI_CLIENT_ID = "mostra-cli";
24
+
25
+ /** The device grant's type (RFC 8628 §3.4). */
26
+ export const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
27
+
28
+ const ACCESS_TTL_MS = 60 * 60 * 1000;
29
+ const REFRESH_TTL_MS = 90 * 24 * 60 * 60 * 1000;
30
+ const DEVICE_TTL_MS = 10 * 60 * 1000;
31
+ const DEVICE_INTERVAL_S = 5;
32
+ const ROTATION_GRACE_MS = 30_000;
33
+ /** An authorization code lives a minute (OAuth 2.1 §4.1.2: short-lived). */
34
+ const CODE_TTL_MS = 60_000;
35
+ /** How long a used or expired code is kept to recognize its reuse (an hour). */
36
+ const CODE_KEPT_MS = 60 * 60 * 1000;
37
+
38
+ /** User codes: eight letters a person can't confuse (RFC 8628 §6.1), shown as `ABCD-EFGH`. */
39
+ const USER_CODE_LETTERS = "BCDFGHJKLMNPQRSTVWXZ";
40
+
41
+ /** What a valid access token names. */
42
+ export interface Authenticated {
43
+ /** The resource (audience) the token was issued for: `<apiOrigin>/host` or `<apiOrigin>/mcp`. */
44
+ readonly resource: string;
45
+ /** The client the grant is for. */
46
+ readonly clientId: string;
47
+ /** The grant's scopes, space-separated. */
48
+ readonly scope: string;
49
+ readonly accountId: string;
50
+ readonly accountName: string | undefined;
51
+ readonly grantId: string;
52
+ readonly homeId: string;
53
+ readonly linkId: string | undefined;
54
+ readonly expiresAt: number;
55
+ }
56
+
57
+ /** An OAuth error answer (RFC 6749 §5.2, RFC 8628 §3.5). */
58
+ export interface OAuthError {
59
+ readonly status: number;
60
+ readonly error: string;
61
+ readonly description: string;
62
+ }
63
+
64
+ /** The token endpoint's success answer. */
65
+ export interface TokenAnswer {
66
+ readonly access_token: string;
67
+ readonly token_type: "Bearer";
68
+ readonly expires_in: number;
69
+ readonly refresh_token: string;
70
+ readonly scope: string;
71
+ readonly mostra_account: { readonly id: string; readonly name?: string };
72
+ readonly mostra_instance?: string;
73
+ /** Whether this instance is the account's default instance (D165 item 1b). */
74
+ readonly mostra_default?: boolean;
75
+ /** The account's hosted home. */
76
+ readonly mostra_home?: string;
77
+ }
78
+
79
+ /** What an authorization code carries, kept with its hash (one minute, single use). */
80
+ export interface CodeGrant {
81
+ readonly clientId: string;
82
+ readonly redirectUri: string;
83
+ readonly challenge: string;
84
+ readonly resource: string;
85
+ readonly scope: string;
86
+ readonly accountId: string;
87
+ /** A hosted shell's viewer sign-in this code finishes (INTERFACES §18.4). */
88
+ readonly viewerSignin?: string;
89
+ /**
90
+ * Whether the authorization request named its redirect URI; the token request must name it
91
+ * too then (OAuth 2.1 §4.1.3). Absent: it did.
92
+ */
93
+ readonly redirectGiven?: boolean;
94
+ }
95
+
96
+ /** A sign-in identity resolved to the server's account, or why not. */
97
+ export type ResolvedAccount =
98
+ | { readonly kind: "account"; readonly accountId: string; readonly name: string | undefined }
99
+ | { readonly kind: "step"; readonly url: string }
100
+ | { readonly kind: "refused"; readonly message: string }
101
+ | { readonly kind: "suspended" }
102
+ | { readonly kind: "unavailable" };
103
+
104
+ /** The SHA-256 of a secret, as the directory stores it. */
105
+ export function hashSecret(secret: string): string {
106
+ return createHash("sha256").update(secret).digest("hex");
107
+ }
108
+
109
+ function secret(): string {
110
+ return randomBytes(32).toString("base64url");
111
+ }
112
+
113
+ function userCode(): string {
114
+ let code = "";
115
+ for (let index = 0; index < 8; index++)
116
+ code += USER_CODE_LETTERS[randomInt(USER_CODE_LETTERS.length)];
117
+ return code;
118
+ }
119
+
120
+ /** Whether a PKCE verifier hashes to the S256 challenge (RFC 7636 §4.6), in constant time. */
121
+ export function pkceMatches(verifier: string, challenge: string): boolean {
122
+ if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) return false;
123
+ const computed = createHash("sha256").update(verifier).digest("base64url");
124
+ return (
125
+ computed.length === challenge.length &&
126
+ timingSafeEqual(Buffer.from(computed), Buffer.from(challenge))
127
+ );
128
+ }
129
+
130
+ /**
131
+ * A resource indicator in its canonical form (RFC 8707; the MCP specification): scheme and host in
132
+ * lower case, no trailing slash, no fragment. An unusable one answers `""`.
133
+ */
134
+ export function canonicalResource(resource: string): string {
135
+ try {
136
+ // WHATWG URL parsing already lower-cases the scheme and host.
137
+ const url = new URL(resource);
138
+ if (url.hash !== "" || url.search !== "") return "";
139
+ return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, "")}`;
140
+ } catch {
141
+ return "";
142
+ }
143
+ }
144
+
145
+ /** `abcd-efgh`, `ABCDEFGH` → `ABCDEFGH`. */
146
+ function normalizeUserCode(input: string): string {
147
+ return input.toUpperCase().replace(/[^A-Z]/g, "");
148
+ }
149
+
150
+ /** The device grant's state, kept in its `token` row's `data_json`. */
151
+ interface DeviceState {
152
+ readonly userCode: string;
153
+ readonly status: "pending" | "approved" | "denied";
154
+ readonly accountId?: string;
155
+ readonly instance?: string;
156
+ readonly name?: string;
157
+ readonly lastPollAt?: number;
158
+ /** The instance asked to become the account's default (`mostra login --default`). */
159
+ readonly makeDefault?: boolean;
160
+ }
161
+
162
+ /** Options for {@link createAuthorization}. */
163
+ export interface AuthorizationOptions {
164
+ readonly directory: Ledger;
165
+ readonly config: RemoteServerConfig;
166
+ readonly log: Log;
167
+ /** The operator module, for `accounts.resolve` and `accounts.status` (D165 item 9). */
168
+ readonly operator?: Operator;
169
+ readonly now?: () => number;
170
+ /** How long an access token lasts; an hour unless tests shorten it. */
171
+ readonly accessTtlMs?: number;
172
+ /** How long a used refresh token returns its successor; 30 s unless tests shorten it. */
173
+ readonly rotationGraceMs?: number;
174
+ /**
175
+ * Called when an instance link was made or bound again (`instance.linked`, §18.5): the server
176
+ * appends the event in the hosted home.
177
+ */
178
+ readonly linked?: (event: {
179
+ readonly homeId: string;
180
+ readonly linkId: string;
181
+ readonly name: string;
182
+ }) => void;
183
+ }
184
+
185
+ /** The authorization server. */
186
+ export interface Authorization {
187
+ /** `POST /oauth/device`. */
188
+ device(form: URLSearchParams): Record<string, unknown> | OAuthError;
189
+ /** `POST /oauth/token`. */
190
+ token(form: URLSearchParams): TokenAnswer | OAuthError;
191
+ /** `POST /oauth/revoke` (RFC 7009): revokes the grant a token belongs to. */
192
+ revoke(form: URLSearchParams): void;
193
+ /** What a bearer token names, or `undefined` when it is unknown, expired or revoked. */
194
+ authenticate(bearer: string): Authenticated | undefined;
195
+ /** Whether a grant is still live (not revoked, its account active). */
196
+ grantLive(grantId: string): boolean;
197
+ /** The device page's state for a user code: pending, or why it can't be approved. */
198
+ pendingCode(
199
+ code: string,
200
+ ): { readonly ok: true } | { readonly ok: false; readonly reason: string };
201
+ /**
202
+ * Approves or denies a device code as `person` (the development provider's name, or WP-30's
203
+ * signed-in identity), recording the account's consent for the CLI.
204
+ */
205
+ decide(input: {
206
+ readonly code: string;
207
+ readonly approve: boolean;
208
+ readonly identity: {
209
+ readonly provider: string;
210
+ readonly subject: string;
211
+ readonly name?: string;
212
+ };
213
+ }): { readonly ok: true } | { readonly ok: false; readonly reason: string };
214
+ /** The verification address people open. */
215
+ readonly verificationUri: string;
216
+ /** Approves or denies a device code for an account a browser session signed in as. */
217
+ decideFor(input: {
218
+ readonly code: string;
219
+ readonly approve: boolean;
220
+ readonly accountId: string;
221
+ }): { readonly ok: true } | { readonly ok: false; readonly reason: string };
222
+ /**
223
+ * Resolves a sign-in identity to an account (INTERFACES §18.5): through the operator's
224
+ * `accounts.resolve` when it has one, else the server's own accounts; `steps` counts the first
225
+ * sign-in steps already taken.
226
+ */
227
+ resolveAccount(identity: SignInIdentity, steps: number): Promise<ResolvedAccount>;
228
+ /** An account's display name, and the provider that verified it (its first identity's). */
229
+ accountName(accountId: string): { readonly name?: string; readonly provider?: string };
230
+ /** Mints an authorization code (one minute, single use; only its hash is kept). */
231
+ issueCode(grant: CodeGrant): string;
232
+ /**
233
+ * Redeems a hosted shell's viewer sign-in code (never at the token endpoint): its client, PKCE
234
+ * verifier and sign-in must match. Answers the account, or why not.
235
+ */
236
+ redeemViewerCode(input: {
237
+ readonly code: string;
238
+ readonly verifier: string;
239
+ readonly clientId: string;
240
+ readonly viewerSignin: string;
241
+ }): { readonly accountId: string } | { readonly refused: string };
242
+ /**
243
+ * A session for a credential the operator issued (`accounts.authenticate`, §18.6): the account
244
+ * (kept under the operator's ID), its hosted home, and one instance link per credential subject,
245
+ * so a program holding an operator-issued key runs an always-on owner instance.
246
+ */
247
+ credentialSession(input: {
248
+ readonly account: string;
249
+ readonly subject: string;
250
+ readonly resource: string;
251
+ /** Whether this use links an instance (the binding's, `/host`); `/mcp` and `/files` don't. */
252
+ readonly link: boolean;
253
+ }): Authenticated;
254
+ /** The account a refresh token belongs to, so the operator's word on it is asked first. */
255
+ refreshAccount(refreshToken: string): string | undefined;
256
+ /** An account's standing in the directory. */
257
+ accountStatus(accountId: string): "active" | "suspended";
258
+ /** Records the operator's word on an account (`accounts.status`, §18.6). */
259
+ setAccountStatus(accountId: string, status: "active" | "suspended"): void;
260
+ /**
261
+ * Whether an instance link is its account's default, after making it so when `makeDefault`
262
+ * (`POST /link`, D167; one default per account, as `mostra login --default` makes it).
263
+ */
264
+ linkState(linkId: string, makeDefault: boolean): { readonly default: boolean };
265
+ /** The account's hosted home, made on its first use (one home per owner per server). */
266
+ ensureHome(accountId: string): string;
267
+ /** Whether an account has consented to a client. */
268
+ consented(accountId: string, clientId: string): boolean;
269
+ /** Records an account's consent to a client. */
270
+ consent(accountId: string, clientId: string): void;
271
+ }
272
+
273
+ function oauthError(status: number, error: string, description: string): OAuthError {
274
+ return { status, error, description };
275
+ }
276
+
277
+ /** Creates the authorization server over the server's directory. */
278
+ export function createAuthorization(options: AuthorizationOptions): Authorization {
279
+ const { directory, config, log } = options;
280
+ const now = options.now ?? (() => Date.now());
281
+ const accessTtlMs = options.accessTtlMs ?? ACCESS_TTL_MS;
282
+ const rotationGraceMs = options.rotationGraceMs ?? ROTATION_GRACE_MS;
283
+ const iso = (ms: number): string => new Date(ms).toISOString();
284
+ const verificationUri = `${config.apiOrigin}/device`;
285
+
286
+ directory.write((db) => {
287
+ db.run(
288
+ "INSERT OR IGNORE INTO oauth_client (id, kind, metadata_json, created_at) VALUES (?, 'cli', ?, ?)",
289
+ CLI_CLIENT_ID,
290
+ JSON.stringify({ client_name: "Mostra CLI" }),
291
+ iso(now()),
292
+ );
293
+ });
294
+
295
+ const deviceRow = (db: LedgerDb, hash: string) =>
296
+ db.get<{ data_json: string; expires_at: string }>(
297
+ "SELECT data_json, expires_at FROM token WHERE hash = ? AND kind = 'device'",
298
+ hash,
299
+ );
300
+
301
+ /** An account the operator names: kept in the directory under the operator's own ID. */
302
+ const operatorAccount = (
303
+ db: LedgerDb,
304
+ identity: { provider: string; subject: string; name?: string; email?: string },
305
+ account: string,
306
+ name: string | undefined,
307
+ status: "active" | "suspended",
308
+ ): void => {
309
+ db.run(
310
+ `INSERT INTO account (id, name, status, created_at) VALUES (?, ?, ?, ?)
311
+ ON CONFLICT (id) DO UPDATE SET name = COALESCE(excluded.name, name), status = excluded.status`,
312
+ account,
313
+ name ?? identity.name ?? null,
314
+ status,
315
+ iso(now()),
316
+ );
317
+ db.run(
318
+ `INSERT INTO identity (provider, subject, account_id, email, name, linked_at) VALUES (?, ?, ?, ?, ?, ?)
319
+ ON CONFLICT (provider, subject) DO UPDATE SET account_id = excluded.account_id,
320
+ email = excluded.email, name = excluded.name`,
321
+ identity.provider,
322
+ identity.subject,
323
+ account,
324
+ identity.email ?? null,
325
+ identity.name ?? null,
326
+ iso(now()),
327
+ );
328
+ };
329
+
330
+ /** The account for a sign-in identity, made on the first sign-in. */
331
+ const accountFor = (
332
+ db: LedgerDb,
333
+ identity: { provider: string; subject: string; name?: string },
334
+ ): string => {
335
+ const found = db.get<{ account_id: string }>(
336
+ "SELECT account_id FROM identity WHERE provider = ? AND subject = ?",
337
+ identity.provider,
338
+ identity.subject,
339
+ );
340
+ if (found) return found.account_id;
341
+ const account = AccountId.create();
342
+ db.run(
343
+ "INSERT INTO account (id, name, status, created_at) VALUES (?, ?, 'active', ?)",
344
+ account,
345
+ identity.name ?? null,
346
+ iso(now()),
347
+ );
348
+ db.run(
349
+ "INSERT INTO identity (provider, subject, account_id, name, linked_at) VALUES (?, ?, ?, ?, ?)",
350
+ identity.provider,
351
+ identity.subject,
352
+ account,
353
+ identity.name ?? null,
354
+ iso(now()),
355
+ );
356
+ return account;
357
+ };
358
+
359
+ /** The account's hosted home, made on its first link (one home per owner per server). */
360
+ const homeFor = (db: LedgerDb, account: string): string => {
361
+ const found = db.get<{ id: string }>("SELECT id FROM home WHERE owner_account_id = ?", account);
362
+ if (found) return found.id;
363
+ const home = HomeId.create();
364
+ db.run(
365
+ "INSERT INTO home (id, owner_account_id, data_path, created_at) VALUES (?, ?, ?, ?)",
366
+ home,
367
+ account,
368
+ `homes/${home}`,
369
+ iso(now()),
370
+ );
371
+ return home;
372
+ };
373
+
374
+ /** Makes or binds again the instance link a sign-in names. */
375
+ const linkFor = (
376
+ db: LedgerDb,
377
+ account: string,
378
+ home: string,
379
+ wanted: string | undefined,
380
+ name: string,
381
+ ): string => {
382
+ if (wanted !== undefined && LinkId.is(wanted)) {
383
+ const row = db.get<{ account_id: string }>(
384
+ "SELECT account_id FROM instance_link WHERE id = ?",
385
+ wanted,
386
+ );
387
+ // A link is rebound only for its own account: another account's ID names nothing here.
388
+ if (row?.account_id === account) {
389
+ db.run("UPDATE instance_link SET revoked_at = NULL, name = ? WHERE id = ?", name, wanted);
390
+ return wanted;
391
+ }
392
+ }
393
+ const link = LinkId.create();
394
+ const first =
395
+ db.get<{ n: number }>("SELECT COUNT(*) AS n FROM instance_link WHERE account_id = ?", account)
396
+ ?.n === 0;
397
+ db.run(
398
+ "INSERT INTO instance_link (id, account_id, home_id, name, is_default, relay_high, linked_at) VALUES (?, ?, ?, ?, ?, 0, ?)",
399
+ link,
400
+ account,
401
+ home,
402
+ name,
403
+ first ? 1 : 0,
404
+ iso(now()),
405
+ );
406
+ return link;
407
+ };
408
+
409
+ /** Issues an access and a refresh token for a grant. */
410
+ const issue = (db: LedgerDb, grantId: string): { access: string; refresh: string } => {
411
+ const access = secret();
412
+ const refresh = secret();
413
+ db.run(
414
+ "INSERT INTO token (hash, grant_id, kind, expires_at) VALUES (?, ?, 'access', ?)",
415
+ hashSecret(access),
416
+ grantId,
417
+ iso(now() + accessTtlMs),
418
+ );
419
+ db.run(
420
+ "INSERT INTO token (hash, grant_id, kind, expires_at) VALUES (?, ?, 'refresh', ?)",
421
+ hashSecret(refresh),
422
+ grantId,
423
+ iso(now() + REFRESH_TTL_MS),
424
+ );
425
+ return { access, refresh };
426
+ };
427
+
428
+ const answer = (
429
+ db: LedgerDb,
430
+ grantId: string,
431
+ tokens: { access: string; refresh: string },
432
+ ): TokenAnswer => {
433
+ const row = db.get<{
434
+ account_id: string;
435
+ link_id: string | null;
436
+ name: string | null;
437
+ is_default: number | null;
438
+ home_id: string | null;
439
+ scope: string;
440
+ }>(
441
+ `SELECT g.account_id, g.link_id, a.name, l.is_default, l.home_id, g.scope
442
+ FROM "grant" g JOIN account a ON a.id = g.account_id
443
+ LEFT JOIN instance_link l ON l.id = g.link_id WHERE g.id = ?`,
444
+ grantId,
445
+ );
446
+ if (!row) throw new Error("grant vanished");
447
+ return {
448
+ access_token: tokens.access,
449
+ token_type: "Bearer",
450
+ expires_in: Math.max(1, Math.floor(accessTtlMs / 1000)),
451
+ refresh_token: tokens.refresh,
452
+ scope: row.scope,
453
+ mostra_account: { id: row.account_id, ...(row.name !== null ? { name: row.name } : {}) },
454
+ // An instance's link, for the CLI's device grant; an MCP client's grant has none.
455
+ ...(row.link_id !== null
456
+ ? {
457
+ mostra_instance: row.link_id,
458
+ mostra_default: row.is_default === 1,
459
+ mostra_home: row.home_id ?? "",
460
+ }
461
+ : {}),
462
+ };
463
+ };
464
+
465
+ /**
466
+ * The successors of refresh tokens used in the last 30 s, by the used token's hash: kept in
467
+ * memory only, so the directory never holds a usable secret. After a restart inside the grace, a
468
+ * repeated refresh is refused without revoking anything; the client still holds its successor.
469
+ */
470
+ const recent = new Map<
471
+ string,
472
+ { readonly tokens: { access: string; refresh: string }; readonly at: number }
473
+ >();
474
+ const forgetOld = (): void => {
475
+ for (const [hash, entry] of recent) if (now() - entry.at > rotationGraceMs) recent.delete(hash);
476
+ };
477
+
478
+ /** `grant_type=refresh_token`: rotation with a 30 s grace, reuse after it revokes the grant. */
479
+ const refresh = (form: URLSearchParams, clientId: string): TokenAnswer | OAuthError => {
480
+ const presented = form.get("refresh_token") ?? "";
481
+ const hash = hashSecret(presented);
482
+ return directory.write((db): TokenAnswer | OAuthError => {
483
+ const row = db.get<{
484
+ grant_id: string;
485
+ expires_at: string;
486
+ used_at: string | null;
487
+ }>(
488
+ "SELECT grant_id, expires_at, used_at FROM token WHERE hash = ? AND kind = 'refresh'",
489
+ hash,
490
+ );
491
+ if (
492
+ !row ||
493
+ !grantLiveIn(db, row.grant_id, { anyStatus: true }) ||
494
+ grantClient(db, row.grant_id) !== clientId
495
+ ) {
496
+ return oauthError(400, "invalid_grant", "The refresh token isn't valid; sign in again.");
497
+ }
498
+ // A suspended account's refresh token stays good: the refresh is refused for now, without
499
+ // touching the token, so the instance or client keeps it and refreshes once the operator
500
+ // lifts the suspension. `invalid_grant` would tell it to sign in again (second Fable
501
+ // review of WP-30, 1).
502
+ if (!grantLiveIn(db, row.grant_id)) {
503
+ return oauthError(
504
+ 403,
505
+ "temporarily_unavailable",
506
+ "This account is suspended; its sign-in works again once the server's operator lifts the suspension.",
507
+ );
508
+ }
509
+ if (Date.parse(row.expires_at) <= now()) {
510
+ return oauthError(400, "invalid_grant", "The refresh token expired; sign in again.");
511
+ }
512
+ if (row.used_at !== null) {
513
+ const used = Date.parse(row.used_at);
514
+ forgetOld();
515
+ if (now() - used <= rotationGraceMs) {
516
+ // A parallel refresh within the grace: the same successor (§18.5).
517
+ const kept = recent.get(hash);
518
+ if (kept) return answer(db, row.grant_id, kept.tokens);
519
+ return oauthError(
520
+ 400,
521
+ "invalid_grant",
522
+ "This refresh token was just used; use its successor.",
523
+ );
524
+ }
525
+ // A refresh token used again after its grace: someone else holds it. The grant goes.
526
+ db.run('UPDATE "grant" SET revoked_at = ? WHERE id = ?', iso(now()), row.grant_id);
527
+ log.warn("auth.refresh_reused", { grant: row.grant_id });
528
+ return oauthError(
529
+ 400,
530
+ "invalid_grant",
531
+ "The refresh token was used before; sign in again.",
532
+ );
533
+ }
534
+ const tokens = issue(db, row.grant_id);
535
+ db.run(
536
+ "UPDATE token SET used_at = ?, successor_hash = ? WHERE hash = ?",
537
+ iso(now()),
538
+ hashSecret(tokens.refresh),
539
+ hash,
540
+ );
541
+ forgetOld();
542
+ recent.set(hash, { tokens, at: now() });
543
+ return answer(db, row.grant_id, tokens);
544
+ });
545
+ };
546
+
547
+ /** The client a grant is for. */
548
+ const grantClient = (db: LedgerDb, grantId: string): string | undefined =>
549
+ db.get<{ client_id: string }>('SELECT client_id FROM "grant" WHERE id = ?', grantId)?.client_id;
550
+
551
+ const grantLiveIn = (
552
+ db: LedgerDb,
553
+ grantId: string,
554
+ options: { readonly anyStatus?: boolean } = {},
555
+ ): boolean => {
556
+ // An operator's credential is checked by asking the operator, by the binding's watch.
557
+ if (grantId.startsWith("credential:")) return true;
558
+ const row = db.get<{ revoked_at: string | null; status: string }>(
559
+ 'SELECT g.revoked_at, a.status FROM "grant" g JOIN account a ON a.id = g.account_id WHERE g.id = ?',
560
+ grantId,
561
+ );
562
+ return (
563
+ row !== undefined &&
564
+ row.revoked_at === null &&
565
+ (options.anyStatus === true || row.status === "active")
566
+ );
567
+ };
568
+
569
+ return {
570
+ verificationUri,
571
+
572
+ device(form) {
573
+ if (form.get("client_id") !== CLI_CLIENT_ID) {
574
+ return oauthError(401, "invalid_client", "Only the Mostra CLI uses the device grant here.");
575
+ }
576
+ const scope = form.get("scope") ?? "mostra";
577
+ if (!scope.split(" ").every((part) => part === "mostra" || part === "offline_access")) {
578
+ return oauthError(400, "invalid_scope", "The only scope is mostra.");
579
+ }
580
+ const deviceCode = secret();
581
+ const code = userCode();
582
+ const instance = form.get("mostra_instance") ?? undefined;
583
+ const name = (form.get("mostra_name") ?? "").slice(0, 128) || "Mostra instance";
584
+ const state: DeviceState = {
585
+ userCode: code,
586
+ status: "pending",
587
+ name,
588
+ ...(instance !== undefined ? { instance } : {}),
589
+ ...(form.get("mostra_default") === "1" ? { makeDefault: true } : {}),
590
+ };
591
+ directory.write((db) =>
592
+ db.run(
593
+ "INSERT INTO token (hash, kind, expires_at, data_json) VALUES (?, 'device', ?, ?)",
594
+ hashSecret(deviceCode),
595
+ iso(now() + DEVICE_TTL_MS),
596
+ JSON.stringify(state),
597
+ ),
598
+ );
599
+ const shown = `${code.slice(0, 4)}-${code.slice(4)}`;
600
+ log.info("auth.device_started", {});
601
+ return {
602
+ device_code: deviceCode,
603
+ user_code: shown,
604
+ verification_uri: verificationUri,
605
+ verification_uri_complete: `${verificationUri}?user_code=${shown}`,
606
+ expires_in: Math.floor(DEVICE_TTL_MS / 1000),
607
+ interval: DEVICE_INTERVAL_S,
608
+ };
609
+ },
610
+
611
+ token(form) {
612
+ const grantType = form.get("grant_type");
613
+ const clientId = form.get("client_id") ?? "";
614
+ if (grantType === "authorization_code") {
615
+ const code = form.get("code") ?? "";
616
+ const hash = hashSecret(code);
617
+ return directory.write((db): TokenAnswer | OAuthError => {
618
+ const row = db.get<{ data_json: string; expires_at: string; used_at: string | null }>(
619
+ "SELECT data_json, expires_at, used_at FROM token WHERE hash = ? AND kind = 'code'",
620
+ hash,
621
+ );
622
+ if (row?.used_at != null) {
623
+ // A code presented again: someone else may hold it, so what it gave is revoked
624
+ // (OAuth 2.1 §4.1.3, RFC 9700 §4.5.3).
625
+ const spent = JSON.parse(row.data_json) as CodeGrant & { readonly grantId?: string };
626
+ if (spent.grantId !== undefined) {
627
+ db.run(
628
+ 'UPDATE "grant" SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL',
629
+ iso(now()),
630
+ spent.grantId,
631
+ );
632
+ log.warn("auth.code_reused", { grant: spent.grantId });
633
+ }
634
+ return oauthError(400, "invalid_grant", "The code is unknown, used or expired.");
635
+ }
636
+ // Spent at its first presentation, whatever comes of it: a code works once. The row is
637
+ // kept (as a hash) until it is long expired, so a second presentation is recognized.
638
+ // Code rows only: a refresh token sent as a code is no code, and is left alone.
639
+ db.run("UPDATE token SET used_at = ? WHERE hash = ? AND kind = 'code'", iso(now()), hash);
640
+ if (!row || Date.parse(row.expires_at) <= now()) {
641
+ return oauthError(400, "invalid_grant", "The code is unknown, used or expired.");
642
+ }
643
+ const grant = JSON.parse(row.data_json) as CodeGrant;
644
+ if (grant.viewerSignin !== undefined) {
645
+ return oauthError(
646
+ 400,
647
+ "invalid_grant",
648
+ "This code is a page's sign-in, not a client's.",
649
+ );
650
+ }
651
+ if (grant.clientId !== clientId) {
652
+ return oauthError(400, "invalid_grant", "The code was issued to another client.");
653
+ }
654
+ // Required when the authorization request named it (OAuth 2.1 §4.1.3), and the same.
655
+ const redirectUri = form.get("redirect_uri");
656
+ if (
657
+ (redirectUri === null && grant.redirectGiven !== false) ||
658
+ (redirectUri !== null && redirectUri !== grant.redirectUri)
659
+ ) {
660
+ return oauthError(
661
+ 400,
662
+ "invalid_grant",
663
+ "redirect_uri isn't the one the code was issued for.",
664
+ );
665
+ }
666
+ if (!pkceMatches(form.get("code_verifier") ?? "", grant.challenge)) {
667
+ return oauthError(400, "invalid_grant", "The PKCE code_verifier doesn't match.");
668
+ }
669
+ const resource = form.get("resource");
670
+ if (resource !== null && canonicalResource(resource) !== grant.resource) {
671
+ return oauthError(
672
+ 400,
673
+ "invalid_target",
674
+ "resource isn't the one the code was issued for.",
675
+ );
676
+ }
677
+ const grantId = `grt_${randomBytes(16).toString("hex")}`;
678
+ db.run(
679
+ 'INSERT INTO "grant" (id, account_id, client_id, scope, resource, link_id, created_at) VALUES (?, ?, ?, ?, ?, NULL, ?)',
680
+ grantId,
681
+ grant.accountId,
682
+ grant.clientId,
683
+ grant.scope,
684
+ grant.resource,
685
+ iso(now()),
686
+ );
687
+ db.run(
688
+ "UPDATE token SET data_json = ? WHERE hash = ? AND kind = 'code'",
689
+ JSON.stringify({ ...grant, grantId }),
690
+ hash,
691
+ );
692
+ log.info("auth.code_redeemed", { client: grant.clientId, grant: grantId });
693
+ return answer(db, grantId, issue(db, grantId));
694
+ });
695
+ }
696
+ if (grantType === "refresh_token") return refresh(form, clientId);
697
+ if (clientId !== CLI_CLIENT_ID) {
698
+ return oauthError(401, "invalid_client", "Unknown client.");
699
+ }
700
+ if (grantType === DEVICE_GRANT) {
701
+ const deviceCode = form.get("device_code") ?? "";
702
+ const hash = hashSecret(deviceCode);
703
+ return directory.write((db): TokenAnswer | OAuthError => {
704
+ const row = deviceRow(db, hash);
705
+ if (!row) return oauthError(400, "invalid_grant", "Unknown device code.");
706
+ if (Date.parse(row.expires_at) <= now()) {
707
+ return oauthError(400, "expired_token", "The code expired; sign in again.");
708
+ }
709
+ const state = JSON.parse(row.data_json) as DeviceState;
710
+ if (state.status === "denied") {
711
+ return oauthError(400, "access_denied", "The sign-in was refused.");
712
+ }
713
+ if (state.status === "pending") {
714
+ const tooSoon =
715
+ state.lastPollAt !== undefined &&
716
+ now() - state.lastPollAt < DEVICE_INTERVAL_S * 1000 - 250;
717
+ db.run(
718
+ "UPDATE token SET data_json = ? WHERE hash = ?",
719
+ JSON.stringify({ ...state, lastPollAt: now() }),
720
+ hash,
721
+ );
722
+ return tooSoon
723
+ ? oauthError(400, "slow_down", "Poll less often.")
724
+ : oauthError(400, "authorization_pending", "Waiting for the person to approve.");
725
+ }
726
+ // Approved: one grant, once. The device code is spent here.
727
+ const account = state.accountId as string;
728
+ const home = homeFor(db, account);
729
+ const link = linkFor(db, account, home, state.instance, state.name ?? "Mostra instance");
730
+ // `mostra login --default` makes this instance the account's default (D165 item 1b):
731
+ // chat-host authoring goes to it. One default per account (a unique index).
732
+ if (state.makeDefault === true) {
733
+ db.run(
734
+ "UPDATE instance_link SET is_default = 0 WHERE account_id = ? AND id != ?",
735
+ account,
736
+ link,
737
+ );
738
+ db.run("UPDATE instance_link SET is_default = 1 WHERE id = ?", link);
739
+ }
740
+ const grantId = `grt_${randomBytes(16).toString("hex")}`;
741
+ db.run(
742
+ 'INSERT INTO "grant" (id, account_id, client_id, scope, resource, link_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
743
+ grantId,
744
+ account,
745
+ CLI_CLIENT_ID,
746
+ "mostra",
747
+ `${config.apiOrigin}/host`,
748
+ link,
749
+ iso(now()),
750
+ );
751
+ db.run("DELETE FROM token WHERE hash = ?", hash);
752
+ const tokens = issue(db, grantId);
753
+ setImmediate(() =>
754
+ options.linked?.({ homeId: home, linkId: link, name: state.name ?? "" }),
755
+ );
756
+ log.info("auth.linked", { account, home, link });
757
+ return answer(db, grantId, tokens);
758
+ });
759
+ }
760
+ return oauthError(
761
+ 400,
762
+ "unsupported_grant_type",
763
+ "Use authorization_code, refresh_token or the device grant.",
764
+ );
765
+ },
766
+
767
+ revoke(form) {
768
+ const presented = form.get("token") ?? "";
769
+ const hash = hashSecret(presented);
770
+ directory.write((db) => {
771
+ const row = db.get<{ grant_id: string | null }>(
772
+ "SELECT grant_id FROM token WHERE hash = ?",
773
+ hash,
774
+ );
775
+ if (row?.grant_id) {
776
+ db.run(
777
+ 'UPDATE "grant" SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL',
778
+ iso(now()),
779
+ row.grant_id,
780
+ );
781
+ log.info("auth.revoked", { grant: row.grant_id });
782
+ }
783
+ });
784
+ },
785
+
786
+ authenticate(bearer) {
787
+ if (bearer.length < 20 || bearer.length > 200) return undefined;
788
+ const hash = hashSecret(bearer);
789
+ return directory.read((db) => {
790
+ const row = db.get<{
791
+ hash: string;
792
+ expires_at: string;
793
+ grant_id: string;
794
+ account_id: string;
795
+ link_id: string | null;
796
+ name: string | null;
797
+ resource: string;
798
+ client_id: string;
799
+ scope: string;
800
+ }>(
801
+ `SELECT t.hash, t.expires_at, t.grant_id, g.account_id, g.link_id, a.name, g.resource, g.client_id, g.scope
802
+ FROM token t JOIN "grant" g ON g.id = t.grant_id JOIN account a ON a.id = g.account_id
803
+ WHERE t.hash = ? AND t.kind = 'access'`,
804
+ hash,
805
+ );
806
+ if (!row) return undefined;
807
+ // Constant-time on what was found, though the lookup was by hash already.
808
+ if (!timingSafeEqual(Buffer.from(row.hash), Buffer.from(hash))) return undefined;
809
+ const expiresAt = Date.parse(row.expires_at);
810
+ // A suspended account's token still names it, so its caller hears "suspended" (403)
811
+ // rather than "sign in again", and the operator's later word can lift it (D165 item 9).
812
+ if (expiresAt <= now() || !grantLiveIn(db, row.grant_id, { anyStatus: true }))
813
+ return undefined;
814
+ const home = db.get<{ id: string }>(
815
+ "SELECT id FROM home WHERE owner_account_id = ?",
816
+ row.account_id,
817
+ );
818
+ // An MCP client's account may have no home yet: it gets one at its first hosted call.
819
+ if (!home && row.resource.endsWith("/host")) return undefined;
820
+ return {
821
+ resource: row.resource,
822
+ clientId: row.client_id,
823
+ scope: row.scope,
824
+ accountId: row.account_id,
825
+ accountName: row.name ?? undefined,
826
+ grantId: row.grant_id,
827
+ homeId: home?.id ?? "",
828
+ linkId: row.link_id ?? undefined,
829
+ expiresAt,
830
+ };
831
+ });
832
+ },
833
+
834
+ decideFor(input) {
835
+ const wanted = normalizeUserCode(input.code);
836
+ return directory.write((db) => {
837
+ const rows = db.all<{ hash: string; data_json: string }>(
838
+ "SELECT hash, data_json FROM token WHERE kind = 'device' AND expires_at > ?",
839
+ iso(now()),
840
+ );
841
+ const row = rows.find(
842
+ (candidate) => (JSON.parse(candidate.data_json) as DeviceState).userCode === wanted,
843
+ );
844
+ if (!row) return { ok: false as const, reason: "That code is unknown or has expired." };
845
+ const state = JSON.parse(row.data_json) as DeviceState;
846
+ if (state.status !== "pending")
847
+ return { ok: false as const, reason: "That code was already used." };
848
+ db.run(
849
+ "UPDATE token SET data_json = ? WHERE hash = ?",
850
+ JSON.stringify(
851
+ input.approve
852
+ ? { ...state, status: "approved", accountId: input.accountId }
853
+ : { ...state, status: "denied" },
854
+ ),
855
+ row.hash,
856
+ );
857
+ if (input.approve) {
858
+ db.run(
859
+ "INSERT INTO consent (account_id, client_id, granted_at) VALUES (?, ?, ?) ON CONFLICT (account_id, client_id) DO UPDATE SET revoked_at = NULL",
860
+ input.accountId,
861
+ CLI_CLIENT_ID,
862
+ iso(now()),
863
+ );
864
+ }
865
+ return { ok: true as const };
866
+ });
867
+ },
868
+
869
+ async resolveAccount(identity, steps) {
870
+ const verdict = options.operator
871
+ ? await options.operator.resolve(identity, steps)
872
+ : ({ default: true } as const);
873
+ if (verdict === "unavailable") return { kind: "unavailable" };
874
+ if ("default" in verdict) {
875
+ const accountId = directory.write((db) => accountFor(db, identity));
876
+ const status = directory.read(
877
+ (db) =>
878
+ db.get<{ status: string }>("SELECT status FROM account WHERE id = ?", accountId)
879
+ ?.status,
880
+ );
881
+ if (status === "suspended") return { kind: "suspended" };
882
+ return { kind: "account", accountId, name: identity.name };
883
+ }
884
+ if ("step" in verdict) return { kind: "step", url: verdict.step.url };
885
+ if ("refused" in verdict) return { kind: "refused", message: verdict.refused.message };
886
+ directory.write((db) =>
887
+ operatorAccount(db, identity, verdict.account, verdict.name, verdict.status),
888
+ );
889
+ if (verdict.status === "suspended") return { kind: "suspended" };
890
+ return { kind: "account", accountId: verdict.account, name: verdict.name ?? identity.name };
891
+ },
892
+
893
+ accountName(accountId) {
894
+ return directory.read((db) => {
895
+ const row = db.get<{ name: string | null; provider: string | null }>(
896
+ `SELECT a.name, (SELECT i.provider FROM identity i WHERE i.account_id = a.id
897
+ ORDER BY i.linked_at LIMIT 1) AS provider FROM account a WHERE a.id = ?`,
898
+ accountId,
899
+ );
900
+ return {
901
+ ...(row?.name ? { name: row.name } : {}),
902
+ ...(row?.provider ? { provider: row.provider } : {}),
903
+ };
904
+ });
905
+ },
906
+
907
+ issueCode(grant) {
908
+ const code = secret();
909
+ directory.write((db) => {
910
+ // Codes are kept a while after use to recognize a second presentation, then dropped.
911
+ db.run(
912
+ "DELETE FROM token WHERE kind = 'code' AND expires_at < ?",
913
+ iso(now() - CODE_KEPT_MS),
914
+ );
915
+ db.run(
916
+ "INSERT INTO token (hash, kind, expires_at, data_json) VALUES (?, 'code', ?, ?)",
917
+ hashSecret(code),
918
+ iso(now() + CODE_TTL_MS),
919
+ JSON.stringify(grant),
920
+ );
921
+ });
922
+ return code;
923
+ },
924
+
925
+ redeemViewerCode(input) {
926
+ const hash = hashSecret(input.code);
927
+ return directory.write((db) => {
928
+ const row = db.get<{ data_json: string; expires_at: string }>(
929
+ "SELECT data_json, expires_at FROM token WHERE hash = ? AND kind = 'code'",
930
+ hash,
931
+ );
932
+ db.run("DELETE FROM token WHERE hash = ?", hash);
933
+ if (!row || Date.parse(row.expires_at) <= now()) {
934
+ return { refused: "The sign-in code is unknown, used or expired." };
935
+ }
936
+ const grant = JSON.parse(row.data_json) as CodeGrant;
937
+ if (grant.viewerSignin === undefined || grant.viewerSignin !== input.viewerSignin) {
938
+ return { refused: "This sign-in code was started for another page." };
939
+ }
940
+ if (grant.clientId !== input.clientId) {
941
+ return { refused: "This sign-in code was issued to another shell." };
942
+ }
943
+ if (!pkceMatches(input.verifier, grant.challenge)) {
944
+ return { refused: "The sign-in's PKCE verifier doesn't match." };
945
+ }
946
+ return { accountId: grant.accountId };
947
+ });
948
+ },
949
+
950
+ credentialSession(input) {
951
+ return directory.write((db) => {
952
+ db.run(
953
+ "INSERT INTO account (id, name, status, created_at) VALUES (?, NULL, 'active', ?) ON CONFLICT (id) DO NOTHING",
954
+ input.account,
955
+ iso(now()),
956
+ );
957
+ const home = homeFor(db, input.account);
958
+ let link = db.get<{ link_id: string }>(
959
+ "SELECT link_id FROM credential_link WHERE account_id = ? AND subject = ?",
960
+ input.account,
961
+ input.subject,
962
+ )?.link_id;
963
+ // Only a binding makes the key's instance link: a key used on /mcp or /files first names
964
+ // none, so no link that never binds takes the account's default (Fable review, 3).
965
+ if (link === undefined && input.link) {
966
+ link = linkFor(
967
+ db,
968
+ input.account,
969
+ home,
970
+ undefined,
971
+ `Service key ${input.subject}`.slice(0, 128),
972
+ );
973
+ db.run(
974
+ "INSERT INTO credential_link (account_id, subject, link_id) VALUES (?, ?, ?)",
975
+ input.account,
976
+ input.subject,
977
+ link,
978
+ );
979
+ }
980
+ const name = db.get<{ name: string | null }>(
981
+ "SELECT name FROM account WHERE id = ?",
982
+ input.account,
983
+ )?.name;
984
+ return {
985
+ resource: input.resource,
986
+ clientId: "operator",
987
+ scope: "mostra",
988
+ accountId: input.account,
989
+ accountName: name ?? undefined,
990
+ // Not a grant of this server: the operator is asked again while the binding stays open.
991
+ grantId: `credential:${input.account}:${input.subject}`,
992
+ homeId: home,
993
+ linkId: link,
994
+ expiresAt: now() + accessTtlMs,
995
+ };
996
+ });
997
+ },
998
+
999
+ refreshAccount(refreshToken) {
1000
+ return directory.read(
1001
+ (db) =>
1002
+ db.get<{ account_id: string }>(
1003
+ "SELECT g.account_id FROM token t JOIN \"grant\" g ON g.id = t.grant_id WHERE t.hash = ? AND t.kind = 'refresh'",
1004
+ hashSecret(refreshToken),
1005
+ )?.account_id,
1006
+ );
1007
+ },
1008
+
1009
+ accountStatus(accountId) {
1010
+ return directory.read((db) =>
1011
+ db.get<{ status: string }>("SELECT status FROM account WHERE id = ?", accountId)?.status ===
1012
+ "suspended"
1013
+ ? "suspended"
1014
+ : "active",
1015
+ );
1016
+ },
1017
+
1018
+ setAccountStatus(accountId, status) {
1019
+ directory.write((db) =>
1020
+ db.run(
1021
+ "UPDATE account SET status = ? WHERE id = ? AND status != ?",
1022
+ status,
1023
+ accountId,
1024
+ status,
1025
+ ),
1026
+ );
1027
+ },
1028
+
1029
+ linkState(linkId, makeDefault) {
1030
+ return directory.write((db) => {
1031
+ if (makeDefault) {
1032
+ const owner = db.get<{ account_id: string }>(
1033
+ "SELECT account_id FROM instance_link WHERE id = ?",
1034
+ linkId,
1035
+ );
1036
+ if (owner) {
1037
+ db.run(
1038
+ "UPDATE instance_link SET is_default = 0 WHERE account_id = ? AND id != ?",
1039
+ owner.account_id,
1040
+ linkId,
1041
+ );
1042
+ db.run("UPDATE instance_link SET is_default = 1 WHERE id = ?", linkId);
1043
+ }
1044
+ }
1045
+ const row = db.get<{ is_default: number }>(
1046
+ "SELECT is_default FROM instance_link WHERE id = ?",
1047
+ linkId,
1048
+ );
1049
+ return { default: row?.is_default === 1 };
1050
+ });
1051
+ },
1052
+
1053
+ ensureHome(accountId) {
1054
+ return directory.write((db) => homeFor(db, accountId));
1055
+ },
1056
+
1057
+ consented(accountId, clientId) {
1058
+ return directory.read(
1059
+ (db) =>
1060
+ db.get(
1061
+ "SELECT 1 FROM consent WHERE account_id = ? AND client_id = ? AND revoked_at IS NULL",
1062
+ accountId,
1063
+ clientId,
1064
+ ) !== undefined,
1065
+ );
1066
+ },
1067
+
1068
+ consent(accountId, clientId) {
1069
+ directory.write((db) =>
1070
+ db.run(
1071
+ "INSERT INTO consent (account_id, client_id, granted_at) VALUES (?, ?, ?) ON CONFLICT (account_id, client_id) DO UPDATE SET revoked_at = NULL, granted_at = excluded.granted_at",
1072
+ accountId,
1073
+ clientId,
1074
+ iso(now()),
1075
+ ),
1076
+ );
1077
+ },
1078
+
1079
+ grantLive(grantId) {
1080
+ return directory.read((db) => grantLiveIn(db, grantId));
1081
+ },
1082
+
1083
+ pendingCode(code) {
1084
+ const wanted = normalizeUserCode(code);
1085
+ return directory.read((db) => {
1086
+ const rows = db.all<{ data_json: string; expires_at: string }>(
1087
+ "SELECT data_json, expires_at FROM token WHERE kind = 'device' AND expires_at > ?",
1088
+ iso(now()),
1089
+ );
1090
+ const row = rows.find(
1091
+ (candidate) => (JSON.parse(candidate.data_json) as DeviceState).userCode === wanted,
1092
+ );
1093
+ if (!row) return { ok: false as const, reason: "That code is unknown or has expired." };
1094
+ const state = JSON.parse(row.data_json) as DeviceState;
1095
+ return state.status === "pending"
1096
+ ? { ok: true as const }
1097
+ : { ok: false as const, reason: "That code was already used." };
1098
+ });
1099
+ },
1100
+
1101
+ decide(input) {
1102
+ const wanted = normalizeUserCode(input.code);
1103
+ return directory.write((db) => {
1104
+ const rows = db.all<{ hash: string; data_json: string }>(
1105
+ "SELECT hash, data_json FROM token WHERE kind = 'device' AND expires_at > ?",
1106
+ iso(now()),
1107
+ );
1108
+ const row = rows.find(
1109
+ (candidate) => (JSON.parse(candidate.data_json) as DeviceState).userCode === wanted,
1110
+ );
1111
+ if (!row) return { ok: false as const, reason: "That code is unknown or has expired." };
1112
+ const state = JSON.parse(row.data_json) as DeviceState;
1113
+ if (state.status !== "pending")
1114
+ return { ok: false as const, reason: "That code was already used." };
1115
+ if (!input.approve) {
1116
+ db.run(
1117
+ "UPDATE token SET data_json = ? WHERE hash = ?",
1118
+ JSON.stringify({ ...state, status: "denied" }),
1119
+ row.hash,
1120
+ );
1121
+ return { ok: true as const };
1122
+ }
1123
+ const account = accountFor(db, input.identity);
1124
+ db.run(
1125
+ "INSERT INTO consent (account_id, client_id, granted_at) VALUES (?, ?, ?) ON CONFLICT (account_id, client_id) DO UPDATE SET revoked_at = NULL",
1126
+ account,
1127
+ CLI_CLIENT_ID,
1128
+ iso(now()),
1129
+ );
1130
+ db.run(
1131
+ "UPDATE token SET data_json = ? WHERE hash = ?",
1132
+ JSON.stringify({ ...state, status: "approved", accountId: account }),
1133
+ row.hash,
1134
+ );
1135
+ return { ok: true as const };
1136
+ });
1137
+ },
1138
+ };
1139
+ }