@cosmicdrift/kumiko-framework 0.386.0 → 0.388.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 (468) hide show
  1. package/AGENTS.md +6 -1
  2. package/LICENSE +21 -57
  3. package/README.md +2 -2
  4. package/agents/examples/anonymous-access.md +1 -1
  5. package/agents/examples/apex-landing.md +204 -0
  6. package/agents/examples/api-worker-split.md +64 -0
  7. package/agents/examples/app-config.md +14 -0
  8. package/agents/examples/auth-mfa.md +115 -0
  9. package/agents/examples/env-composition.md +28 -1
  10. package/agents/examples/legal-pages.md +1 -1
  11. package/agents/examples/prod-boot-options.md +16 -0
  12. package/agents/examples/rate-limiting.md +48 -0
  13. package/agents/examples/record-detail-layout.md +692 -0
  14. package/agents/examples/seed-migration.md +212 -0
  15. package/agents/examples/wizard-form.md +941 -0
  16. package/agents/examples/writeform-section.md +548 -0
  17. package/agents/features.md +19 -2
  18. package/agents/widgets.md +40 -39
  19. package/dist/api/api-constants.js +2 -2
  20. package/dist/api/auth-middleware.js +7 -7
  21. package/dist/api/auth-rate-limiters.js +7 -3
  22. package/dist/api/auth-routes-mfa.js +1 -1
  23. package/dist/api/auth-routes-session.js +1 -1
  24. package/dist/api/auth-routes-shared.js +7 -3
  25. package/dist/api/auth-routes-signup.js +1 -1
  26. package/dist/api/client-error-route.js +8 -2
  27. package/dist/api/client-ip.js +3 -1
  28. package/dist/api/extra-route.js +1 -1
  29. package/dist/api/index.d.ts +3 -1
  30. package/dist/api/index.js +3 -1
  31. package/dist/api/pii-leak-guard.js +4 -2
  32. package/dist/api/readiness.js +5 -5
  33. package/dist/api/redis-sse-broker.js +8 -6
  34. package/dist/api/request-context.d.ts +1 -1
  35. package/dist/api/request-context.js +1 -1
  36. package/dist/api/routes.js +2 -2
  37. package/dist/api/server-boot-checks.d.ts +10 -0
  38. package/dist/api/server-boot-checks.js +157 -0
  39. package/dist/api/server-event-dispatcher.d.ts +26 -0
  40. package/dist/api/server-event-dispatcher.js +208 -0
  41. package/dist/api/server-extra-routes.d.ts +11 -0
  42. package/dist/api/server-extra-routes.js +203 -0
  43. package/dist/api/server-middleware.d.ts +20 -0
  44. package/dist/api/server-middleware.js +211 -0
  45. package/dist/api/server-routes.d.ts +19 -0
  46. package/dist/api/server-routes.js +293 -0
  47. package/dist/api/server-websocket-routes.d.ts +4 -0
  48. package/dist/api/server-websocket-routes.js +108 -0
  49. package/dist/api/server-wiring.d.ts +32 -0
  50. package/dist/api/server-wiring.js +236 -0
  51. package/dist/api/server.d.ts +10 -15
  52. package/dist/api/server.js +48 -1250
  53. package/dist/api/session-cookies.js +4 -4
  54. package/dist/api/sse-broker.js +1 -1
  55. package/dist/api/sse-route.d.ts +13 -13
  56. package/dist/api/sse-route.js +31 -27
  57. package/dist/auth/index.js +4 -4
  58. package/dist/auth/roles.d.ts +4 -4
  59. package/dist/auth/roles.js +24 -24
  60. package/dist/compliance/duration-spec.js +18 -20
  61. package/dist/compliance/index.js +2 -3
  62. package/dist/compliance/override-schema.d.ts +4 -4
  63. package/dist/compliance/override-schema.js +19 -22
  64. package/dist/compliance/profiles.d.ts +26 -29
  65. package/dist/compliance/profiles.js +62 -69
  66. package/dist/compliance/sub-processors.d.ts +28 -30
  67. package/dist/compliance/sub-processors.js +17 -21
  68. package/dist/consumer-cli.js +4 -4
  69. package/dist/crypto/blind-index.js +18 -17
  70. package/dist/crypto/ciphertext-pattern.js +1 -1
  71. package/dist/crypto/event-pii.js +3 -3
  72. package/dist/crypto/kek-source.d.ts +1 -1
  73. package/dist/crypto/kek-source.js +3 -2
  74. package/dist/crypto/kms-adapter.d.ts +1 -1
  75. package/dist/crypto/kms-adapter.js +4 -6
  76. package/dist/crypto/kms-wiring.d.ts +1 -2
  77. package/dist/crypto/kms-wiring.js +2 -2
  78. package/dist/crypto/owner-transition-rekey.d.ts +5 -1
  79. package/dist/crypto/owner-transition-rekey.js +1 -1
  80. package/dist/crypto/pg-kms-adapter.js +2 -6
  81. package/dist/crypto/pii-field-encryption.d.ts +5 -1
  82. package/dist/crypto/pii-field-encryption.js +7 -5
  83. package/dist/crypto/subject-resolver.d.ts +1 -1
  84. package/dist/crypto/subject-resolver.js +2 -2
  85. package/dist/db/aggregate-sql.d.ts +21 -0
  86. package/dist/db/aggregate-sql.js +155 -0
  87. package/dist/db/apply-entity-event.d.ts +6 -6
  88. package/dist/db/apply-entity-event.js +55 -55
  89. package/dist/db/blind-index-cleanup.js +7 -7
  90. package/dist/db/closed-connection.d.ts +9 -0
  91. package/dist/db/closed-connection.js +95 -0
  92. package/dist/db/collect-table-metas.js +10 -11
  93. package/dist/db/compound-types.d.ts +1 -1
  94. package/dist/db/compound-types.js +12 -12
  95. package/dist/db/cursor.js +3 -4
  96. package/dist/db/dialect.d.ts +2 -2
  97. package/dist/db/dialect.js +3 -3
  98. package/dist/db/distinct-on.d.ts +1 -1
  99. package/dist/db/driver-row-coercion.d.ts +2 -0
  100. package/dist/db/driver-row-coercion.js +186 -0
  101. package/dist/db/driver-value-preparation.d.ts +16 -0
  102. package/dist/db/driver-value-preparation.js +99 -0
  103. package/dist/db/eagerload.d.ts +3 -3
  104. package/dist/db/eagerload.js +21 -12
  105. package/dist/db/entity-field-encryption.d.ts +1 -0
  106. package/dist/db/entity-field-encryption.js +1 -1
  107. package/dist/db/entity-table-meta.d.ts +2 -2
  108. package/dist/db/entity-table-meta.js +105 -112
  109. package/dist/db/event-store-executor-context.d.ts +3 -2
  110. package/dist/db/event-store-executor-context.js +13 -13
  111. package/dist/db/event-store-executor-read-aggregate.d.ts +8 -0
  112. package/dist/db/event-store-executor-read-aggregate.js +112 -0
  113. package/dist/db/event-store-executor-read-filter.d.ts +31 -0
  114. package/dist/db/event-store-executor-read-filter.js +203 -0
  115. package/dist/db/event-store-executor-read-paging.d.ts +14 -0
  116. package/dist/db/event-store-executor-read-paging.js +99 -0
  117. package/dist/db/event-store-executor-read-rows.d.ts +6 -0
  118. package/dist/db/event-store-executor-read-rows.js +32 -0
  119. package/dist/db/event-store-executor-read-search.d.ts +28 -0
  120. package/dist/db/event-store-executor-read-search.js +221 -0
  121. package/dist/db/event-store-executor-read-sort.d.ts +41 -0
  122. package/dist/db/event-store-executor-read-sort.js +130 -0
  123. package/dist/db/event-store-executor-read-where.d.ts +24 -0
  124. package/dist/db/event-store-executor-read-where.js +81 -0
  125. package/dist/db/event-store-executor-read.d.ts +2 -9
  126. package/dist/db/event-store-executor-read.js +50 -704
  127. package/dist/db/event-store-executor-write-steps.d.ts +20 -0
  128. package/dist/db/event-store-executor-write-steps.js +100 -0
  129. package/dist/db/event-store-executor-write.js +401 -510
  130. package/dist/db/index.d.ts +6 -2
  131. package/dist/db/index.js +5 -1
  132. package/dist/db/list-aggregate-labels.d.ts +14 -0
  133. package/dist/db/list-aggregate-labels.js +26 -0
  134. package/dist/db/located-timestamp.d.ts +11 -11
  135. package/dist/db/located-timestamp.js +29 -30
  136. package/dist/db/migrate-generator.d.ts +1 -1
  137. package/dist/db/migrate-generator.js +97 -105
  138. package/dist/db/migrate-runner.js +29 -26
  139. package/dist/db/money.d.ts +6 -6
  140. package/dist/db/money.js +29 -27
  141. package/dist/db/queries/backfill-pii.js +5 -5
  142. package/dist/db/queries/ddl.js +1 -1
  143. package/dist/db/queries/es-ops.d.ts +1 -1
  144. package/dist/db/queries/es-ops.js +1 -1
  145. package/dist/db/queries/event-consumer.js +3 -3
  146. package/dist/db/queries/event-store.js +4 -2
  147. package/dist/db/queries/projection-rebuild.js +3 -3
  148. package/dist/db/queries/raw-sql.d.ts +2 -2
  149. package/dist/db/queries/raw-sql.js +2 -2
  150. package/dist/db/queries/shadow-swap.js +19 -19
  151. package/dist/db/query.d.ts +3 -16
  152. package/dist/db/query.js +8 -761
  153. package/dist/db/rebuild-marker.js +20 -21
  154. package/dist/db/reference-data.js +6 -1
  155. package/dist/db/replay-migration-sql.js +2 -2
  156. package/dist/db/schema-inspection.js +4 -5
  157. package/dist/db/table-builder.d.ts +1 -2
  158. package/dist/db/table-builder.js +137 -190
  159. package/dist/db/table-info.d.ts +10 -0
  160. package/dist/db/table-info.js +45 -0
  161. package/dist/db/temporal-value-guards.d.ts +6 -0
  162. package/dist/db/temporal-value-guards.js +15 -0
  163. package/dist/db/tenant-db-runner.d.ts +1 -0
  164. package/dist/db/tenant-db-runner.js +3 -0
  165. package/dist/db/tenant-db.d.ts +2 -2
  166. package/dist/db/tenant-db.js +48 -11
  167. package/dist/db/where-clause.d.ts +6 -0
  168. package/dist/db/where-clause.js +236 -0
  169. package/dist/derivatives/delete-stored-file.js +6 -2
  170. package/dist/derivatives/derivatives-context.js +1 -1
  171. package/dist/engine/boot-validator/access-roles.js +4 -3
  172. package/dist/engine/boot-validator/api-ext.js +14 -14
  173. package/dist/engine/boot-validator/boot-check.js +1 -1
  174. package/dist/engine/boot-validator/config-deps.js +7 -6
  175. package/dist/engine/boot-validator/detail-screens.js +4 -4
  176. package/dist/engine/boot-validator/entity-handler.d.ts +1 -0
  177. package/dist/engine/boot-validator/entity-handler.js +77 -61
  178. package/dist/engine/boot-validator/form-derivations.js +35 -1
  179. package/dist/engine/boot-validator/gdpr-storage.js +4 -4
  180. package/dist/engine/boot-validator/i18n-keys.js +6 -4
  181. package/dist/engine/boot-validator/index.d.ts +2 -2
  182. package/dist/engine/boot-validator/index.js +22 -20
  183. package/dist/engine/boot-validator/nav.js +5 -5
  184. package/dist/engine/boot-validator/ownership.js +12 -9
  185. package/dist/engine/boot-validator/parent-ref.js +1 -1
  186. package/dist/engine/boot-validator/pii-retention.js +258 -187
  187. package/dist/engine/boot-validator/projection-list-screens.js +7 -7
  188. package/dist/engine/boot-validator/query-refs.js +1 -1
  189. package/dist/engine/boot-validator/screens-actions.d.ts +1 -0
  190. package/dist/engine/boot-validator/screens-actions.js +23 -17
  191. package/dist/engine/boot-validator/screens-dashboard.js +2 -5
  192. package/dist/engine/boot-validator/screens-forms.js +12 -17
  193. package/dist/engine/boot-validator/screens-kind-config-edit.d.ts +3 -0
  194. package/dist/engine/boot-validator/screens-kind-config-edit.js +88 -0
  195. package/dist/engine/boot-validator/screens-kind-entity-edit.d.ts +3 -0
  196. package/dist/engine/boot-validator/screens-kind-entity-edit.js +55 -0
  197. package/dist/engine/boot-validator/screens-kind-entity-list.d.ts +3 -0
  198. package/dist/engine/boot-validator/screens-kind-entity-list.js +228 -0
  199. package/dist/engine/boot-validator/screens-kind-projection-detail.d.ts +3 -0
  200. package/dist/engine/boot-validator/screens-kind-projection-detail.js +235 -0
  201. package/dist/engine/boot-validator/screens-kind-projection-list.d.ts +3 -0
  202. package/dist/engine/boot-validator/screens-kind-projection-list.js +52 -0
  203. package/dist/engine/boot-validator/screens-kind-secret-mint.d.ts +3 -0
  204. package/dist/engine/boot-validator/screens-kind-secret-mint.js +28 -0
  205. package/dist/engine/boot-validator/screens-kind-shared.d.ts +37 -0
  206. package/dist/engine/boot-validator/screens-kind-shared.js +142 -0
  207. package/dist/engine/boot-validator/screens-lists.d.ts +2 -1
  208. package/dist/engine/boot-validator/screens-lists.js +26 -24
  209. package/dist/engine/boot-validator/screens.d.ts +0 -2
  210. package/dist/engine/boot-validator/screens.js +102 -869
  211. package/dist/engine/boot-validator/security-baseline.js +3 -2
  212. package/dist/engine/boot-validator/transfer-graph.js +2 -2
  213. package/dist/engine/boot-validator/workspaces.js +3 -3
  214. package/dist/engine/bridge-stub.js +3 -4
  215. package/dist/engine/build-app-schema.js +130 -170
  216. package/dist/engine/build-config-feature-schema.js +50 -50
  217. package/dist/engine/build-target.js +20 -23
  218. package/dist/engine/codemod/pipeline-codemod.js +20 -13
  219. package/dist/engine/config-helpers.js +4 -4
  220. package/dist/engine/constants.js +2 -2
  221. package/dist/engine/create-app.js +2 -2
  222. package/dist/engine/define-feature.js +21 -13
  223. package/dist/engine/define-handler.js +13 -11
  224. package/dist/engine/define-step.js +1 -1
  225. package/dist/engine/define-workflow.d.ts +5 -5
  226. package/dist/engine/define-workflow.js +6 -6
  227. package/dist/engine/entity-handlers.d.ts +13 -0
  228. package/dist/engine/entity-handlers.js +22 -34
  229. package/dist/engine/entity-list-runtime-options.d.ts +8 -0
  230. package/dist/engine/entity-list-runtime-options.js +18 -0
  231. package/dist/engine/event-def.js +2 -2
  232. package/dist/engine/extension-names.d.ts +16 -17
  233. package/dist/engine/extension-names.js +37 -38
  234. package/dist/engine/extensions/escape-hatch-usage.js +1 -1
  235. package/dist/engine/extensions/tenant-data.js +2 -2
  236. package/dist/engine/extensions/user-data.d.ts +23 -24
  237. package/dist/engine/factories.d.ts +14 -13
  238. package/dist/engine/factories.js +38 -37
  239. package/dist/engine/feature-ast/entity-field-types.js +1 -1
  240. package/dist/engine/feature-ast/extractors/handlers.js +2 -1
  241. package/dist/engine/feature-ast/extractors/hooks.js +1 -1
  242. package/dist/engine/feature-ast/extractors/round2.js +25 -6
  243. package/dist/engine/feature-ast/extractors/shared.d.ts +2 -3
  244. package/dist/engine/feature-ast/extractors/shared.js +2 -3
  245. package/dist/engine/feature-ast/parse.js +13 -13
  246. package/dist/engine/feature-ast/patch.js +4 -182
  247. package/dist/engine/feature-ast/pattern-change-schema.d.ts +3 -0
  248. package/dist/engine/feature-ast/pattern-change-schema.js +2 -1
  249. package/dist/engine/feature-ast/pattern-id-matchers.d.ts +7 -0
  250. package/dist/engine/feature-ast/pattern-id-matchers.js +210 -0
  251. package/dist/engine/feature-ast/patterns.d.ts +11 -2
  252. package/dist/engine/feature-ast/patterns.js +43 -51
  253. package/dist/engine/feature-ast/render.js +50 -89
  254. package/dist/engine/feature-config-events-jobs.js +15 -12
  255. package/dist/engine/feature-entity-handlers.js +12 -5
  256. package/dist/engine/feature-manifest.d.ts +9 -9
  257. package/dist/engine/feature-manifest.js +6 -7
  258. package/dist/engine/feature-ui-extensions.d.ts +3 -3
  259. package/dist/engine/feature-ui-extensions.js +30 -22
  260. package/dist/engine/field-access.js +5 -6
  261. package/dist/engine/form-derivations.js +18 -7
  262. package/dist/engine/handler-field-references.js +1 -1
  263. package/dist/engine/index.d.ts +1 -0
  264. package/dist/engine/index.js +4 -4
  265. package/dist/engine/object-form.d.ts +1 -0
  266. package/dist/engine/object-form.js +14 -4
  267. package/dist/engine/ownership.js +3 -3
  268. package/dist/engine/parse-ref-target.js +5 -7
  269. package/dist/engine/pattern-library/index.js +2 -2
  270. package/dist/engine/pattern-library/library.js +2 -2
  271. package/dist/engine/pattern-library/types.js +3 -3
  272. package/dist/engine/pipeline.js +2 -2
  273. package/dist/engine/project-app-schema-for-roles.d.ts +2 -0
  274. package/dist/engine/project-app-schema-for-roles.js +7 -5
  275. package/dist/engine/projection-helpers.js +9 -9
  276. package/dist/engine/qualified-name.js +2 -2
  277. package/dist/engine/registry-facade.js +1 -1
  278. package/dist/engine/registry-ingest.js +13 -13
  279. package/dist/engine/registry-state.js +17 -19
  280. package/dist/engine/registry-validate.js +12 -12
  281. package/dist/engine/run-in.js +2 -2
  282. package/dist/engine/run-pipeline.js +7 -0
  283. package/dist/engine/schema-builder.js +251 -233
  284. package/dist/engine/screen-filter-ops.js +17 -20
  285. package/dist/engine/screen-helpers.js +4 -3
  286. package/dist/engine/screen-kind.d.ts +7 -0
  287. package/dist/engine/screen-kind.js +1 -0
  288. package/dist/engine/state-machine.d.ts +12 -12
  289. package/dist/engine/state-machine.js +7 -7
  290. package/dist/engine/steps/_resolver-utils.js +4 -3
  291. package/dist/engine/steps/for-each.js +4 -4
  292. package/dist/engine/steps/unsafe-projection-delete.js +1 -1
  293. package/dist/engine/steps/unsafe-projection-upsert.js +4 -4
  294. package/dist/engine/steps/wait-for-event.js +4 -4
  295. package/dist/engine/steps/workflow-system-events.js +3 -3
  296. package/dist/engine/strip-disabled-features-from-app-schema.js +51 -14
  297. package/dist/engine/tier-resolver-extension.d.ts +29 -27
  298. package/dist/engine/tier-resolver-extension.js +26 -26
  299. package/dist/engine/transfer-adjacency.js +2 -2
  300. package/dist/engine/validate-projection-allowlist.js +9 -28
  301. package/dist/engine/walk-step-instances.d.ts +2 -0
  302. package/dist/engine/walk-step-instances.js +38 -0
  303. package/dist/engine/where-rule-lint.js +1 -1
  304. package/dist/engine/write-handler-qn-extract.js +1 -1
  305. package/dist/entrypoint/index.d.ts +4 -1
  306. package/dist/entrypoint/index.js +10 -4
  307. package/dist/env/index.d.ts +7 -6
  308. package/dist/env/index.js +10 -9
  309. package/dist/errors/docs-url.d.ts +1 -1
  310. package/dist/errors/docs-url.js +22 -2
  311. package/dist/errors/transition-details.js +7 -7
  312. package/dist/errors/write-error-info.d.ts +6 -6
  313. package/dist/errors/write-error-info.js +6 -6
  314. package/dist/es-ops/context.d.ts +9 -9
  315. package/dist/es-ops/context.js +29 -29
  316. package/dist/es-ops/index.js +7 -9
  317. package/dist/es-ops/operations-schema.js +4 -10
  318. package/dist/es-ops/runner.d.ts +11 -11
  319. package/dist/es-ops/runner.js +49 -53
  320. package/dist/es-ops/types.d.ts +55 -55
  321. package/dist/es-ops/types.js +11 -11
  322. package/dist/event-store/admin-api.js +7 -8
  323. package/dist/event-store/errors.js +1 -1
  324. package/dist/event-store/event-store.js +12 -6
  325. package/dist/event-store/rebuild-dead-letter.js +1 -1
  326. package/dist/files/bind-pending-file-refs.js +3 -3
  327. package/dist/files/create-file-ref-from-bytes.js +4 -1
  328. package/dist/files/feature.js +9 -10
  329. package/dist/files/file-handle.js +7 -9
  330. package/dist/files/file-ref-entity.js +15 -15
  331. package/dist/files/file-ref-table.js +7 -8
  332. package/dist/files/file-routes.d.ts +7 -0
  333. package/dist/files/file-routes.js +22 -13
  334. package/dist/files/in-memory-provider.js +8 -9
  335. package/dist/files/local-provider.js +18 -25
  336. package/dist/files/provider-resolver.d.ts +7 -7
  337. package/dist/files/resolve-content-type.js +43 -0
  338. package/dist/files/storage-tracking.js +2 -2
  339. package/dist/files/upload-ledger.js +7 -0
  340. package/dist/files/zip-stream.d.ts +12 -19
  341. package/dist/files/zip-stream.js +44 -63
  342. package/dist/i18n/required-surface-keys.d.ts +1 -1
  343. package/dist/i18n/required-surface-keys.js +188 -212
  344. package/dist/internal/stack-support.d.ts +2 -1
  345. package/dist/internal/stack-support.js +1 -1
  346. package/dist/jobs/job-runner-context.d.ts +32 -0
  347. package/dist/jobs/job-runner-context.js +305 -0
  348. package/dist/jobs/job-runner-execution.d.ts +7 -0
  349. package/dist/jobs/job-runner-execution.js +160 -0
  350. package/dist/jobs/job-runner-gates.d.ts +19 -0
  351. package/dist/jobs/job-runner-gates.js +198 -0
  352. package/dist/jobs/job-runner-helpers.d.ts +17 -3
  353. package/dist/jobs/job-runner-helpers.js +69 -4
  354. package/dist/jobs/job-runner-schedulers.d.ts +1 -1
  355. package/dist/jobs/job-runner-schedulers.js +3 -4
  356. package/dist/jobs/job-runner-scope.d.ts +44 -0
  357. package/dist/jobs/job-runner-scope.js +102 -0
  358. package/dist/jobs/job-runner-types.d.ts +12 -0
  359. package/dist/jobs/job-runner.d.ts +0 -1
  360. package/dist/jobs/job-runner.js +57 -669
  361. package/dist/lifecycle/lifecycle.js +3 -5
  362. package/dist/lifecycle/signal-handlers.js +5 -4
  363. package/dist/logging/utils.d.ts +2 -1
  364. package/dist/logging/utils.js +38 -10
  365. package/dist/migrations/index.js +1 -1
  366. package/dist/migrations/kumiko-drift.js +14 -13
  367. package/dist/migrations/pending-rebuilds.d.ts +21 -20
  368. package/dist/migrations/pending-rebuilds.js +27 -27
  369. package/dist/migrations/projection-table-index.d.ts +3 -3
  370. package/dist/migrations/projection-table-index.js +8 -8
  371. package/dist/observability/escape-hatch-report.d.ts +3 -0
  372. package/dist/observability/escape-hatch-report.js +12 -1
  373. package/dist/observability/metric-validator.js +1 -1
  374. package/dist/observability/metrics-handle.js +3 -3
  375. package/dist/pipeline/append-event-core.js +11 -2
  376. package/dist/pipeline/cascade-handler.d.ts +1 -1
  377. package/dist/pipeline/cascade-handler.js +165 -138
  378. package/dist/pipeline/dispatch-batch.js +2 -2
  379. package/dist/pipeline/dispatch-query.js +20 -13
  380. package/dist/pipeline/dispatch-shared.d.ts +14 -3
  381. package/dist/pipeline/dispatch-shared.js +67 -721
  382. package/dist/pipeline/dispatch-stream.js +1 -1
  383. package/dist/pipeline/dispatch-write.js +297 -190
  384. package/dist/pipeline/dispatcher-utils.d.ts +1 -1
  385. package/dist/pipeline/dispatcher-utils.js +1 -1
  386. package/dist/pipeline/event-consumer-state.js +2 -2
  387. package/dist/pipeline/event-dispatcher-admin.js +2 -1
  388. package/dist/pipeline/event-dispatcher-delivery.js +4 -6
  389. package/dist/pipeline/event-dispatcher.js +17 -28
  390. package/dist/pipeline/handler-context-auth.d.ts +9 -0
  391. package/dist/pipeline/handler-context-auth.js +54 -0
  392. package/dist/pipeline/handler-context-config.d.ts +14 -0
  393. package/dist/pipeline/handler-context-config.js +113 -0
  394. package/dist/pipeline/handler-context-db.d.ts +24 -0
  395. package/dist/pipeline/handler-context-db.js +149 -0
  396. package/dist/pipeline/handler-context-dispatch.d.ts +21 -0
  397. package/dist/pipeline/handler-context-dispatch.js +89 -0
  398. package/dist/pipeline/handler-context-events.d.ts +43 -0
  399. package/dist/pipeline/handler-context-events.js +237 -0
  400. package/dist/pipeline/handler-context-notify.d.ts +12 -0
  401. package/dist/pipeline/handler-context-notify.js +55 -0
  402. package/dist/pipeline/handler-context-observability.d.ts +7 -0
  403. package/dist/pipeline/handler-context-observability.js +21 -0
  404. package/dist/pipeline/handler-context-scope.d.ts +48 -0
  405. package/dist/pipeline/handler-context-scope.js +88 -0
  406. package/dist/pipeline/irreversible-operation-gate.js +1 -1
  407. package/dist/pipeline/lifecycle-pipeline.js +9 -9
  408. package/dist/pipeline/member-read-only-transaction.js +1 -3
  409. package/dist/pipeline/msp-rebuild.js +1 -1
  410. package/dist/pipeline/notify-scope.js +12 -1
  411. package/dist/pipeline/pre-handler-gates.js +20 -4
  412. package/dist/pipeline/pre-transaction-reservations.d.ts +1 -0
  413. package/dist/pipeline/pre-transaction-reservations.js +9 -3
  414. package/dist/pipeline/projection-rebuild.js +15 -13
  415. package/dist/pipeline/system-hooks.js +39 -41
  416. package/dist/pipeline/system-identity-switch.js +1 -3
  417. package/dist/pipeline/tenant-timezone-cache.js +1 -1
  418. package/dist/random/generate.d.ts +29 -29
  419. package/dist/random/generate.js +30 -30
  420. package/dist/random/words.js +20 -20
  421. package/dist/rate-limit/middleware.js +9 -5
  422. package/dist/redis/client.js +2 -2
  423. package/dist/redis/pubsub-signal.js +14 -17
  424. package/dist/schema-cli/apply-command.d.ts +2 -0
  425. package/dist/schema-cli/apply-command.js +97 -0
  426. package/dist/schema-cli/baseline-command.d.ts +2 -0
  427. package/dist/schema-cli/baseline-command.js +33 -0
  428. package/dist/schema-cli/generate-command.d.ts +2 -0
  429. package/dist/schema-cli/generate-command.js +90 -0
  430. package/dist/schema-cli/shared.d.ts +39 -0
  431. package/dist/schema-cli/shared.js +95 -0
  432. package/dist/schema-cli/status-command.d.ts +2 -0
  433. package/dist/schema-cli/status-command.js +73 -0
  434. package/dist/schema-cli/validate-boot-input.d.ts +5 -0
  435. package/dist/schema-cli/validate-boot-input.js +130 -0
  436. package/dist/schema-cli/validate-command.d.ts +2 -0
  437. package/dist/schema-cli/validate-command.js +130 -0
  438. package/dist/schema-cli.d.ts +2 -18
  439. package/dist/schema-cli.js +47 -510
  440. package/dist/search/index.js +4 -4
  441. package/dist/search/meilisearch-adapter.js +2 -1
  442. package/dist/search/purge-subject.js +4 -5
  443. package/dist/search/reindex-entity.js +6 -9
  444. package/dist/time/boot-tz-warning.d.ts +2 -2
  445. package/dist/time/boot-tz-warning.js +8 -8
  446. package/dist/time/iana.js +10 -10
  447. package/dist/time/index.js +9 -9
  448. package/dist/time/legacy-date.d.ts +2 -2
  449. package/dist/time/legacy-date.js +6 -8
  450. package/dist/time/polyfill.js +1 -1
  451. package/dist/time/tz-context.d.ts +1 -1
  452. package/dist/time/tz-context.js +1 -1
  453. package/dist/ui-types/app-schema.js +7 -7
  454. package/dist/ui-types/list-row-meta.js +4 -4
  455. package/dist/upgrade-cli.js +159 -130
  456. package/dist/utils/compare.js +1 -1
  457. package/package.json +5 -5
  458. package/src/changes.json +358 -0
  459. package/src/scripts/codemod/crypto-shredding-testing-move.ts +2 -2
  460. package/src/scripts/codemod/feature-layout.ts +10 -2
  461. package/src/scripts/codemod/migrate-cross-tenant.ts +1 -1
  462. package/src/scripts/codemod/migrate-open-to-all.ts +1 -1
  463. package/src/scripts/codemod/object-form.ts +41 -4
  464. package/src/scripts/codemod/package-merge.ts +58 -8
  465. package/src/scripts/codemod/pii-personal-migration.ts +192 -153
  466. package/src/scripts/codemod/testing-injection.ts +122 -42
  467. package/src/scripts/codemod/testing-move.ts +29 -7
  468. package/src/scripts/codemod/unprocessable-error-details-reason.ts +2 -2
@@ -1,1262 +1,60 @@
1
1
  import { Hono } from "hono";
2
- import { ROLES } from "../auth/roles.js";
3
- import { createProjectingTenantDb, withExecutorManagedWrites } from "../db/tenant-db.js";
4
- import { createDerivativesContext } from "../derivatives/derivatives-context.js";
5
- import { buildAppSchema } from "../engine/build-app-schema.js";
6
- import { EXT_FILE_PROVIDER, EXT_PRINCIPAL_STATUS } from "../engine/extension-names.js";
7
- import { projectAppSchemaForRoles } from "../engine/project-app-schema-for-roles.js";
8
- import { runsInLane } from "../engine/run-in.js";
9
- import { resolveDisabledFeatureNames, stripDisabledFeaturesFromAppSchema, } from "../engine/strip-disabled-features-from-app-schema.js";
10
- import { createAnonymousUser, createSystemUser, isAnonymousSessionUser, } from "../engine/system-user.js";
11
- import { isFileField, } from "../engine/types/index.js";
12
- import { assertSeedModeNotInProduction } from "../event-store/seed-clock.js";
13
- import { createTenantFileContext } from "../files/file-handle.js";
14
- import { createFileRoutes, readFilesRouteOptions } from "../files/file-routes.js";
15
- import { makeFileProviderResolver } from "../files/provider-resolver.js";
16
- import { createRecordReadCheck } from "../files/record-read-check.js";
17
- import { createRecordWriteCheck } from "../files/record-write-check.js";
18
- import { createFallbackLogger } from "../logging/index.js";
19
- import { createNoopProvider, registerStandardMetrics, wrapRedisClient, } from "../observability/index.js";
20
- import { resolveTenantLifecyclePlugin } from "../pipeline/active-membership.js";
21
- import { configAccessorFactoryOf } from "../pipeline/config-accessor-factory.js";
22
- import { createDispatcher } from "../pipeline/dispatcher.js";
23
- import { SHARED_INSTANCE_SENTINEL } from "../pipeline/event-consumer-state.js";
24
- import { createEventDispatcher } from "../pipeline/event-dispatcher.js";
25
- import { createLifecycleHooks } from "../pipeline/lifecycle-pipeline.js";
26
- import { createMultiStreamApplyContext } from "../pipeline/multi-stream-apply-context.js";
27
- import { createAccessInvalidationEventConsumer, createJobTriggerEventConsumer, createSearchEventConsumer, createSseBroadcastEventConsumer, } from "../pipeline/system-hooks.js";
28
- import { authEndpointRateLimit, createPayloadDigest, createRateLimitResolver, globalIpRateLimit, httpRouteRateLimit, } from "../rate-limit/index.js";
29
- import { resolveCacheSyncBus } from "../redis/cache-sync-bus.js";
30
- import { deriveSearchAdapterConfig } from "../search/derive-search-adapter-config.js";
31
- import { assertUnreachable, generateId } from "../utils/index.js";
32
- import { collectAnonymousLiveEntities } from "./anonymous-live-entities.js";
33
- import { NO_ROUTE_MATCH_HEADER_NAME, NON_PUBLIC_API_PATHS, PUBLIC_API_PATHS, Routes, } from "./api-constants.js";
34
- import { authMiddleware, getAuthTokenExpiry, getUser, identifyOptionalSession, } from "./auth-middleware.js";
35
- import { assertSessionCallbacksPaired, createAuthRoutes, } from "./auth-routes.js";
36
- import { createClientErrorRoute } from "./client-error-route.js";
37
- import { assertValidTrustedProxyHops, clientIpSourceFromHonoContext, createClientIpResolver, } from "./client-ip.js";
38
- import { csrfMiddleware } from "./csrf-middleware.js";
39
- import { collectEntityReadAccess } from "./entity-read-access.js";
40
- import { ExtraRouteEntries, ExtraRouteRejection, } from "./extra-route.js";
41
- import { computeStrongEtag, etagMatches } from "./http-cache.js";
42
- import { createJwtHelper } from "./jwt.js";
43
- import { observabilityMiddleware } from "./observability-middleware.js";
44
- import { assertOriginGuardConfig, isWebSocketOriginAllowed, normalizeOrigin, rejectOrigin, resolveOriginGuard, } from "./origin-middleware.js";
45
- import { patRouteGuard } from "./pat-route-guard.js";
46
- import { piiCiphertextResponseGuard } from "./pii-leak-guard.js";
47
- import { createDefaultSseBroker } from "./redis-sse-broker.js";
48
- import { requestContext } from "./request-context.js";
49
- import { buildRequestContextData, requestIdMiddleware } from "./request-id-middleware.js";
50
- import { bodyLimitForRoutePath, DEFAULT_MAX_REQUEST_BYTES, registerBodyLimit, registerHealthRoutes, registerMetricsRoute, registerVersionRoute, } from "./route-registrars.js";
51
- import { createApiRoutes, handleUncaughtRouteError } from "./routes.js";
52
- import { resolveSessionCookies, sessionCookiesMiddleware } from "./session-cookies.js";
53
- import { createSseRoute } from "./sse-route.js";
54
- import { buildWebSocketSessionRevalidator, createWebSocketConnectionLimiter, hasWebSocketUpgradeServer, isWebSocketUpgradeRequest, WEBSOCKET_DEFAULT_MAX_CONNECTIONS_PER_USER, WEBSOCKET_DEFAULT_MAX_MESSAGE_BYTES, } from "./websocket-route.js";
55
- // The per-tenant file-provider resolver, built once for a registry+context so
56
- // a job-runner and the server it runs beside share one instance (and one
57
- // per-tenant provider cache). Mirrors buildServer's own resolution exactly —
58
- // including NOT inventing a resolver when no `file-provider-*` plugin is
59
- // mounted, which is what keeps buildServer's boot-guard below able to fire.
60
- export function withFileProviderResolver(registry, context, cacheSync) {
61
- if (context._fileProviderResolver !== undefined)
62
- return context;
63
- if (registry.getExtensionUsages(EXT_FILE_PROVIDER).length === 0)
64
- return context;
65
- return {
66
- ...context,
67
- _fileProviderResolver: makeFileProviderResolver({
68
- registry,
69
- _configAccessorFactory: configAccessorFactoryOf(context),
70
- secrets: context.secrets,
71
- db: context.db,
72
- ...(cacheSync ? { cacheSync } : {}),
73
- }),
74
- };
75
- }
76
- // A payload-bucket handler without a resolver would answer every call with a
77
- // 500 at request time; fail at boot instead.
78
- function assertNoPayloadRateLimitsWithoutResolver(registry) {
79
- const offenders = [];
80
- for (const feature of registry.features.values()) {
81
- for (const [name, handler] of Object.entries(feature.writeHandlers)) {
82
- if (handler.additionalRateLimits !== undefined) {
83
- offenders.push(`${feature.name}:write:${name}`);
84
- }
85
- }
86
- }
87
- // skip: every handler's payload buckets are covered by the resolver
88
- if (offenders.length === 0)
89
- return;
90
- throw new Error(`Handlers declare additionalRateLimits but no RateLimitResolver is configured: ${offenders.join(", ")}. ` +
91
- "Wire a Redis client on context.redis (or pass context.rateLimit), or drop the payload buckets " +
92
- "(for the waitlist: emailRateLimits: []).");
93
- }
2
+ import { DEFAULT_MAX_REQUEST_BYTES, registerBodyLimit, registerVersionRoute, } from "./route-registrars.js";
3
+ import { handleUncaughtRouteError } from "./routes.js";
4
+ import { compilePublicApiRequestMatcher, mountExtraRoutes } from "./server-extra-routes.js";
5
+ import { installAuthGuardChain, installObservability, installPiiLeakGuard, installRateLimitMiddleware, installRequestId, installSessionCookies, } from "./server-middleware.js";
6
+ import { installNoRouteMatchMarker, mountAuthRoutes, mountClientErrorRoute, mountDispatcherRoutes, mountFeatureHttpRoutes, mountFileRoutes, mountOperationalRoutes, mountSchemaRoute, } from "./server-routes.js";
7
+ import { mountWebSocketRoutes } from "./server-websocket-routes.js";
8
+ import { resolveServerWiring } from "./server-wiring.js";
94
9
  export function buildServer(options) {
95
- assertSeedModeNotInProduction();
96
- // Single effective hop-count for every IP-derived rate-limit + requestMeta
97
- // below — the top-level option wins over the deprecated
98
- // `auth.trustedProxyHops` fallback.
99
- const trustedProxyHops = options.trustedProxyHops ?? options.auth?.trustedProxyHops ?? 0;
100
- assertValidTrustedProxyHops(trustedProxyHops, "buildServer");
101
- // Exactly ONE resolver for the whole server — the warn-once flag must fire
102
- // once per boot, not once per consumer (requestIdMiddleware, L1, L2,
103
- // auth-routes each sharing this same instance rather than building a
104
- // private one).
105
- const clientIpResolver = createClientIpResolver(trustedProxyHops, "buildServer");
106
- // File-storage is resolved per-tenant through file-foundation: a mounted
107
- // `file-provider-*` plugin (inmemory/s3/s3-env) is the single source for
108
- // uploads, ctx.files and the GDPR jobs.
109
- const hasFileProvider = options.registry.getExtensionUsages(EXT_FILE_PROVIDER).length > 0;
110
- // A test/advanced caller may inject the resolver directly on the context
111
- // (e.g. a static in-memory provider) instead of mounting a provider plugin.
112
- const hasInjectedResolver = options.context._fileProviderResolver !== undefined;
113
- // Hard-fail when the registry declares file/image fields but no provider
114
- // plugin is mounted — uploads would otherwise fail at the first request
115
- // instead of at boot. Proves a plugin is mounted, not that each tenant
116
- // selected one; per-tenant misconfig surfaces via createFileProviderForTenant.
117
- if (registryDeclaresFileFields(options.registry) && !hasFileProvider && !hasInjectedResolver) {
118
- throw new Error("Features declare file/image fields but no file-storage provider is mounted — " +
119
- "mount `file-foundation` + a `file-provider-*` feature (inmemory/s3/s3-env) and " +
120
- "select one per tenant via the 'file-foundation:config:provider' config-key.");
121
- }
122
- // #2051 — a screen whose search box renders (kumiko-screen.tsx gates it on
123
- // `screen.searchable ?? entity-has-searchable-field`, the same condition
124
- // used below) sends `payload.search` on every query. Without a
125
- // context.searchAdapter that throws UnprocessableError at request time
126
- // (#2032) — surface the misconfig at boot instead of on the first search.
127
- // Warn, not throw: unlike missing file-storage (uploads always fail),
128
- // list screens still work without search: only the search box is broken.
129
- // Several deployed apps (offlot-app, publicstatus, kumiko-studio,
130
- // kumiko-enterprise) currently run in exactly this state.
131
- if (!options.context.searchAdapter) {
132
- const unwiredEntities = entitiesWithSearchableScreen(options.registry);
133
- if (unwiredEntities.length > 0) {
134
- console.warn(`[kumiko:boot] ${unwiredEntities.length} entit${unwiredEntities.length === 1 ? "y" : "ies"} ` +
135
- `have a searchable list screen but no SearchAdapter is wired on context.searchAdapter: ` +
136
- `${unwiredEntities.join(", ")}. Search requests against ${unwiredEntities.length === 1 ? "it" : "them"} will fail with a 422 (search_adapter_not_wired) at runtime. ` +
137
- "Wire a SearchAdapter (e.g. createMeilisearchAdapter) on context.searchAdapter, or remove `searchable: true` from the affected fields.");
138
- }
139
- }
140
- // Stateless JWTs (no sessionChecker → no revocation) default to a shorter
141
- // TTL than session-backed ones, since a leaked stateless token can't be
142
- // revoked and stays valid until it expires. Explicit jwtTtl always wins.
143
- const defaultJwtTtl = options.auth?.sessionChecker ? 8 * 60 * 60 : 60 * 60;
144
- const jwt = createJwtHelper(options.jwtSecret, options.jwtIssuer, options.jwtTtl ?? defaultJwtTtl);
145
- // An explicit ServerOptions.sseBroker always wins (caller owns its
146
- // lifecycle) — createDefaultSseBroker is the single decision point every
147
- // other caller must funnel through instead of picking a broker on its
148
- // own, so the REDIS_URL-gated cross-replica default (fw#2625) can't be
149
- // silently bypassed the way runProdApp bypassed it before this existed.
150
- let sseBroker;
151
- let ownedRedisSseBroker;
152
- if (options.sseBroker) {
153
- sseBroker = options.sseBroker;
154
- }
155
- else {
156
- const defaults = createDefaultSseBroker();
157
- sseBroker = defaults.sseBroker;
158
- ownedRedisSseBroker = defaults.ownedRedisSseBroker;
159
- if (!ownedRedisSseBroker) {
160
- console.warn("[kumiko:boot] REDIS_URL is not set: cross-replica fanout disabled. SSE, access-invalidation and toggle-sync reach only the cursor-owning process, so with more than one replica clients on the other replicas miss events and revoked sessions stay open there.");
161
- }
162
- }
163
- // Same decision as the SSE broker: an explicit dispatcherOptions value
164
- // (incl. null = opt out) wins, otherwise REDIS_URL turns on cross-replica
165
- // cache invalidation (no REDIS_URL = process-local bus).
166
- const { bus: cacheSync, owned: ownedCacheSync } = resolveCacheSyncBus(options.dispatcherOptions?.cacheSync);
167
- // Resolve the per-process instance identifier. Prefer explicit
168
- // ServerOptions.instanceId (tests, deliberate wiring), fall back to the
169
- // deploy-env variable, finally a boot-time UUID. Validator rejects the
170
- // sentinel — a deliberate collision attempt would silently merge this
171
- // instance's per-instance cursors with the shared-row cursors and
172
- // deliver events twice to one shard while starving the other.
173
- const resolvedInstanceId = options.instanceId ?? process.env["KUMIKO_INSTANCE_ID"] ?? generateId();
174
- if (resolvedInstanceId === SHARED_INSTANCE_SENTINEL) {
175
- throw new Error(`ServerOptions.instanceId / KUMIKO_INSTANCE_ID cannot equal the reserved sentinel "${SHARED_INSTANCE_SENTINEL}" — ` +
176
- `pick any other stable string.`);
177
- }
178
- // Warn when we fell back to a random UUID. The built-in SSE consumer is
179
- // delivery="shared" (one cursor for all pods, fw#2625), so it no longer
180
- // writes a row per instance. The id still labels this process in the
181
- // app.started event and in per-instance consumers (opt-in delivery), where a
182
- // fresh id per boot leaves an orphaned cursor-row that pins pruneEvents
183
- // (retention-guard uses MIN(lastProcessedEventId) across all shards). Silent
184
- // when options.instanceId or KUMIKO_INSTANCE_ID is explicit — those are
185
- // deliberate choices (the test suite sets KUMIKO_INSTANCE_ID="test-instance").
186
- const instanceIdWasRandom = options.instanceId === undefined && !process.env["KUMIKO_INSTANCE_ID"];
187
- if (instanceIdWasRandom) {
188
- console.warn(`[kumiko:boot] No ServerOptions.instanceId / KUMIKO_INSTANCE_ID set — generated a random UUID (${resolvedInstanceId}). ` +
189
- `SSE no longer needs a per-instance cursor, but the id labels this process in the app.started event and in per-instance consumers; without a stable id each restart leaves an orphaned cursor-row behind for those and pins events-retention on its last cursor. ` +
190
- `Set KUMIKO_INSTANCE_ID to the pod name (e.g. from the Kubernetes downward API metadata.name) in production.`);
191
- }
192
- // Observability — Noop by default so no call-site needs to null-check.
193
- // Every handler/middleware that reaches for ctx.tracer / ctx.metrics gets
194
- // a working, zero-cost fallback when no provider is configured.
195
- const observability = options.observability ?? createNoopProvider();
196
- // Register framework + feature metrics once on this meter. Standard
197
- // metrics (HTTP, dispatcher, DB) are used by Auto-Instrumentation; feature
198
- // metrics come from r.metric(...) declarations collected in the registry.
199
- registerStandardMetrics(observability.meter);
200
- for (const [name, def] of options.registry.getAllMetrics()) {
201
- if (observability.meter.definitions().has(name))
202
- continue;
203
- observability.meter.registerMetric({
204
- name,
205
- type: def.type,
206
- description: def.description,
207
- labels: def.labels,
208
- buckets: def.buckets,
209
- unit: def.unit,
210
- tenantLabel: def.tenantLabel,
211
- });
212
- }
213
- // When a non-default provider is configured, wrap the injected Redis clients
214
- // so `redis.cmd` spans attach to every command. For the default NoopProvider
215
- // we skip the proxy to keep zero runtime overhead when observability is off.
216
- const shouldWrapRedis = options.observability !== undefined;
217
- const redisCtx = options.context.redis;
218
- const wrappedRedis = shouldWrapRedis && redisCtx ? wrapRedisClient(redisCtx, observability.tracer) : redisCtx;
219
- // Inject tracer + meter into the AppContext so the dispatcher can propagate
220
- // them into every HandlerContext it builds. Build the per-tenant file-provider
221
- // resolver once (when a provider plugin is mounted) — the dispatcher uses it
222
- // to materialise `ctx.files`, the upload routes + MSP-applies share it. The
223
- // resolver reads config + the s3.secretAccessKey secret under SYSTEM identity.
224
- const contextWithFiles = withFileProviderResolver(options.registry, options.context, cacheSync);
225
- const fileProviderResolver = contextWithFiles._fileProviderResolver;
226
- // Auto-wire the rate-limit resolver, but ONLY when at least one
227
- // handler actually declared a rateLimit option. Apps that don't use
228
- // L3 pay zero cost: no resolver instance, no Lua-script registration
229
- // on Redis, no AppContext field. Apps that wire L1/L2 middleware can
230
- // pass `context.rateLimit` explicitly — that takes precedence over
231
- // the auto-wire (e.g. middleware-only setup without any L3 handler).
232
- // Auto-build the resolver when L3 handlers declared rateLimit OR when
233
- // the caller asked for L1/L2 middleware. Either path needs a resolver;
234
- // both share the same instance to avoid duplicate Lua-script registration.
235
- const wantsL3 = options.registry.hasRateLimitedHandler();
236
- const wantsL1L2 = options.rateLimit?.global !== undefined || options.rateLimit?.auth !== undefined;
237
- const wantsHttpRouteLimit = [...options.registry.features.values()].some((feature) => Object.values(feature.httpRoutes).some((route) => route.rateLimit !== undefined));
238
- const wantsResolver = wantsL3 || wantsL1L2 || wantsHttpRouteLimit;
239
- // Master for the payload-bucket HMAC: the current signing secret (the
240
- // keyring's signKid for rotation setups). buildServer always has one, so
241
- // the digest is available whenever a handler declares additionalRateLimits.
242
- const payloadDigest = createPayloadDigest(payloadDigestMasterSecret(options.jwtSecret));
243
- const rateLimitResolver = options.context.rateLimit ??
244
- (wrappedRedis && wantsResolver ? createRateLimitResolver({ redis: wrappedRedis }) : undefined);
245
- if (!rateLimitResolver) {
246
- assertNoPayloadRateLimitsWithoutResolver(options.registry);
247
- // The systemScope default limit only exists once a resolver does, and an app that
248
- // declared no explicit rateLimit anywhere never gets one auto-wired (wantsL3 stays
249
- // false) — so its cross-tenant handlers are silently unlimited.
250
- const unlimitedSystemScopeFeatures = [...options.registry.features.values()]
251
- .filter((feature) => feature.systemScope &&
252
- Object.keys(feature.writeHandlers).length + Object.keys(feature.queryHandlers).length > 0)
253
- .map((feature) => feature.name);
254
- if (unlimitedSystemScopeFeatures.length > 0) {
255
- console.warn(`[kumiko:boot] r.systemScope() features have handlers but no RateLimitResolver is configured, ` +
256
- `so their default rate limit is not enforced: ${unlimitedSystemScopeFeatures.join(", ")}. ` +
257
- "Wire a Redis client on context.redis and declare rateLimit on at least one handler (or pass " +
258
- "context.rateLimit) to enable the resolver.");
259
- }
260
- }
261
- const contextWithObservability = {
262
- ...contextWithFiles,
263
- ...(wrappedRedis ? { redis: wrappedRedis } : {}),
264
- ...(rateLimitResolver ? { rateLimit: rateLimitResolver } : {}),
265
- _rateLimitPayloadDigest: payloadDigest,
266
- ...(cacheSync ? { cacheSync } : {}),
267
- // Propagate the feature-toggle resolver to the context so the event-
268
- // dispatcher (and any future context-reading consumer) sees the same
269
- // source as the command dispatcher's handler-gate. Options take
270
- // precedence over whatever was already on context — the
271
- // dispatcher-options arg is the authoritative wire-up point.
272
- ...(options.dispatcherOptions?.effectiveFeatures
273
- ? { effectiveFeatures: options.dispatcherOptions.effectiveFeatures }
274
- : {}),
275
- tracer: observability.tracer,
276
- meter: observability.meter,
277
- };
278
- const lifecycle = createLifecycleHooks(options.registry, options.systemHooks, options.eventDedup ? { eventDedup: options.eventDedup } : undefined);
279
- const dispatcher = createDispatcher(options.registry, contextWithObservability, {
280
- ...options.dispatcherOptions,
281
- lifecycle,
282
- sseBroker,
283
- cacheSync: cacheSync ?? null,
284
- ...(options.auth ? { membershipQuery: options.auth.membershipQuery } : {}),
285
- });
286
- // Async event-dispatcher — the replacement for the old transactional
287
- // outbox. Consumer sources:
288
- // 1. System: SSE broadcast (iff sseBroker), Search index (iff
289
- // context.searchAdapter).
290
- // 2. Features: every r.multiStreamProjection registered in the registry
291
- // becomes its own consumer row with an independent cursor. The MSP
292
- // apply map is routed by event.type; apply receives the raw DbRunner
293
- // of a TX-scoped, tenant-bound DB handle so per-tenant writes stay
294
- // isolated.
295
- //
296
- // The dispatcher is built but NOT started here. Production boot code
297
- // must call `.start()`; test code typically calls `.runOnce()`.
298
- // @cast-boundary engine-bridge — context.db union narrows to DbConnection here
299
- const baseDb = contextWithObservability.db;
300
- // @cast-boundary engine-bridge — searchAdapter is an optional context-extension
301
- const searchAdapter = contextWithObservability
302
- .searchAdapter;
303
- // Adapter is built before the registry exists (app boot order) — hand it
304
- // the registry-derived default config here so it can lazily configure
305
- // each tenant index on first access instead of requiring per-tenant app
306
- // wiring.
307
- const derivedSearchConfig = searchAdapter
308
- ? deriveSearchAdapterConfig(options.registry)
309
- : undefined;
310
- if (searchAdapter && derivedSearchConfig) {
311
- searchAdapter.setDefaultConfig?.(derivedSearchConfig);
312
- }
313
- const sseConsumerEnabled = options.eventDispatcher?.systemConsumers?.sse ?? true;
314
- const searchConsumerEnabled = options.eventDispatcher?.systemConsumers?.search ?? true;
315
- const jobTriggerConsumerEnabled = options.eventDispatcher?.systemConsumers?.jobTrigger ?? true;
316
- const jobRunnerForTriggers = options.dispatcherOptions?.jobRunner;
317
- const mspJobs = jobRunnerForTriggers?.dispatch
318
- ? {
319
- dispatch: async (jobName, payload, dispatchOptions) => {
320
- await jobRunnerForTriggers.dispatch?.(jobName, payload, dispatchOptions);
321
- },
322
- }
323
- : undefined;
324
- const systemConsumers = [];
325
- if (sseConsumerEnabled) {
326
- systemConsumers.push(createSseBroadcastEventConsumer(sseBroker));
327
- }
328
- if (searchConsumerEnabled && searchAdapter) {
329
- systemConsumers.push(createSearchEventConsumer(searchAdapter, options.registry));
330
- }
331
- if (jobTriggerConsumerEnabled && jobRunnerForTriggers) {
332
- systemConsumers.push(createJobTriggerEventConsumer(jobRunnerForTriggers, options.registry));
333
- }
334
- // Default ON (#1524 global-by-default). Tests that opt out of SSE via
335
- // systemConsumers.accessInvalidation=false (test-stack mirrors sse off)
336
- // skip the row so retention prune suites are not blocked by a lagging
337
- // cursor=0 consumer they never drain.
338
- const accessInvalidationEnabled = options.eventDispatcher?.systemConsumers?.accessInvalidation ?? true;
339
- if (accessInvalidationEnabled) {
340
- systemConsumers.push(createAccessInvalidationEventConsumer(sseBroker));
341
- }
342
- // MultiStreamProjections: one EventConsumer per MSP. Handler routes by
343
- // event.type into the MSP's apply map. MSPs aggregate cross-aggregate but
344
- // still within one tenant by default — the applier receives the plain
345
- // baseDb DbRunner; tenant consistency comes from the triggering event's
346
- // own tenantId, not a per-event TenantDb scope.
347
- //
348
- // Lane-filter (Welle 2.6.b): MSPs declare `runIn` to pin them to a
349
- // deploy-lane. An MSP with `runIn: "api"` won't be wired into the
350
- // worker-process dispatcher (and vice versa). `runIn: "both"` (or the
351
- // legacy undefined default of "worker") runs wherever a dispatcher is
352
- // started — SKIP LOCKED on the consumer-cursor handles the race between
353
- // processes that both want the same event.
354
- const processLane = options.processLane ?? "worker";
355
- const mspDefs = [...options.registry.getAllMultiStreamProjections().values()].filter((msp) => runsInLane(msp.runIn, processLane));
356
- const mspConsumers = mspDefs.map((msp) => ({
357
- name: msp.name,
358
- // Feature-toggle gating: carry the owning feature so the event-dispatcher
359
- // can pause this consumer when the feature is globally disabled. Events
360
- // queue up in the store and replay cleanly from the same cursor on resume.
361
- ...(options.registry.getMultiStreamProjectionFeature(msp.name) && {
362
- featureName: options.registry.getMultiStreamProjectionFeature(msp.name), // @cast-boundary engine-bridge
363
- }),
364
- // Copy the continuous-lifecycle error policy straight onto the consumer.
365
- // Rebuild uses its own policy (rebuildProjection reads msp.errorMode.rebuild
366
- // directly); steady-state delivery runs through this consumer.
367
- ...(msp.errorMode?.continuous && { errorPolicy: msp.errorMode.continuous }),
368
- // Carry the MSP's declared delivery semantic through to the consumer.
369
- // Default (shared) is applied inside event-dispatcher, so omitting when
370
- // the MSP didn't declare one keeps the existing behaviour.
371
- ...(msp.delivery && { delivery: msp.delivery }),
372
- // Carry the MSP's declared cursor-seed through to the consumer. Default
373
- // (beginning) is applied inside insertConsumerIfAbsent.
374
- ...(msp.startFrom && { startFrom: msp.startFrom }),
375
- handler: async (event, ctx) => {
376
- const applyFn = msp.apply[event.type];
377
- // skip: this MSP doesn't care about this event type — fast path,
378
- // every event type passes through every MSP consumer exactly once.
379
- if (!applyFn)
380
- return;
381
- if (!baseDb) {
382
- // skip: no baseDb wired — allConsumers.length > 0 + baseDb check
383
- // above gates dispatcher creation, so we won't reach here in
384
- // production. Defensive return for the type-narrowing path.
385
- return;
386
- }
387
- // Saga/process-manager ctx: apply can call ctx.appendEvent to cascade
388
- // a follow-up event onto another aggregate. Uses the triggering event's
389
- // tenantId + userId so the causal chain stays tenant-consistent.
390
- // MSP qualified names are "<feature>:projection:<short>" — the
391
- // prefix before the first ":" owns the MSP. Used to reject
392
- // cross-feature ctx.appendEvent calls at emit-site.
393
- const mspOwner = msp.name.split(":")[0];
394
- const mspFiles = fileProviderResolver
395
- ? createTenantFileContext(fileProviderResolver, event.tenantId)
396
- : undefined;
397
- const mspDb = withExecutorManagedWrites(baseDb);
398
- const applyCtx = createMultiStreamApplyContext({
399
- registry: options.registry,
400
- db: mspDb,
401
- tenantId: event.tenantId,
402
- userId: event.metadata.userId,
403
- ...(mspOwner && { callerFeature: mspOwner }),
404
- ...(mspFiles && { files: mspFiles }),
405
- ...(contextWithObservability.secrets && { secrets: contextWithObservability.secrets }),
406
- ...(mspJobs && { jobs: mspJobs }),
407
- ...(mspFiles && {
408
- derivatives: createDerivativesContext({
409
- files: mspFiles,
410
- registry: options.registry,
411
- db: baseDb,
412
- tenantId: event.tenantId,
413
- }),
414
- }),
415
- });
416
- await applyFn(event, mspDb, applyCtx);
417
- // Keep ctx reachable to satisfy the EventConsumerHandler signature.
418
- void ctx;
419
- },
420
- }));
421
- const allConsumers = [...systemConsumers, ...mspConsumers];
422
- const { disabled: dispatcherDisabled, systemConsumers: _systemConsumersOpt, ...dispatcherTunables } = options.eventDispatcher ?? {};
423
- let eventDispatcher;
424
- if (allConsumers.length > 0 && baseDb && !dispatcherDisabled) {
425
- eventDispatcher = createEventDispatcher({
426
- db: baseDb,
427
- consumers: allConsumers,
428
- context: contextWithObservability,
429
- tracer: observability.tracer,
430
- meter: observability.meter,
431
- instanceId: resolvedInstanceId,
432
- ...dispatcherTunables,
433
- });
434
- }
435
- // Wire the event-dispatcher shutdown into the lifecycle so the caller
436
- // doesn't have to know the dispatcher exists. Hooks drain LIFO, so this
437
- // runs before anything registered later by the caller (e.g. DB pool close).
438
- if (options.lifecycle && eventDispatcher) {
439
- const dispatcher = eventDispatcher;
440
- options.lifecycle.registerShutdownHook("eventDispatcher", async () => {
441
- await dispatcher.stop();
442
- });
443
- }
444
- // Same reasoning, scoped to the broker this function created itself — an
445
- // app-injected sseBroker (options.sseBroker) owns its own teardown.
446
- if (options.lifecycle && ownedRedisSseBroker) {
447
- const broker = ownedRedisSseBroker;
448
- options.lifecycle.registerShutdownHook("redisSseBroker", async () => {
449
- await broker.close();
450
- });
451
- }
452
- if (options.lifecycle && ownedCacheSync) {
453
- const bus = ownedCacheSync;
454
- options.lifecycle.registerShutdownHook("cacheSync", async () => {
455
- await bus.close();
456
- });
457
- }
10
+ const wiring = resolveServerWiring(options);
458
11
  const app = new Hono();
459
12
  // Sub-apps mounted via app.route() without their own handler inherit this one.
460
13
  app.onError(handleUncaughtRouteError);
461
- // Resolved once; auth routes, auth/csrf middleware and the tenant-cookie
462
- // helpers read the cookie names from the request context.
463
- const sessionCookies = resolveSessionCookies({
464
- secureCookies: options.auth?.secureCookies,
465
- cookieDomain: options.auth?.cookieDomain,
466
- retiredCookieDomains: options.auth?.retiredCookieDomains,
467
- });
468
- app.use("*", sessionCookiesMiddleware(sessionCookies));
469
- // Only entry:"signature" bypasses jwtGuard (verify() authenticates
470
- // itself); entry:"anonymous" still needs the anonymousAccess fallthrough
471
- // (tenant-by-host), entry:"user" needs c.get("user") populated.
472
- const extraRoutePublicMatchers = compileExtraRoutePublicMatchers(options.extraRoutes);
473
- const isExtraRoutePublicPath = (c) => extraRoutePublicMatchers.some((m) => m.method === c.req.method && m.pattern.test(c.req.path));
474
- registerHealthRoutes(app, {
475
- lifecycle: options.lifecycle,
476
- readiness: {
477
- db: baseDb,
478
- redis: options.context.redis,
479
- consumers: allConsumers,
480
- ...(options.readiness ?? {}),
481
- },
482
- });
483
- if (options.metrics) {
484
- registerMetricsRoute(app, observability.meter, options.metrics);
485
- }
486
- else if (process.env["NODE_ENV"] === "production") {
487
- console.warn("[kumiko:boot] /metrics is off: no `metrics` option, so nothing is measured or scraped. " +
488
- "Set PROMETHEUS_METRICS_TOKEN (min 32 chars) and spread resolveObservabilityWiring(token) into the server options.");
489
- }
490
- app.use("/api/*", requestIdMiddleware({
491
- resolver: clientIpResolver,
492
- ...(options.errorDocs && { errorDocs: options.errorDocs }),
493
- }));
494
- // Cap JSON bodies before rate-limit/auth/observability even run. Header-
495
- // check is O(1); oversized requests never allocate memory for a full body
496
- // parse. Upload route keeps its own per-field maxSize.
14
+ // Hono runs middleware and routes in registration order, so the order below is behavior.
15
+ // On "*" and first: auth routes, auth/csrf guards and tenant-cookie helpers read the names from the context.
16
+ const sessionCookies = installSessionCookies(app, options.auth);
17
+ const isPublicApiRequest = compilePublicApiRequestMatcher(options.extraRoutes);
18
+ // /health and /metrics sit outside /api/*, so the /api/* guards below never run for them.
19
+ mountOperationalRoutes(app, wiring);
20
+ // First on /api/*: every later layer logs with the request id and client ip it sets.
21
+ installRequestId(app, wiring);
22
+ // O(1) header check before rate limit, auth and observability touch the body.
497
23
  registerBodyLimit(app, options.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES);
498
- // L1/L2 rate-limit middleware run BEFORE auth so an unauthenticated
499
- // flood can't even reach the JWT-verify code path. Wired only when
500
- // the caller passed `rateLimit.global` or `rateLimit.auth`. The
501
- // resolver is the auto-wired one (or `context.rateLimit` if set);
502
- // boot-fails loudly when the caller asked for middleware without a
503
- // working Redis to back it.
504
- let globalRateLimitGuard;
505
- if (wantsL1L2) {
506
- if (!rateLimitResolver) {
507
- throw new Error("rateLimit middleware requested but no resolver available — pass `context.redis` " +
508
- "or `context.rateLimit` so the resolver can be built.");
509
- }
510
- if (options.rateLimit?.global) {
511
- globalRateLimitGuard = globalIpRateLimit({
512
- ...options.rateLimit.global,
513
- resolver: rateLimitResolver,
514
- clientIpResolver,
515
- meter: observability.meter,
516
- });
517
- app.use("/api/*", globalRateLimitGuard);
518
- }
519
- if (options.rateLimit?.auth) {
520
- const { path: l2Path = "/api/auth/*", ...l2Opts } = options.rateLimit.auth;
521
- app.use(l2Path, authEndpointRateLimit({ ...l2Opts, resolver: rateLimitResolver, clientIpResolver }));
522
- }
523
- }
524
- // Observability span wraps everything that follows (auth, routes).
525
- // Must come AFTER request-id (so span can carry the id) and BEFORE auth
526
- // (so auth-verify can be a child span once we instrument it in v2).
527
- app.use("/api/*", observabilityMiddleware({
528
- tracer: observability.tracer,
529
- meter: observability.meter,
530
- }));
531
- // Tripwire: a kumiko-pii: ciphertext in a JSON response is always a bug
532
- // (raw read leaked past a decrypt) — dev fails loud, prod redacts (#820).
533
- app.use("/api/*", piiCiphertextResponseGuard());
534
- // Auth middleware skips public paths (login, health) — those routes need
535
- // to be callable without a valid JWT. Every other /api/* request requires
536
- // a token (or, when anonymousAccess is wired, falls through as anonymous).
537
- // A session-checker is forwarded when the auth-config wires one, so the
538
- // middleware can reject revoked sids on every request.
539
- // Mounting a tenantLifecycleStatus provider is what turns the 410 on, so no
540
- // entrypoint can forget the wiring; `??` short-circuits, so an explicit
541
- // auth.resolveTenantLifecycleStatus remains the override.
542
- const tenantLifecycleResolver = options.auth?.resolveTenantLifecycleStatus ??
543
- deriveTenantLifecycleResolver(options.registry, baseDb);
544
- // sessionOnlyGuard deliberately does NOT get this — its callers have no
545
- // anonymousAccess fallback, so a foreign-origin cookie there must keep
546
- // failing through the sibling originMiddleware 403.
547
- const normalizedForeignCookieOrigins = options.auth?.allowedOrigins?.length
548
- ? new Set(options.auth.allowedOrigins.map(normalizeOrigin))
549
- : undefined;
550
- const tenantlessAnonymousQns = new Set([...options.registry.getAllWriteHandlers()]
551
- .filter(([, handler]) => handler.tenantlessAnonymous === true)
552
- .map(([qn]) => qn));
553
- const jwtGuard = authMiddleware(jwt, {
554
- ...(tenantlessAnonymousQns.size > 0
555
- ? { isTenantlessAnonymousWrite: (qn) => tenantlessAnonymousQns.has(qn) }
556
- : {}),
557
- ...(options.auth?.sessionChecker ? { sessionChecker: options.auth.sessionChecker } : {}),
558
- ...(options.auth?.tokenVerifier ? { tokenVerifier: options.auth.tokenVerifier } : {}),
559
- ...(tenantLifecycleResolver ? { resolveTenantLifecycleStatus: tenantLifecycleResolver } : {}),
560
- ...(options.anonymousAccess ? { anonymousAccess: options.anonymousAccess } : {}),
561
- ...(normalizedForeignCookieOrigins
562
- ? { foreignCookieOrigins: normalizedForeignCookieOrigins }
563
- : {}),
564
- });
565
- app.use("/api/*", async (c, next) => {
566
- if (PUBLIC_API_PATHS.has(c.req.path) || isExtraRoutePublicPath(c))
567
- return next();
568
- return jwtGuard(c, next);
569
- });
570
- // Fail-closed PAT scoping: a PAT-authenticated caller (user.pat set by
571
- // jwtGuard's tokenVerifier above) may only reach the dispatcher routes —
572
- // everywhere else on /api/* is off-limits regardless of granted scopes.
573
- const patRouteGuardMiddleware = patRouteGuard();
574
- app.use("/api/*", async (c, next) => {
575
- if (PUBLIC_API_PATHS.has(c.req.path) || isExtraRoutePublicPath(c))
576
- return next();
577
- return patRouteGuardMiddleware(c, next);
578
- });
579
- // Without anonymousAccess a missing token 401s instead of falling through as anonymous.
580
- const sessionOnlyGuard = authMiddleware(jwt, {
581
- ...(options.auth?.sessionChecker ? { sessionChecker: options.auth.sessionChecker } : {}),
582
- ...(options.auth?.tokenVerifier ? { tokenVerifier: options.auth.tokenVerifier } : {}),
583
- ...(tenantLifecycleResolver ? { resolveTenantLifecycleStatus: tenantLifecycleResolver } : {}),
584
- });
585
- // PAT rate limiting — runs AFTER the auth guard so the resolved principal is
586
- // available. Only PAT-authenticated requests are counted (keyed by token id);
587
- // cookie/JWT users pass through untouched. In-memory limiter is per-instance
588
- // (see run-prod-app) — a multi-node deployment wanting a shared counter swaps
589
- // in a Redis-backed LoginRateLimiter.
590
- const patRateLimiter = options.auth?.patRateLimiter;
591
- const patRateLimitGuard = patRateLimiter ? buildPatRateLimitGuard(patRateLimiter) : undefined;
592
- if (patRateLimitGuard) {
593
- app.use("/api/*", async (c, next) => {
594
- if (PUBLIC_API_PATHS.has(c.req.path) || isExtraRoutePublicPath(c))
595
- return next();
596
- return patRateLimitGuard(c, next);
597
- });
598
- }
599
- // Origin-allowlist guard — additional CSRF-hardening for deployments that
600
- // widen the auth cookie across subdomains (auth.cookieDomain). Registered
601
- // when allowedOrigins is non-empty, or with host-only cookies when
602
- // auth.publicOrigin is known (see resolveOriginGuard), with the same /api/* + public-skip
603
- // scope as the CSRF guard and BEFORE it, so a disallowed cross-site POST
604
- // surfaces as `origin_not_allowed` rather than `csrf_token_mismatch`. Fails
605
- // closed (assertOriginGuardConfig throws) when a wide cookieDomain is set
606
- // without an allowlist and without an explicit opt-out — that config is the
607
- // unguarded-subdomain-XSS footgun, not a warn-and-continue case.
608
- assertOriginGuardConfig(options.auth);
609
- assertSessionCallbacksPaired(options.auth);
610
- const allowedOrigins = options.auth?.allowedOrigins;
611
- const originGuard = resolveOriginGuard(options.auth);
612
- if (originGuard) {
613
- app.use("/api/*", async (c, next) => {
614
- if (PUBLIC_API_PATHS.has(c.req.path) || isExtraRoutePublicPath(c))
615
- return next();
616
- return originGuard(c, next);
617
- });
618
- }
619
- // Double-submit CSRF guard — runs only on cookie-authenticated,
620
- // state-changing requests (POST/PUT/PATCH/DELETE). The guard reads the
621
- // authTransport flag set by authMiddleware, so public paths (no auth)
622
- // and bearer-authenticated paths (no cookie vector) fall straight
623
- // through. Must be registered AFTER the auth middleware above so the
624
- // flag is populated; registered for the same scope so /api/* routes
625
- // are covered uniformly.
626
- const csrfGuard = csrfMiddleware();
627
- app.use("/api/*", async (c, next) => {
628
- if (PUBLIC_API_PATHS.has(c.req.path) || isExtraRoutePublicPath(c))
629
- return next();
630
- return csrfGuard(c, next);
631
- });
632
- // No PAT rate-limit here: patRouteGuardMiddleware rejects every PAT on httpRoutes before it could count.
633
- // httpRoutes sit outside /api/*, so the pre-auth /api/* middlewares do not run for them: the
634
- // global IP limit (an unauthenticated flood must not reach JWT verify / session checks) and the
635
- // PII ciphertext tripwire are re-attached here. requestId, body limit and observability are not.
636
- const sessionOnlyHttpRouteGuards = [
637
- ...(globalRateLimitGuard ? [globalRateLimitGuard] : []),
638
- piiCiphertextResponseGuard(),
639
- sessionOnlyGuard,
640
- patRouteGuardMiddleware,
641
- ...(originGuard ? [originGuard] : []),
642
- csrfGuard,
643
- ];
644
- // Public auth routes (login) need to be registered BEFORE the generic
645
- // api routes so Hono matches them first.
646
- if (options.auth) {
647
- // A membershipQuery handler is registered but principalStatus is not provided by exactly
648
- // one feature — surface that misconfig at boot instead of an InternalError on first login/switch-tenant.
649
- if (options.registry.getQueryHandler(options.auth.membershipQuery)) {
650
- const principalStatusProviders = options.registry.getExtensionUsages(EXT_PRINCIPAL_STATUS).length;
651
- if (principalStatusProviders === 0) {
652
- throw new Error(`[kumiko] auth membershipQuery "${options.auth.membershipQuery}" is registered but no feature ` +
653
- 'provides the "principalStatus" contract — mount the user feature (tenant switch and sign-in ' +
654
- "need it to reject blocked principals).");
655
- }
656
- if (principalStatusProviders > 1) {
657
- throw new Error(`[kumiko] auth membershipQuery "${options.auth.membershipQuery}" is registered but ` +
658
- `${principalStatusProviders} features provide the "principalStatus" contract — exactly one ` +
659
- "is expected (the bundled user feature already provides it).");
660
- }
661
- }
662
- app.route("/api", createAuthRoutes(dispatcher, jwt, {
663
- ...options.auth,
664
- secureCookies: sessionCookies.secure,
665
- resolver: clientIpResolver,
666
- }));
667
- }
668
- app.route("/api", createClientErrorRoute({
669
- resolver: rateLimitResolver ??
670
- (wrappedRedis ? createRateLimitResolver({ redis: wrappedRedis }) : undefined),
671
- clientIpResolver,
672
- meter: observability.meter,
673
- identifySession: (c) => identifyOptionalSession(c, jwt),
674
- }));
675
- app.route("/api", createApiRoutes(dispatcher, {
676
- ...(options.sseHeartbeatMs !== undefined ? { sseHeartbeatMs: options.sseHeartbeatMs } : {}),
677
- }));
678
- app.route("/api", createSseRoute(sseBroker, {
679
- anonymousLiveEntities: collectAnonymousLiveEntities(options.registry),
680
- entityReadAccess: collectEntityReadAccess(options.registry),
681
- }));
682
- // GET /api/schema — the only way a client obtains the AppSchema. Behind
683
- // jwtGuard (NON_PUBLIC_API_PATHS), so anonymousAccess's synthesised user
684
- // also gets rejected below — the schema never reaches an unauthenticated
685
- // caller. The FULL schema is built lazily once — the registry is
686
- // immutable for this server's lifetime, so it's the same on every
687
- // request — then projected per caller-role-set (fw#3314: a role only
688
- // sees the screens/navs/workspaces/content-collections it may reach,
689
- // not the whole app's schema) and cached per role key. Tenant is
690
- // deliberately NOT part of the key: the projection depends only on
691
- // roles, and per-tenant caching would grow unboundedly across tenants
692
- // that share the same role set. What IS part of the key: the sorted set of
693
- // features the caller's tenant has switched off (r.toggleable) — few
694
- // distinct sets, so the cache stays small. The resolver is read per request
695
- // because run{Dev,Prod}App fill it in after the server is built.
696
- let fullSchema;
697
- const projectedSchemaCache = new Map();
698
- app.get(`/api${Routes.schema}`, async (c) => {
699
- const user = getUser(c);
700
- if (isMissingOrAnonymousUser(user)) {
701
- return unauthenticatedResponse(c);
702
- }
703
- const effectiveFeatures = options.dispatcherOptions?.effectiveFeatures;
704
- const disabledFeatureNames = effectiveFeatures === undefined
705
- ? []
706
- : await resolveDisabledFeatureNames(options.registry, effectiveFeatures, user.tenantId);
707
- const roleKey = JSON.stringify([[...new Set(user?.roles ?? [])].sort(), disabledFeatureNames]);
708
- let cached = projectedSchemaCache.get(roleKey);
709
- if (cached === undefined) {
710
- if (fullSchema === undefined) {
711
- fullSchema = buildAppSchema(options.registry, {
712
- searchAdapterMissing: !options.context.searchAdapter,
713
- });
714
- }
715
- const projected = projectAppSchemaForRoles(stripDisabledFeaturesFromAppSchema(fullSchema, options.registry, disabledFeatureNames), user?.roles ?? []);
716
- const json = JSON.stringify(projected);
717
- cached = { json, etag: computeStrongEtag(json) };
718
- projectedSchemaCache.set(roleKey, cached);
719
- }
720
- const cacheHeaders = { "Cache-Control": "private, no-cache", ETag: cached.etag };
721
- if (etagMatches(c.req.header("If-None-Match") ?? null, cached.etag)) {
722
- return c.body(null, 304, cacheHeaders);
723
- }
724
- return c.body(cached.json, 200, {
725
- "Content-Type": "application/json; charset=utf-8",
726
- ...cacheHeaders,
727
- });
728
- });
729
- // Mount upload/download routes whenever a file provider is resolvable (a
730
- // file-provider plugin is mounted, or a resolver was injected). They resolve
731
- // the provider per-tenant through file-foundation — no `files` option; route
732
- // policy comes from createFilesFeature(opts?). Gating on the resolver (not on
733
- // declared file fields) keeps unattached uploads working and matches the old
734
- // "files option present → routes" behavior.
735
- if (fileProviderResolver) {
736
- const fileDb = options.context.db; // @cast-boundary engine-bridge
737
- if (!fileDb)
738
- throw new Error("file routes require db in context");
739
- const routeOptions = readFilesRouteOptions(options.registry);
740
- const canReadRecord = createRecordReadCheck(options.registry, dispatcher.query);
741
- app.route("/api", createFileRoutes({
742
- db: fileDb,
743
- registry: options.registry,
744
- resolveProvider: fileProviderResolver,
745
- canReadRecord,
746
- canWriteRecord: createRecordWriteCheck({
747
- registry: options.registry,
748
- canReadRecord,
749
- tenantDbFor: (tenantId) => createProjectingTenantDb(fileDb, tenantId, options.registry),
750
- }),
751
- ...(routeOptions.accessGuard ? { accessGuard: routeOptions.accessGuard } : {}),
752
- ...(routeOptions.privilegedRoles ? { privilegedRoles: routeOptions.privilegedRoles } : {}),
753
- ...(routeOptions.unclaimedUploadReaders
754
- ? { unclaimedUploadReaders: routeOptions.unclaimedUploadReaders }
755
- : {}),
756
- ...(routeOptions.maxUploadSize ? { maxUploadSize: routeOptions.maxUploadSize } : {}),
757
- }));
758
- }
759
- // Feature-deklarierte HTTP-Routes (r.httpRoute). Mount nach /api/* damit
760
- // /api/* immer Vorrang hat — feature-Routes liegen ohnehin außerhalb
761
- // (Boot-Validator blockt /api-Prefix). deps.app ist die Outer-App, sodass
762
- // der Handler /api/query intern via app.fetch(...) nutzen kann (gleicher
763
- // Auth-Pfad wie ein echter HTTP-Call). deps.systemQuery umgeht diesen
764
- // Pfad bewusst — für Routes die einen FESTEN Tenant erzwingen müssen
765
- // (z.B. legal-pages → immer SYSTEM_TENANT_ID), statt ihn per X-Tenant-
766
- // Header vorzutäuschen (das sieht für die anonymousAccess-Auflösung
767
- // wie ein normaler Client-Header aus und wird von resolverTrust:
768
- // "authoritative"-Configs zurecht als Tenant-Override abgelehnt).
769
- for (const feature of options.registry.features.values()) {
770
- for (const route of Object.values(feature.httpRoutes)) {
771
- // @wrapper-known semantic-alias
772
- const honoHandler = async (c) => route.handler(c, {
773
- app,
774
- // createAnonymousUser, NOT createSystemUser: systemQuery's
775
- // synthesized user must clear the SAME access gate a real
776
- // anonymous visitor would, no more — regardless of the route's
777
- // own `anonymous` mode. The system role would ALSO satisfy that
778
- // gate here, but it can read fields gated to "system" that
779
- // "anonymous" can't (filterReadFields is a plain role-in-map
780
- // check) — a systemQuery caller reading a system-gated field
781
- // would leak it into the response. The forced tenant already
782
- // comes from bypassing the HTTP layer entirely; no elevated
783
- // role is needed or wanted on top of that.
784
- systemQuery: makeSystemQuery(c, dispatcher, clientIpResolver),
785
- clientIp: clientIpResolver.resolve(clientIpSourceFromHonoContext(c)),
786
- });
787
- // Without a resolver (no Redis in the context — dev/test stacks) the
788
- // declared limit is skipped rather than failing the boot of every app
789
- // that mounts a bundled feature whose routes carry a default limit.
790
- const routeLimit = route.rateLimit && rateLimitResolver
791
- ? [
792
- httpRouteRateLimit({
793
- resolver: rateLimitResolver,
794
- rateLimit: route.rateLimit,
795
- routeKey: `${route.method} ${route.path}`,
796
- clientIpResolver,
797
- meter: observability.meter,
798
- }),
799
- ]
800
- : [];
801
- mountHonoRoute(app, route.method, route.path, honoHandler, [
802
- ...routeLimit,
803
- ...(route.anonymous ? [] : sessionOnlyHttpRouteGuards),
804
- ]);
805
- }
806
- }
807
- // r.webSocketRoute — GET routes under /api/ws/*, so the jwt/pat/rate-limit
808
- // chain above already ran. Origin/CSRF guards skip GETs, hence the own check.
809
- const webSocketOriginAllowlist = allowedOrigins?.length
810
- ? new Set(allowedOrigins.map(normalizeOrigin))
811
- : undefined;
812
- const webSocketRoutePaths = new Map();
813
- const webSocketConnectionLimiter = createWebSocketConnectionLimiter();
814
- for (const feature of options.registry.features.values()) {
815
- for (const route of Object.values(feature.webSocketRoutes)) {
816
- const owner = webSocketRoutePaths.get(route.path);
817
- if (owner !== undefined) {
818
- throw new Error(`[kumiko] WebSocket route "${route.path}" is declared by both feature "${owner}" and ` +
819
- `"${feature.name}" — paths must be unique across features.`);
820
- }
821
- webSocketRoutePaths.set(route.path, feature.name);
822
- app.get(route.path, buildWebSocketRouteHandler(route, {
823
- dispatcher,
824
- clientIpResolver,
825
- originAllowlist: webSocketOriginAllowlist,
826
- ...(options.auth?.sessionChecker ? { sessionChecker: options.auth.sessionChecker } : {}),
827
- ...(tenantLifecycleResolver
828
- ? { resolveTenantLifecycleStatus: tenantLifecycleResolver }
829
- : {}),
830
- connectionLimiter: webSocketConnectionLimiter,
831
- }));
832
- }
833
- }
834
- // extraRoutes (kumiko-framework#3050) — declarative HTTP-routes with a
835
- // Pflicht `entry` tier. Mounted after r.httpRoute for the same reason: an
836
- // extraRoute dispatching through `dispatcher` builds Hono's matcher, so
837
- // this must run before any seed that also dispatches (runProdApp/
838
- // createKumikoServer call buildServer before seeding).
839
- if (options.extraRoutes) {
840
- // Boot-time validation for the whole list BEFORE mounting anything —
841
- // an app with one bad route should fail loud at boot, not mount N-1
842
- // routes and then throw on route N.
843
- for (const route of options.extraRoutes) {
844
- if (!isKnownExtraRouteEntry(route.entry)) {
845
- throw new Error(`[kumiko] extraRoutes: unknown entry "${String(route.entry)}" on ` +
846
- `"${route.method} ${route.path}" — expected "anonymous" | "user" | "signature". ` +
847
- "A JS caller without the ExtraRouteDefinition type can hit this at boot.");
848
- }
849
- if (route.entry === ExtraRouteEntries.user && !route.path.startsWith("/api/")) {
850
- throw new Error(`[kumiko] extraRoutes: entry:"user" route "${route.method} ${route.path}" must be ` +
851
- "mounted under \"/api/\" — that's the only path prefix that rides the framework's " +
852
- "jwtGuard chain, which is what populates deps.user.");
853
- }
854
- // A signature route under /api/ skips jwtGuard/origin/csrf for every
855
- // path its pattern matches — a wildcard would switch off auth for
856
- // unrelated /api/* handlers (e.g. "/api/*" swallows /api/write).
857
- if (route.entry === ExtraRouteEntries.signature &&
858
- route.path.startsWith("/api/") &&
859
- route.path.includes("*")) {
860
- throw new Error(`[kumiko] extraRoutes: entry:"signature" route "${route.method} ${route.path}" must not ` +
861
- 'use a wildcard under "/api/" — it would bypass the auth chain for every matching path.');
862
- }
863
- // A `:param` segment is as broad as a wildcard, and the public matchers test
864
- // the bare request path: "/:seg/write" and "/api/:hook" both match /api/write.
865
- if (route.entry === ExtraRouteEntries.signature) {
866
- const routePattern = honoPathToRegex(route.path);
867
- const shadowedFrameworkPath = [...PUBLIC_API_PATHS, ...NON_PUBLIC_API_PATHS].find((path) => routePattern.test(path));
868
- if (shadowedFrameworkPath !== undefined) {
869
- throw new Error(`[kumiko] extraRoutes: entry:"signature" route "${route.method} ${route.path}" must not ` +
870
- `match the framework path "${shadowedFrameworkPath}" — it would bypass the auth chain for it.`);
871
- }
872
- }
873
- }
874
- const dispatchSystemWrite = makeDispatchSystemWrite(dispatcher);
875
- const dispatchSystemQuery = makeDispatchSystemQuery(dispatcher);
876
- for (const route of options.extraRoutes) {
877
- const honoHandler = buildExtraRouteHonoHandler(route, {
878
- app,
879
- dispatcher,
880
- registry: options.registry,
881
- secrets: contextWithObservability.secrets,
882
- dispatchSystemWrite,
883
- dispatchSystemQuery,
884
- clientIpResolver,
885
- });
886
- mountHonoRoute(app, route.method, route.path, honoHandler, bodyLimitForRoutePath(route.path, options.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES));
887
- }
888
- }
889
- // /version-Default registriert NACH feature-routes — Hono "first match
890
- // wins", also gewinnt feature-deklariertes /version (z.B. App-spezifisches
891
- // version-format mit Tenant-Stats) wenn vorhanden, sonst greift der
892
- // Default-Handler aus BUILD_VERSION/BUILD_TIME-env-vars.
24
+ // Before auth, so an unauthenticated flood never reaches JWT verify.
25
+ const globalRateLimitGuard = installRateLimitMiddleware(app, wiring);
26
+ // After the request id (the span carries it), before auth and routes (they run inside the span).
27
+ installObservability(app, wiring.observability);
28
+ // Before the auth chain, so its error responses pass the ciphertext tripwire too.
29
+ installPiiLeakGuard(app);
30
+ // jwt first: the PAT route scope, PAT rate limit and csrf guards read the principal it resolves.
31
+ const authGuards = installAuthGuardChain(app, wiring, {
32
+ isPublicApiRequest,
33
+ globalRateLimitGuard,
34
+ });
35
+ // Before the generic /api routes: Hono serves the first match.
36
+ mountAuthRoutes(app, wiring, sessionCookies);
37
+ mountClientErrorRoute(app, wiring);
38
+ mountDispatcherRoutes(app, wiring);
39
+ mountSchemaRoute(app, options);
40
+ mountFileRoutes(app, wiring);
41
+ // Feature routes after /api/*, so the framework paths always win.
42
+ mountFeatureHttpRoutes(app, wiring, authGuards.sessionOnlyHttpRouteGuards);
43
+ mountWebSocketRoutes(app, wiring, authGuards.tenantLifecycleResolver);
44
+ mountExtraRoutes(app, wiring);
45
+ // After feature routes, so a feature-declared /version wins.
893
46
  registerVersionRoute(app);
894
- // Marks "no route matched this path" so tryHonoFirst (server-runtime)
895
- // can tell it apart from a matched route's OWN deliberate 404 (e.g.
896
- // default-deny reads like file-derivatives' public-variant route) —
897
- // without this, tryHonoFirst's only signal was the status code, and a
898
- // matched route answering 404 got silently rewritten to the SPA shell
899
- // with status 200 (kumiko-framework#2435). Must be the LAST thing wired
900
- // on `app`: this only fires when the router found no handler at all, so
901
- // a route's own `c.text(..., 404)` never passes through here. A handler
902
- // that calls `c.notFound()` instead of building its own Response DOES
903
- // route through this same handler and stays indistinguishable from a
904
- // routing miss — pre-existing Hono semantics, not something this fix
905
- // changes; deliberate 404s must build their own Response.
906
- // The header is an internal signal only — tryHonoFirst and every direct
907
- // app.fetch() passthrough strip it before a response reaches a client.
908
- app.notFound((c) => c.text("Not Found", 404, { [NO_ROUTE_MATCH_HEADER_NAME]: "1" }));
47
+ // Last: it may only fire when no route matched at all.
48
+ installNoRouteMatchMarker(app);
909
49
  return {
910
50
  app,
911
- jwt,
912
- sseBroker,
913
- observability,
914
- dispatcher,
915
- context: contextWithObservability,
916
- ...(eventDispatcher ? { eventDispatcher } : {}),
51
+ jwt: wiring.jwt,
52
+ sseBroker: wiring.sseBroker,
53
+ observability: wiring.observability,
54
+ dispatcher: wiring.dispatcher,
55
+ lifecycleHooks: wiring.lifecycleHooks,
56
+ context: wiring.context,
57
+ ...(wiring.eventDispatcher ? { eventDispatcher: wiring.eventDispatcher } : {}),
917
58
  ...(options.lifecycle ? { lifecycle: options.lifecycle } : {}),
918
59
  };
919
60
  }
920
- // Method-switch shared by r.httpRoute and extraRoutes — one place to keep
921
- // the two mounting paths from drifting on which Hono methods get a
922
- // convenience-call vs. app.on().
923
- function mountHonoRoute(app, method, path,
924
- // biome-ignore lint/suspicious/noExplicitAny: Hono context generics are invisible at the framework boundary
925
- handler, middlewares = []) {
926
- // Guards go into the route's own handler chain, never a method-gated
927
- // app.use: Hono serves HEAD through the GET route with c.req.method still
928
- // "HEAD", so a `method === c.req.method` gate would skip them for HEAD.
929
- if (middlewares.length > 0) {
930
- // [path]: only Hono's array-path overload accepts a variable-length handler spread.
931
- app.on(method, [path], ...middlewares, handler);
932
- // skip: guarded route already mounted with its guard chain
933
- return;
934
- }
935
- switch (method) {
936
- case "GET":
937
- app.get(path, handler);
938
- break;
939
- case "POST":
940
- app.post(path, handler);
941
- break;
942
- case "PUT":
943
- app.put(path, handler);
944
- break;
945
- case "PATCH":
946
- app.patch(path, handler);
947
- break;
948
- case "DELETE":
949
- app.delete(path, handler);
950
- break;
951
- case "OPTIONS":
952
- case "HEAD":
953
- // Hono's on() for the methods without a convenience method.
954
- app.on(method, path, handler);
955
- break;
956
- default:
957
- assertUnreachable(method, "http method");
958
- }
959
- }
960
- // Must run after the auth guard so getUser(c) carries the PAT.
961
- function buildPatRateLimitGuard(patRateLimiter) {
962
- return async (c, next) => {
963
- const pat = getUser(c)?.pat;
964
- if (pat && !(await patRateLimiter.check(pat.tokenId))) {
965
- return c.json({
966
- error: {
967
- code: "pat_rate_limited",
968
- httpStatus: 429,
969
- message: "personal access token rate limit exceeded",
970
- i18nKey: "auth.errors.patRateLimited",
971
- },
972
- }, 429);
973
- }
974
- return next();
975
- };
976
- }
977
- // Shared systemQuery builder for r.httpRoute and extraRoutes (anonymous +
978
- // signature entries). requestContext.run must wrap the dispatcher call —
979
- // both route kinds run outside the requestIdMiddleware chain that normally
980
- // populates it, and `rateLimit: {per: "ip", ...}` on a handler invoked
981
- // through systemQuery is otherwise silent dead-code (enforceRateLimit reads
982
- // requestContext.get()?.ip, undefined without this wrap).
983
- function makeSystemQuery(
984
- // biome-ignore lint/suspicious/noExplicitAny: Hono context generics are invisible at the framework boundary
985
- c, dispatcher, clientIpResolver) {
986
- return (type, payload, tenantId) => requestContext.run(requestContext.get() ?? buildRequestContextData(c, clientIpResolver), () => dispatcher.query(type, payload, createAnonymousUser(tenantId)));
987
- }
988
- // SystemAdmin write/query builders shared by buildServer's `extraRoutes`
989
- // mount and server-runtime's `wire` hook (runProdApp/createKumikoServer,
990
- // after buildServer). Privilege-scope: SystemAdmin is the highest
991
- // non-tenant-scoped role — reaches ANY SystemAdmin-gated handler on ANY
992
- // tenant. Only safe for callers that already proved their own authenticity
993
- // (signature verify(), HMAC state, ...), never exposed to a raw request.
994
- export function makeDispatchSystemWrite(dispatcher) {
995
- return ({ handlerQn, payload, tenantId }) => dispatcher.write(handlerQn, payload, createSystemUser(tenantId, [ROLES.SystemAdmin]));
996
- }
997
- // Privilege-scope: the system user gets exactly the roles the caller names —
998
- // no implicit SystemAdmin — so a seed can write data gated on app roles.
999
- // Same trust requirement as makeDispatchSystemWrite: never expose to a raw
1000
- // request, only to code that already proved its own authenticity.
1001
- export function makeDispatchWriteAs(dispatcher) {
1002
- return ({ handlerQn, payload, tenantId, roles }) => dispatcher.write(handlerQn, payload, createSystemUser(tenantId, roles));
1003
- }
1004
- export function makeDispatchSystemQuery(dispatcher) {
1005
- return ({ handlerQn, payload, tenantId }) => dispatcher.query(handlerQn, payload, createSystemUser(tenantId, [ROLES.SystemAdmin]));
1006
- }
1007
- // Same dispatcher.write(...) as entry:"user", but the user is getUser(c) —
1008
- // see AnonymousExtraRouteDeps.write for the privilege/tenant contract.
1009
- function makeAnonymousWrite(
1010
- // biome-ignore lint/suspicious/noExplicitAny: Hono context generics are invisible at the framework boundary
1011
- c, dispatcher) {
1012
- return (type, payload) => {
1013
- const user = getUser(c);
1014
- if (!user) {
1015
- throw new Error('[kumiko] extraRoutes: entry:"anonymous" deps.write requires this route to be mounted ' +
1016
- 'under "/api/" with anonymousAccess wired — no request-resolved session user was found.');
1017
- }
1018
- return dispatcher.write(type, payload, user);
1019
- };
1020
- }
1021
- // Shared by entry:"user" extra routes and GET /api/schema — both require a
1022
- // real, signed-in principal and reject the synthesised anonymousAccess user
1023
- // (SessionUser.roles includes ANONYMOUS_ROLE) the same way.
1024
- function isMissingOrAnonymousUser(user) {
1025
- return !user || isAnonymousSessionUser(user);
1026
- }
1027
- function unauthenticatedResponse(c) {
1028
- return c.json({
1029
- error: {
1030
- code: "unauthenticated",
1031
- httpStatus: 401,
1032
- message: "this route requires a signed-in user",
1033
- i18nKey: "auth.errors.missingToken",
1034
- },
1035
- }, 401);
1036
- }
1037
- const webSocketLog = createFallbackLogger("websocket");
1038
- const extraRouteLog = createFallbackLogger("extra-route");
1039
- function webSocketErrorResponse(c, status, code, message) {
1040
- return c.json({ error: { code, httpStatus: status, message } }, status);
1041
- }
1042
- function buildWebSocketRouteHandler(route, shared) {
1043
- return async (c) => {
1044
- if (!isWebSocketOriginAllowed(c, shared.originAllowlist))
1045
- return rejectOrigin(c);
1046
- const user = getUser(c);
1047
- if (isMissingOrAnonymousUser(user))
1048
- return unauthenticatedResponse(c);
1049
- if (!isWebSocketUpgradeRequest(c.req.raw)) {
1050
- return webSocketErrorResponse(c, 426, "websocket_upgrade_required", "this route only accepts WebSocket upgrade requests");
1051
- }
1052
- const honoEnv = c.env;
1053
- if (!hasWebSocketUpgradeServer(honoEnv)) {
1054
- const message = "webSocketUpgradeFetch not wired: pass it to buildBunServeOptions";
1055
- webSocketLog.error(message, { path: route.path });
1056
- return webSocketErrorResponse(c, 501, "websocket_upgrade_not_wired", message);
1057
- }
1058
- // The slot is taken before connect (a refused attempt must not run it) and stays synchronous with
1059
- // the check, so concurrent upgrades can't overshoot the cap. Every path without a live socket frees it.
1060
- const releaseConnectionSlot = shared.connectionLimiter.tryAcquire(`${route.path}\n${user.tenantId}\n${user.id}`, route.maxConnectionsPerUser ?? WEBSOCKET_DEFAULT_MAX_CONNECTIONS_PER_USER);
1061
- if (!releaseConnectionSlot) {
1062
- return webSocketErrorResponse(c, 429, "websocket_connection_limit", "too many open WebSocket connections for this user");
1063
- }
1064
- let upgraded = false;
1065
- try {
1066
- const handlers = await route.connect(c, {
1067
- user,
1068
- query: (type, payload) => shared.dispatcher.query(type, payload, user),
1069
- write: (type, payload) => shared.dispatcher.write(type, payload, user),
1070
- clientIp: shared.clientIpResolver.resolve(clientIpSourceFromHonoContext(c)),
1071
- });
1072
- if (handlers instanceof Response)
1073
- return handlers;
1074
- const captured = requestContext.get();
1075
- const requestContextData = captured ? withoutAbortSignal(captured) : undefined;
1076
- const revalidateSession = buildWebSocketSessionRevalidator({
1077
- user,
1078
- sessionChecker: shared.sessionChecker,
1079
- resolveTenantLifecycleStatus: shared.resolveTenantLifecycleStatus,
1080
- tokenExpiresAtSec: getAuthTokenExpiry(c),
1081
- });
1082
- upgraded = honoEnv.server.upgrade(c.req.raw, {
1083
- data: {
1084
- handlers,
1085
- maxMessageBytes: route.maxMessageBytes ?? WEBSOCKET_DEFAULT_MAX_MESSAGE_BYTES,
1086
- requestContextData,
1087
- revalidateSession,
1088
- releaseConnectionSlot,
1089
- },
1090
- });
1091
- if (!upgraded) {
1092
- return webSocketErrorResponse(c, 400, "websocket_upgrade_failed", "the WebSocket upgrade was rejected");
1093
- }
1094
- // Bun ignores the returned Response after a successful upgrade.
1095
- return new Response(null);
1096
- }
1097
- finally {
1098
- if (!upgraded)
1099
- releaseConnectionSlot();
1100
- }
1101
- };
1102
- }
1103
- // The request's AbortSignal fires when the upgrade request ends, which would
1104
- // abort every later handler running under the captured context.
1105
- function withoutAbortSignal(data) {
1106
- const { signal: _signal, ...rest } = data;
1107
- return rest;
1108
- }
1109
- function isKnownExtraRouteEntry(entry) {
1110
- return (entry === ExtraRouteEntries.anonymous ||
1111
- entry === ExtraRouteEntries.user ||
1112
- entry === ExtraRouteEntries.signature);
1113
- }
1114
- // Hono path pattern ("/api/foo/:bar", "/api/foo/*") → RegExp. Only the
1115
- // subset extraRoutes actually uses (static segments, `:param`, trailing
1116
- // `*`) — no inline `:param{regex}` constraints, no optional `:param?`.
1117
- function honoPathToRegex(path) {
1118
- const segments = path
1119
- .split("/")
1120
- .map((segment) => {
1121
- if (segment.startsWith(":"))
1122
- return "[^/]+";
1123
- if (segment === "*")
1124
- return ".*";
1125
- return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1126
- })
1127
- .join("/");
1128
- return new RegExp(`^${segments}$`);
1129
- }
1130
- // See the bypass comment at the jwtGuard mount above — only signature
1131
- // routes are public here.
1132
- function compileExtraRoutePublicMatchers(extraRoutes) {
1133
- if (!extraRoutes)
1134
- return [];
1135
- return extraRoutes
1136
- .filter((route) => route.entry === ExtraRouteEntries.signature)
1137
- .map((route) => ({ method: route.method, pattern: honoPathToRegex(route.path) }));
1138
- }
1139
- function buildExtraRouteHonoHandler(route, shared) {
1140
- switch (route.entry) {
1141
- case ExtraRouteEntries.anonymous:
1142
- return async (c) => route.handler(c, {
1143
- app: shared.app,
1144
- registry: shared.registry,
1145
- systemQuery: makeSystemQuery(c, shared.dispatcher, shared.clientIpResolver),
1146
- write: makeAnonymousWrite(c, shared.dispatcher),
1147
- clientIp: shared.clientIpResolver.resolve(clientIpSourceFromHonoContext(c)),
1148
- });
1149
- case ExtraRouteEntries.user:
1150
- return async (c) => {
1151
- const user = getUser(c);
1152
- if (isMissingOrAnonymousUser(user)) {
1153
- return unauthenticatedResponse(c);
1154
- }
1155
- return route.handler(c, {
1156
- app: shared.app,
1157
- registry: shared.registry,
1158
- user,
1159
- query: (type, payload) => shared.dispatcher.query(type, payload, user),
1160
- write: (type, payload) => shared.dispatcher.write(type, payload, user),
1161
- });
1162
- };
1163
- case ExtraRouteEntries.signature:
1164
- return async (c) => {
1165
- const rawBody = await c.req.text();
1166
- const headers = {};
1167
- c.req.raw.headers.forEach((value, key) => {
1168
- headers[key.toLowerCase()] = value;
1169
- });
1170
- let verified;
1171
- try {
1172
- verified = await route.verify({ rawBody, headers, params: c.req.param(), query: c.req.query() }, { registry: shared.registry, secrets: shared.secrets });
1173
- }
1174
- catch (e) {
1175
- if (e instanceof ExtraRouteRejection) {
1176
- if (e.retryAfterSeconds !== undefined) {
1177
- return c.json(e.body, e.status, { "Retry-After": String(e.retryAfterSeconds) });
1178
- }
1179
- return c.json(e.body, e.status);
1180
- }
1181
- // The body goes to unauthenticated callers; infra errors thrown by
1182
- // verify() (secrets, DB) must not leak, so the detail stays in the log.
1183
- extraRouteLog.error(`signature verify() threw on ${c.req.path}`, {
1184
- error: e instanceof Error ? e.message : String(e),
1185
- });
1186
- return c.json({
1187
- error: {
1188
- code: "extra_route_signature_invalid",
1189
- message: "signature verification failed",
1190
- },
1191
- }, 401);
1192
- }
1193
- return route.handler(c, verified, {
1194
- app: shared.app,
1195
- registry: shared.registry,
1196
- secrets: shared.secrets,
1197
- systemQuery: makeSystemQuery(c, shared.dispatcher, shared.clientIpResolver),
1198
- dispatchSystemWrite: shared.dispatchSystemWrite,
1199
- dispatchSystemQuery: shared.dispatchSystemQuery,
1200
- });
1201
- };
1202
- default:
1203
- return assertUnreachable(route, "extra route entry");
1204
- }
1205
- }
1206
- function deriveTenantLifecycleResolver(registry, db) {
1207
- const plugin = resolveTenantLifecyclePlugin(registry, "buildServer");
1208
- if (!plugin)
1209
- return undefined;
1210
- if (!db) {
1211
- throw new Error("[kumiko] a tenantLifecycleStatus provider is mounted (tenant-lifecycle) but context.db is " +
1212
- "missing — the request-level teardown gate needs a DbConnection. Pass context.db, or wire " +
1213
- "auth.resolveTenantLifecycleStatus explicitly.");
1214
- }
1215
- return (tenantId) => plugin.resolveStatus(tenantId, { db });
1216
- }
1217
- // Scans every feature's entities for a file/image/files/images field. Short-
1218
- // circuits on the first hit — no need to build a full inventory, we only want
1219
- // the yes/no answer for the boot check.
1220
- function registryDeclaresFileFields(registry) {
1221
- for (const feature of registry.features.values()) {
1222
- for (const entity of Object.values(feature.entities ?? {})) {
1223
- for (const field of Object.values(entity.fields)) {
1224
- if (isFileField(field))
1225
- return true;
1226
- }
1227
- }
1228
- }
1229
- return false;
1230
- }
1231
- // Entities whose entityList screen WOULD render a search box based on
1232
- // screen/field config alone: `screen.searchable` wins when set, otherwise
1233
- // the box shows iff the entity has ≥1 searchable field. `screen.searchable
1234
- // === false` is excluded — the boot-validator (entity-list-screens.ts) only
1235
- // allows that on the whitelisted download-attempt-list-style screens, which
1236
- // never render the box. This is the config-only half of the rule; the
1237
- // client additionally gates on FeatureSchema.searchAdapterMissing (#2062,
1238
- // set from the same `!options.context.searchAdapter` check below) so the
1239
- // box is actually suppressed once this function finds a hit.
1240
- function entitiesWithSearchableScreen(registry) {
1241
- const entities = new Set();
1242
- for (const feature of registry.features.values()) {
1243
- for (const screen of Object.values(feature.screens)) {
1244
- if (screen.type !== "entityList")
1245
- continue;
1246
- const isSearchable = screen.searchable === true ||
1247
- (screen.searchable === undefined && registry.getSearchableFields(screen.entity).length > 0);
1248
- if (isSearchable)
1249
- entities.add(screen.entity);
1250
- }
1251
- }
1252
- return [...entities];
1253
- }
1254
- function payloadDigestMasterSecret(jwtSecret) {
1255
- if (typeof jwtSecret === "string")
1256
- return jwtSecret;
1257
- const signingSecret = jwtSecret.keys[jwtSecret.signKid];
1258
- if (signingSecret === undefined) {
1259
- throw new Error(`[kumiko] jwtSecret.signKid "${jwtSecret.signKid}" not found in jwtSecret.keys`);
1260
- }
1261
- return signingSecret;
1262
- }