@cosmicdrift/kumiko-framework 0.387.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.
- package/AGENTS.md +6 -1
- package/agents/examples/anonymous-access.md +1 -1
- package/agents/examples/apex-landing.md +204 -0
- package/agents/examples/api-worker-split.md +64 -0
- package/agents/examples/app-config.md +14 -0
- package/agents/examples/auth-mfa.md +115 -0
- package/agents/examples/env-composition.md +28 -1
- package/agents/examples/legal-pages.md +1 -1
- package/agents/examples/prod-boot-options.md +16 -0
- package/agents/examples/rate-limiting.md +48 -0
- package/agents/examples/record-detail-layout.md +692 -0
- package/agents/examples/seed-migration.md +212 -0
- package/agents/examples/wizard-form.md +941 -0
- package/agents/examples/writeform-section.md +548 -0
- package/agents/features.md +19 -2
- package/agents/widgets.md +1 -0
- package/dist/api/client-error-route.js +8 -2
- package/dist/api/index.d.ts +3 -1
- package/dist/api/index.js +3 -1
- package/dist/api/request-context.d.ts +1 -1
- package/dist/api/request-context.js +1 -1
- package/dist/api/server-boot-checks.d.ts +10 -0
- package/dist/api/server-boot-checks.js +157 -0
- package/dist/api/server-event-dispatcher.d.ts +26 -0
- package/dist/api/server-event-dispatcher.js +208 -0
- package/dist/api/server-extra-routes.d.ts +11 -0
- package/dist/api/server-extra-routes.js +203 -0
- package/dist/api/server-middleware.d.ts +20 -0
- package/dist/api/server-middleware.js +211 -0
- package/dist/api/server-routes.d.ts +19 -0
- package/dist/api/server-routes.js +293 -0
- package/dist/api/server-websocket-routes.d.ts +4 -0
- package/dist/api/server-websocket-routes.js +108 -0
- package/dist/api/server-wiring.d.ts +32 -0
- package/dist/api/server-wiring.js +236 -0
- package/dist/api/server.d.ts +10 -15
- package/dist/api/server.js +48 -1251
- package/dist/api/session-cookies.js +4 -4
- package/dist/api/sse-route.js +16 -12
- package/dist/crypto/owner-transition-rekey.d.ts +5 -1
- package/dist/crypto/owner-transition-rekey.js +1 -1
- package/dist/crypto/pii-field-encryption.d.ts +5 -1
- package/dist/crypto/pii-field-encryption.js +3 -1
- package/dist/db/aggregate-sql.d.ts +21 -0
- package/dist/db/aggregate-sql.js +155 -0
- package/dist/db/closed-connection.d.ts +9 -0
- package/dist/db/closed-connection.js +95 -0
- package/dist/db/dialect.js +1 -1
- package/dist/db/distinct-on.d.ts +1 -1
- package/dist/db/driver-row-coercion.d.ts +2 -0
- package/dist/db/driver-row-coercion.js +186 -0
- package/dist/db/driver-value-preparation.d.ts +16 -0
- package/dist/db/driver-value-preparation.js +99 -0
- package/dist/db/entity-field-encryption.d.ts +1 -0
- package/dist/db/entity-field-encryption.js +1 -1
- package/dist/db/entity-table-meta.js +103 -110
- package/dist/db/event-store-executor-context.d.ts +2 -1
- package/dist/db/event-store-executor-read-aggregate.d.ts +8 -0
- package/dist/db/event-store-executor-read-aggregate.js +112 -0
- package/dist/db/event-store-executor-read-filter.d.ts +31 -0
- package/dist/db/event-store-executor-read-filter.js +203 -0
- package/dist/db/event-store-executor-read-paging.d.ts +14 -0
- package/dist/db/event-store-executor-read-paging.js +99 -0
- package/dist/db/event-store-executor-read-rows.d.ts +6 -0
- package/dist/db/event-store-executor-read-rows.js +32 -0
- package/dist/db/event-store-executor-read-search.d.ts +28 -0
- package/dist/db/event-store-executor-read-search.js +221 -0
- package/dist/db/event-store-executor-read-sort.d.ts +41 -0
- package/dist/db/event-store-executor-read-sort.js +130 -0
- package/dist/db/event-store-executor-read-where.d.ts +24 -0
- package/dist/db/event-store-executor-read-where.js +81 -0
- package/dist/db/event-store-executor-read.d.ts +2 -9
- package/dist/db/event-store-executor-read.js +48 -701
- package/dist/db/event-store-executor-write-steps.d.ts +20 -0
- package/dist/db/event-store-executor-write-steps.js +100 -0
- package/dist/db/event-store-executor-write.js +395 -499
- package/dist/db/index.d.ts +6 -2
- package/dist/db/index.js +5 -1
- package/dist/db/list-aggregate-labels.d.ts +14 -0
- package/dist/db/list-aggregate-labels.js +26 -0
- package/dist/db/migrate-generator.js +71 -86
- package/dist/db/migrate-runner.js +4 -1
- package/dist/db/query.d.ts +2 -15
- package/dist/db/query.js +8 -761
- package/dist/db/reference-data.js +6 -1
- package/dist/db/table-builder.js +113 -166
- package/dist/db/table-info.d.ts +10 -0
- package/dist/db/table-info.js +45 -0
- package/dist/db/temporal-value-guards.d.ts +6 -0
- package/dist/db/temporal-value-guards.js +15 -0
- package/dist/db/tenant-db-runner.d.ts +1 -0
- package/dist/db/tenant-db-runner.js +3 -0
- package/dist/db/tenant-db.js +39 -9
- package/dist/db/where-clause.d.ts +6 -0
- package/dist/db/where-clause.js +236 -0
- package/dist/derivatives/delete-stored-file.js +2 -1
- package/dist/engine/boot-validator/boot-check.js +1 -1
- package/dist/engine/boot-validator/detail-screens.js +2 -2
- package/dist/engine/boot-validator/entity-handler.d.ts +1 -0
- package/dist/engine/boot-validator/entity-handler.js +17 -0
- package/dist/engine/boot-validator/form-derivations.js +35 -1
- package/dist/engine/boot-validator/i18n-keys.js +5 -3
- package/dist/engine/boot-validator/index.js +2 -0
- package/dist/engine/boot-validator/pii-retention.js +233 -155
- package/dist/engine/boot-validator/screens-actions.d.ts +1 -0
- package/dist/engine/boot-validator/screens-actions.js +8 -1
- package/dist/engine/boot-validator/screens-dashboard.js +2 -5
- package/dist/engine/boot-validator/screens-forms.js +2 -6
- package/dist/engine/boot-validator/screens-kind-config-edit.d.ts +3 -0
- package/dist/engine/boot-validator/screens-kind-config-edit.js +88 -0
- package/dist/engine/boot-validator/screens-kind-entity-edit.d.ts +3 -0
- package/dist/engine/boot-validator/screens-kind-entity-edit.js +55 -0
- package/dist/engine/boot-validator/screens-kind-entity-list.d.ts +3 -0
- package/dist/engine/boot-validator/screens-kind-entity-list.js +228 -0
- package/dist/engine/boot-validator/screens-kind-projection-detail.d.ts +3 -0
- package/dist/engine/boot-validator/screens-kind-projection-detail.js +235 -0
- package/dist/engine/boot-validator/screens-kind-projection-list.d.ts +3 -0
- package/dist/engine/boot-validator/screens-kind-projection-list.js +52 -0
- package/dist/engine/boot-validator/screens-kind-secret-mint.d.ts +3 -0
- package/dist/engine/boot-validator/screens-kind-secret-mint.js +28 -0
- package/dist/engine/boot-validator/screens-kind-shared.d.ts +37 -0
- package/dist/engine/boot-validator/screens-kind-shared.js +142 -0
- package/dist/engine/boot-validator/screens-lists.d.ts +2 -1
- package/dist/engine/boot-validator/screens-lists.js +12 -9
- package/dist/engine/boot-validator/screens.d.ts +0 -2
- package/dist/engine/boot-validator/screens.js +99 -860
- package/dist/engine/build-app-schema.js +56 -96
- package/dist/engine/define-feature.js +9 -2
- package/dist/engine/define-handler.js +1 -0
- package/dist/engine/entity-handlers.d.ts +13 -0
- package/dist/engine/entity-handlers.js +10 -21
- package/dist/engine/entity-list-runtime-options.d.ts +8 -0
- package/dist/engine/entity-list-runtime-options.js +18 -0
- package/dist/engine/feature-ast/extractors/handlers.js +1 -0
- package/dist/engine/feature-ast/extractors/round2.js +25 -6
- package/dist/engine/feature-ast/patch.js +4 -182
- package/dist/engine/feature-ast/pattern-change-schema.d.ts +3 -0
- package/dist/engine/feature-ast/pattern-change-schema.js +1 -0
- package/dist/engine/feature-ast/pattern-id-matchers.d.ts +7 -0
- package/dist/engine/feature-ast/pattern-id-matchers.js +210 -0
- package/dist/engine/feature-ast/patterns.d.ts +9 -0
- package/dist/engine/feature-ast/patterns.js +43 -51
- package/dist/engine/feature-ast/render.js +48 -87
- package/dist/engine/feature-entity-handlers.js +3 -0
- package/dist/engine/form-derivations.js +18 -7
- package/dist/engine/handler-field-references.js +1 -1
- package/dist/engine/project-app-schema-for-roles.d.ts +2 -0
- package/dist/engine/project-app-schema-for-roles.js +6 -4
- package/dist/engine/registry-ingest.js +1 -1
- package/dist/engine/schema-builder.js +228 -212
- package/dist/engine/screen-helpers.js +1 -1
- package/dist/engine/screen-kind.d.ts +7 -0
- package/dist/engine/screen-kind.js +1 -0
- package/dist/engine/strip-disabled-features-from-app-schema.js +51 -14
- package/dist/engine/validate-projection-allowlist.js +2 -1
- package/dist/entrypoint/index.d.ts +4 -1
- package/dist/entrypoint/index.js +7 -1
- package/dist/errors/docs-url.d.ts +1 -1
- package/dist/errors/docs-url.js +22 -2
- package/dist/es-ops/context.js +1 -1
- package/dist/event-store/admin-api.js +1 -1
- package/dist/event-store/event-store.js +10 -4
- package/dist/files/bind-pending-file-refs.js +3 -3
- package/dist/files/create-file-ref-from-bytes.js +4 -1
- package/dist/files/file-handle.js +2 -3
- package/dist/files/file-routes.js +11 -8
- package/dist/files/resolve-content-type.js +43 -0
- package/dist/files/upload-ledger.js +7 -0
- package/dist/i18n/required-surface-keys.js +182 -206
- package/dist/internal/stack-support.d.ts +2 -1
- package/dist/internal/stack-support.js +1 -1
- package/dist/jobs/job-runner-context.d.ts +32 -0
- package/dist/jobs/job-runner-context.js +305 -0
- package/dist/jobs/job-runner-execution.d.ts +7 -0
- package/dist/jobs/job-runner-execution.js +160 -0
- package/dist/jobs/job-runner-gates.d.ts +19 -0
- package/dist/jobs/job-runner-gates.js +198 -0
- package/dist/jobs/job-runner-helpers.d.ts +17 -3
- package/dist/jobs/job-runner-helpers.js +61 -2
- package/dist/jobs/job-runner-scope.d.ts +44 -0
- package/dist/jobs/job-runner-scope.js +102 -0
- package/dist/jobs/job-runner-types.d.ts +12 -0
- package/dist/jobs/job-runner.d.ts +0 -1
- package/dist/jobs/job-runner.js +47 -657
- package/dist/observability/escape-hatch-report.d.ts +3 -0
- package/dist/observability/escape-hatch-report.js +12 -1
- package/dist/pipeline/cascade-handler.js +165 -138
- package/dist/pipeline/dispatch-query.js +10 -3
- package/dist/pipeline/dispatch-shared.d.ts +13 -3
- package/dist/pipeline/dispatch-shared.js +58 -710
- package/dist/pipeline/dispatch-write.js +296 -189
- package/dist/pipeline/event-dispatcher-admin.js +2 -1
- package/dist/pipeline/event-dispatcher-delivery.js +3 -5
- package/dist/pipeline/handler-context-auth.d.ts +9 -0
- package/dist/pipeline/handler-context-auth.js +54 -0
- package/dist/pipeline/handler-context-config.d.ts +14 -0
- package/dist/pipeline/handler-context-config.js +113 -0
- package/dist/pipeline/handler-context-db.d.ts +24 -0
- package/dist/pipeline/handler-context-db.js +149 -0
- package/dist/pipeline/handler-context-dispatch.d.ts +21 -0
- package/dist/pipeline/handler-context-dispatch.js +89 -0
- package/dist/pipeline/handler-context-events.d.ts +43 -0
- package/dist/pipeline/handler-context-events.js +237 -0
- package/dist/pipeline/handler-context-notify.d.ts +12 -0
- package/dist/pipeline/handler-context-notify.js +55 -0
- package/dist/pipeline/handler-context-observability.d.ts +7 -0
- package/dist/pipeline/handler-context-observability.js +21 -0
- package/dist/pipeline/handler-context-scope.d.ts +48 -0
- package/dist/pipeline/handler-context-scope.js +88 -0
- package/dist/pipeline/notify-scope.js +12 -1
- package/dist/pipeline/pre-handler-gates.js +20 -4
- package/dist/pipeline/pre-transaction-reservations.d.ts +1 -0
- package/dist/pipeline/pre-transaction-reservations.js +9 -3
- package/dist/pipeline/projection-rebuild.js +2 -1
- package/dist/schema-cli/apply-command.d.ts +2 -0
- package/dist/schema-cli/apply-command.js +97 -0
- package/dist/schema-cli/baseline-command.d.ts +2 -0
- package/dist/schema-cli/baseline-command.js +33 -0
- package/dist/schema-cli/generate-command.d.ts +2 -0
- package/dist/schema-cli/generate-command.js +90 -0
- package/dist/schema-cli/shared.d.ts +39 -0
- package/dist/schema-cli/shared.js +95 -0
- package/dist/schema-cli/status-command.d.ts +2 -0
- package/dist/schema-cli/status-command.js +73 -0
- package/dist/schema-cli/validate-boot-input.d.ts +5 -0
- package/dist/schema-cli/validate-boot-input.js +130 -0
- package/dist/schema-cli/validate-command.d.ts +2 -0
- package/dist/schema-cli/validate-command.js +130 -0
- package/dist/schema-cli.d.ts +2 -18
- package/dist/schema-cli.js +47 -604
- package/dist/search/meilisearch-adapter.js +2 -1
- package/dist/upgrade-cli.js +149 -121
- package/package.json +4 -4
- package/src/changes.json +310 -0
- package/src/scripts/codemod/feature-layout.ts +10 -2
- package/src/scripts/codemod/object-form.ts +41 -4
- package/src/scripts/codemod/package-merge.ts +58 -8
- package/src/scripts/codemod/pii-personal-migration.ts +175 -145
- package/src/scripts/codemod/testing-injection.ts +122 -42
- package/src/scripts/codemod/testing-move.ts +29 -7
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { resolveTenantLifecyclePlugin } from "../pipeline/active-membership.js";
|
|
2
|
+
import { authEndpointRateLimit, globalIpRateLimit } from "../rate-limit/index.js";
|
|
3
|
+
import { authMiddleware, getUser } from "./auth-middleware.js";
|
|
4
|
+
import { assertSessionCallbacksPaired } from "./auth-routes.js";
|
|
5
|
+
import { csrfMiddleware } from "./csrf-middleware.js";
|
|
6
|
+
import { observabilityMiddleware } from "./observability-middleware.js";
|
|
7
|
+
import { assertOriginGuardConfig, normalizeOrigin, resolveOriginGuard, } from "./origin-middleware.js";
|
|
8
|
+
import { patRouteGuard } from "./pat-route-guard.js";
|
|
9
|
+
import { piiCiphertextResponseGuard } from "./pii-leak-guard.js";
|
|
10
|
+
import { requestIdMiddleware } from "./request-id-middleware.js";
|
|
11
|
+
import { resolveSessionCookies, sessionCookiesMiddleware, } from "./session-cookies.js";
|
|
12
|
+
export function installSessionCookies(app, auth) {
|
|
13
|
+
// Resolved once; auth routes, auth/csrf middleware and the tenant-cookie
|
|
14
|
+
// helpers read the cookie names from the request context.
|
|
15
|
+
const sessionCookies = resolveSessionCookies({
|
|
16
|
+
secureCookies: auth?.secureCookies,
|
|
17
|
+
cookieDomain: auth?.cookieDomain,
|
|
18
|
+
retiredCookieDomains: auth?.retiredCookieDomains,
|
|
19
|
+
});
|
|
20
|
+
app.use("*", sessionCookiesMiddleware(sessionCookies));
|
|
21
|
+
return sessionCookies;
|
|
22
|
+
}
|
|
23
|
+
export function installRequestId(app, wiring) {
|
|
24
|
+
const { options, clientIpResolver } = wiring;
|
|
25
|
+
app.use("/api/*", requestIdMiddleware({
|
|
26
|
+
resolver: clientIpResolver,
|
|
27
|
+
...(options.errorDocs && { errorDocs: options.errorDocs }),
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
export function installRateLimitMiddleware(app, wiring) {
|
|
31
|
+
const { options, rateLimitResolver, clientIpResolver, observability } = wiring;
|
|
32
|
+
// L1/L2 rate-limit middleware run BEFORE auth so an unauthenticated
|
|
33
|
+
// flood can't even reach the JWT-verify code path. Wired only when
|
|
34
|
+
// the caller passed `rateLimit.global` or `rateLimit.auth`. The
|
|
35
|
+
// resolver is the auto-wired one (or `context.rateLimit` if set);
|
|
36
|
+
// boot-fails loudly when the caller asked for middleware without a
|
|
37
|
+
// working Redis to back it.
|
|
38
|
+
let globalRateLimitGuard;
|
|
39
|
+
if (wiring.rateLimitMiddlewareRequested) {
|
|
40
|
+
if (!rateLimitResolver) {
|
|
41
|
+
throw new Error("rateLimit middleware requested but no resolver available — pass `context.redis` " +
|
|
42
|
+
"or `context.rateLimit` so the resolver can be built.");
|
|
43
|
+
}
|
|
44
|
+
if (options.rateLimit?.global) {
|
|
45
|
+
globalRateLimitGuard = globalIpRateLimit({
|
|
46
|
+
...options.rateLimit.global,
|
|
47
|
+
resolver: rateLimitResolver,
|
|
48
|
+
clientIpResolver,
|
|
49
|
+
meter: observability.meter,
|
|
50
|
+
});
|
|
51
|
+
app.use("/api/*", globalRateLimitGuard);
|
|
52
|
+
}
|
|
53
|
+
if (options.rateLimit?.auth) {
|
|
54
|
+
const { path: l2Path = "/api/auth/*", ...l2Opts } = options.rateLimit.auth;
|
|
55
|
+
app.use(l2Path, authEndpointRateLimit({ ...l2Opts, resolver: rateLimitResolver, clientIpResolver }));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return globalRateLimitGuard;
|
|
59
|
+
}
|
|
60
|
+
export function installObservability(app, observability) {
|
|
61
|
+
// Observability span wraps everything that follows (auth, routes).
|
|
62
|
+
// Must come AFTER request-id (so span can carry the id) and BEFORE auth
|
|
63
|
+
// (so auth-verify can be a child span once we instrument it in v2).
|
|
64
|
+
app.use("/api/*", observabilityMiddleware({
|
|
65
|
+
tracer: observability.tracer,
|
|
66
|
+
meter: observability.meter,
|
|
67
|
+
}));
|
|
68
|
+
}
|
|
69
|
+
export function installPiiLeakGuard(app) {
|
|
70
|
+
// Tripwire: a kumiko-pii: ciphertext in a JSON response is always a bug
|
|
71
|
+
// (raw read leaked past a decrypt) — dev fails loud, prod redacts.
|
|
72
|
+
app.use("/api/*", piiCiphertextResponseGuard());
|
|
73
|
+
}
|
|
74
|
+
export function installAuthGuardChain(app, wiring, scope) {
|
|
75
|
+
const { options, jwt, baseDb } = wiring;
|
|
76
|
+
const { isPublicApiRequest, globalRateLimitGuard } = scope;
|
|
77
|
+
// Auth middleware skips public paths (login, health) — those routes need
|
|
78
|
+
// to be callable without a valid JWT. Every other /api/* request requires
|
|
79
|
+
// a token (or, when anonymousAccess is wired, falls through as anonymous).
|
|
80
|
+
// A session-checker is forwarded when the auth-config wires one, so the
|
|
81
|
+
// middleware can reject revoked sids on every request.
|
|
82
|
+
// Mounting a tenantLifecycleStatus provider is what turns the 410 on, so no
|
|
83
|
+
// entrypoint can forget the wiring; `??` short-circuits, so an explicit
|
|
84
|
+
// auth.resolveTenantLifecycleStatus remains the override.
|
|
85
|
+
const tenantLifecycleResolver = options.auth?.resolveTenantLifecycleStatus ??
|
|
86
|
+
deriveTenantLifecycleResolver(options.registry, baseDb);
|
|
87
|
+
// sessionOnlyGuard deliberately does NOT get this — its callers have no
|
|
88
|
+
// anonymousAccess fallback, so a foreign-origin cookie there must keep
|
|
89
|
+
// failing through the sibling originMiddleware 403.
|
|
90
|
+
const normalizedForeignCookieOrigins = options.auth?.allowedOrigins?.length
|
|
91
|
+
? new Set(options.auth.allowedOrigins.map(normalizeOrigin))
|
|
92
|
+
: undefined;
|
|
93
|
+
const jwtGuard = buildJwtGuard(options, jwt, tenantLifecycleResolver, normalizedForeignCookieOrigins);
|
|
94
|
+
useOnProtectedApiPaths(app, isPublicApiRequest, jwtGuard);
|
|
95
|
+
// Fail-closed PAT scoping: a PAT-authenticated caller (user.pat set by
|
|
96
|
+
// jwtGuard's tokenVerifier above) may only reach the dispatcher routes —
|
|
97
|
+
// everywhere else on /api/* is off-limits regardless of granted scopes.
|
|
98
|
+
const patRouteGuardMiddleware = patRouteGuard();
|
|
99
|
+
useOnProtectedApiPaths(app, isPublicApiRequest, patRouteGuardMiddleware);
|
|
100
|
+
// Without anonymousAccess a missing token 401s instead of falling through as anonymous.
|
|
101
|
+
const sessionOnlyGuard = buildSessionOnlyGuard(options, jwt, tenantLifecycleResolver);
|
|
102
|
+
// PAT rate limiting — runs AFTER the auth guard so the resolved principal is
|
|
103
|
+
// available. Only PAT-authenticated requests are counted (keyed by token id);
|
|
104
|
+
// cookie/JWT users pass through untouched. In-memory limiter is per-instance
|
|
105
|
+
// (see run-prod-app) — a multi-node deployment wanting a shared counter swaps
|
|
106
|
+
// in a Redis-backed LoginRateLimiter.
|
|
107
|
+
const patRateLimiter = options.auth?.patRateLimiter;
|
|
108
|
+
const patRateLimitGuard = patRateLimiter ? buildPatRateLimitGuard(patRateLimiter) : undefined;
|
|
109
|
+
if (patRateLimitGuard) {
|
|
110
|
+
useOnProtectedApiPaths(app, isPublicApiRequest, patRateLimitGuard);
|
|
111
|
+
}
|
|
112
|
+
// Origin-allowlist guard — additional CSRF-hardening for deployments that
|
|
113
|
+
// widen the auth cookie across subdomains (auth.cookieDomain). Registered
|
|
114
|
+
// when allowedOrigins is non-empty, or with host-only cookies when
|
|
115
|
+
// auth.publicOrigin is known (see resolveOriginGuard), with the same /api/* + public-skip
|
|
116
|
+
// scope as the CSRF guard and BEFORE it, so a disallowed cross-site POST
|
|
117
|
+
// surfaces as `origin_not_allowed` rather than `csrf_token_mismatch`. Fails
|
|
118
|
+
// closed (assertOriginGuardConfig throws) when a wide cookieDomain is set
|
|
119
|
+
// without an allowlist and without an explicit opt-out — that config is the
|
|
120
|
+
// unguarded-subdomain-XSS footgun, not a warn-and-continue case.
|
|
121
|
+
assertOriginGuardConfig(options.auth);
|
|
122
|
+
assertSessionCallbacksPaired(options.auth);
|
|
123
|
+
const originGuard = resolveOriginGuard(options.auth);
|
|
124
|
+
if (originGuard) {
|
|
125
|
+
useOnProtectedApiPaths(app, isPublicApiRequest, originGuard);
|
|
126
|
+
}
|
|
127
|
+
// Double-submit CSRF guard — runs only on cookie-authenticated,
|
|
128
|
+
// state-changing requests (POST/PUT/PATCH/DELETE). The guard reads the
|
|
129
|
+
// authTransport flag set by authMiddleware, so public paths (no auth)
|
|
130
|
+
// and bearer-authenticated paths (no cookie vector) fall straight
|
|
131
|
+
// through. Must be registered AFTER the auth middleware above so the
|
|
132
|
+
// flag is populated; registered for the same scope so /api/* routes
|
|
133
|
+
// are covered uniformly.
|
|
134
|
+
const csrfGuard = csrfMiddleware();
|
|
135
|
+
useOnProtectedApiPaths(app, isPublicApiRequest, csrfGuard);
|
|
136
|
+
// No PAT rate-limit here: patRouteGuardMiddleware rejects every PAT on httpRoutes before it could count.
|
|
137
|
+
// httpRoutes sit outside /api/*, so the pre-auth /api/* middlewares do not run for them: the
|
|
138
|
+
// global IP limit (an unauthenticated flood must not reach JWT verify / session checks) and the
|
|
139
|
+
// PII ciphertext tripwire are re-attached here. requestId, body limit and observability are not.
|
|
140
|
+
const sessionOnlyHttpRouteGuards = [
|
|
141
|
+
...(globalRateLimitGuard ? [globalRateLimitGuard] : []),
|
|
142
|
+
piiCiphertextResponseGuard(),
|
|
143
|
+
sessionOnlyGuard,
|
|
144
|
+
patRouteGuardMiddleware,
|
|
145
|
+
...(originGuard ? [originGuard] : []),
|
|
146
|
+
csrfGuard,
|
|
147
|
+
];
|
|
148
|
+
return { tenantLifecycleResolver, sessionOnlyHttpRouteGuards };
|
|
149
|
+
}
|
|
150
|
+
function useOnProtectedApiPaths(app, isPublicApiRequest, guard) {
|
|
151
|
+
app.use("/api/*", async (c, next) => {
|
|
152
|
+
if (isPublicApiRequest(c))
|
|
153
|
+
return next();
|
|
154
|
+
return guard(c, next);
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
function collectTenantlessAnonymousWriteQns(registry) {
|
|
158
|
+
return new Set([...registry.getAllWriteHandlers()]
|
|
159
|
+
.filter(([, handler]) => handler.tenantlessAnonymous === true)
|
|
160
|
+
.map(([qn]) => qn));
|
|
161
|
+
}
|
|
162
|
+
function buildJwtGuard(options, jwt, tenantLifecycleResolver, normalizedForeignCookieOrigins) {
|
|
163
|
+
const tenantlessAnonymousQns = collectTenantlessAnonymousWriteQns(options.registry);
|
|
164
|
+
return authMiddleware(jwt, {
|
|
165
|
+
...(tenantlessAnonymousQns.size > 0
|
|
166
|
+
? { isTenantlessAnonymousWrite: (qn) => tenantlessAnonymousQns.has(qn) }
|
|
167
|
+
: {}),
|
|
168
|
+
...(options.auth?.sessionChecker ? { sessionChecker: options.auth.sessionChecker } : {}),
|
|
169
|
+
...(options.auth?.tokenVerifier ? { tokenVerifier: options.auth.tokenVerifier } : {}),
|
|
170
|
+
...(tenantLifecycleResolver ? { resolveTenantLifecycleStatus: tenantLifecycleResolver } : {}),
|
|
171
|
+
...(options.anonymousAccess ? { anonymousAccess: options.anonymousAccess } : {}),
|
|
172
|
+
...(normalizedForeignCookieOrigins
|
|
173
|
+
? { foreignCookieOrigins: normalizedForeignCookieOrigins }
|
|
174
|
+
: {}),
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
function buildSessionOnlyGuard(options, jwt, tenantLifecycleResolver) {
|
|
178
|
+
return authMiddleware(jwt, {
|
|
179
|
+
...(options.auth?.sessionChecker ? { sessionChecker: options.auth.sessionChecker } : {}),
|
|
180
|
+
...(options.auth?.tokenVerifier ? { tokenVerifier: options.auth.tokenVerifier } : {}),
|
|
181
|
+
...(tenantLifecycleResolver ? { resolveTenantLifecycleStatus: tenantLifecycleResolver } : {}),
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
// Must run after the auth guard so getUser(c) carries the PAT.
|
|
185
|
+
function buildPatRateLimitGuard(patRateLimiter) {
|
|
186
|
+
return async (c, next) => {
|
|
187
|
+
const pat = getUser(c)?.pat;
|
|
188
|
+
if (pat && !(await patRateLimiter.check(pat.tokenId))) {
|
|
189
|
+
return c.json({
|
|
190
|
+
error: {
|
|
191
|
+
code: "pat_rate_limited",
|
|
192
|
+
httpStatus: 429,
|
|
193
|
+
message: "personal access token rate limit exceeded",
|
|
194
|
+
i18nKey: "auth.errors.patRateLimited",
|
|
195
|
+
},
|
|
196
|
+
}, 429);
|
|
197
|
+
}
|
|
198
|
+
return next();
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
function deriveTenantLifecycleResolver(registry, db) {
|
|
202
|
+
const plugin = resolveTenantLifecyclePlugin(registry, "buildServer");
|
|
203
|
+
if (!plugin)
|
|
204
|
+
return undefined;
|
|
205
|
+
if (!db) {
|
|
206
|
+
throw new Error("[kumiko] a tenantLifecycleStatus provider is mounted (tenant-lifecycle) but context.db is " +
|
|
207
|
+
"missing — the request-level teardown gate needs a DbConnection. Pass context.db, or wire " +
|
|
208
|
+
"auth.resolveTenantLifecycleStatus explicitly.");
|
|
209
|
+
}
|
|
210
|
+
return (tenantId) => plugin.resolveStatus(tenantId, { db });
|
|
211
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Hono, MiddlewareHandler } from "hono";
|
|
2
|
+
import type { HttpRouteMethod, SessionUser, TenantId } from "../engine/types/index.ts";
|
|
3
|
+
import type { Dispatcher } from "../pipeline/dispatcher.ts";
|
|
4
|
+
import { type ClientIpResolver } from "./client-ip.ts";
|
|
5
|
+
import type { ServerOptions } from "./server.ts";
|
|
6
|
+
import type { ServerWiring } from "./server-wiring.ts";
|
|
7
|
+
import type { ResolvedSessionCookies } from "./session-cookies.ts";
|
|
8
|
+
export declare function mountOperationalRoutes(app: Hono, wiring: Pick<ServerWiring, "options" | "baseDb" | "eventConsumers" | "observability" | "bootLog">): void;
|
|
9
|
+
export declare function mountAuthRoutes(app: Hono, wiring: Pick<ServerWiring, "options" | "dispatcher" | "jwt" | "clientIpResolver">, sessionCookies: ResolvedSessionCookies): void;
|
|
10
|
+
export declare function mountClientErrorRoute(app: Hono, wiring: Pick<ServerWiring, "rateLimitResolver" | "tracedRedis" | "clientIpResolver" | "observability" | "jwt">): void;
|
|
11
|
+
export declare function mountDispatcherRoutes(app: Hono, wiring: Pick<ServerWiring, "options" | "dispatcher" | "sseBroker">): void;
|
|
12
|
+
export declare function mountSchemaRoute(app: Hono, options: Pick<ServerOptions, "registry" | "dispatcherOptions" | "context">): void;
|
|
13
|
+
export declare function mountFileRoutes(app: Hono, wiring: Pick<ServerWiring, "options" | "dispatcher" | "fileProviderResolver">): void;
|
|
14
|
+
export declare function mountFeatureHttpRoutes(app: Hono, wiring: Pick<ServerWiring, "options" | "dispatcher" | "clientIpResolver" | "rateLimitResolver" | "observability">, sessionOnlyHttpRouteGuards: readonly MiddlewareHandler[]): void;
|
|
15
|
+
export declare function installNoRouteMatchMarker(app: Hono): void;
|
|
16
|
+
export declare function mountHonoRoute(app: Hono, method: HttpRouteMethod, path: string, handler: (c: import("hono").Context<any, any>) => Response | Promise<Response>, middlewares?: readonly MiddlewareHandler[]): void;
|
|
17
|
+
export declare function makeSystemQuery(c: import("hono").Context<any, any>, dispatcher: Dispatcher, clientIpResolver?: ClientIpResolver): (type: string, payload: unknown, tenantId: TenantId) => Promise<unknown>;
|
|
18
|
+
export declare function isMissingOrAnonymousUser(user: SessionUser | undefined): boolean;
|
|
19
|
+
export declare function unauthenticatedResponse(c: import("hono").Context): Response;
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { createProjectingTenantDb } from "../db/tenant-db.js";
|
|
2
|
+
import { buildAppSchema } from "../engine/build-app-schema.js";
|
|
3
|
+
import { projectAppSchemaForRoles } from "../engine/project-app-schema-for-roles.js";
|
|
4
|
+
import { resolveDisabledFeatureNames, stripDisabledFeaturesFromAppSchema, } from "../engine/strip-disabled-features-from-app-schema.js";
|
|
5
|
+
import { createAnonymousUser, isAnonymousSessionUser } from "../engine/system-user.js";
|
|
6
|
+
import { createFileRoutes, readFilesRouteOptions } from "../files/file-routes.js";
|
|
7
|
+
import { createRecordReadCheck } from "../files/record-read-check.js";
|
|
8
|
+
import { createRecordWriteCheck } from "../files/record-write-check.js";
|
|
9
|
+
import { createRateLimitResolver, httpRouteRateLimit } from "../rate-limit/index.js";
|
|
10
|
+
import { assertUnreachable } from "../utils/index.js";
|
|
11
|
+
import { collectAnonymousLiveEntities } from "./anonymous-live-entities.js";
|
|
12
|
+
import { NO_ROUTE_MATCH_HEADER_NAME, Routes } from "./api-constants.js";
|
|
13
|
+
import { getUser, identifyOptionalSession } from "./auth-middleware.js";
|
|
14
|
+
import { createAuthRoutes } from "./auth-routes.js";
|
|
15
|
+
import { createClientErrorRoute } from "./client-error-route.js";
|
|
16
|
+
import { clientIpSourceFromHonoContext } from "./client-ip.js";
|
|
17
|
+
import { collectEntityReadAccess } from "./entity-read-access.js";
|
|
18
|
+
import { computeStrongEtag, etagMatches } from "./http-cache.js";
|
|
19
|
+
import { requestContext } from "./request-context.js";
|
|
20
|
+
import { buildRequestContextData } from "./request-id-middleware.js";
|
|
21
|
+
import { registerHealthRoutes, registerMetricsRoute } from "./route-registrars.js";
|
|
22
|
+
import { createApiRoutes } from "./routes.js";
|
|
23
|
+
import { assertSinglePrincipalStatusProvider } from "./server-boot-checks.js";
|
|
24
|
+
import { createSseRoute } from "./sse-route.js";
|
|
25
|
+
export function mountOperationalRoutes(app, wiring) {
|
|
26
|
+
const { options, baseDb, eventConsumers, observability, bootLog } = wiring;
|
|
27
|
+
registerHealthRoutes(app, {
|
|
28
|
+
lifecycle: options.lifecycle,
|
|
29
|
+
readiness: {
|
|
30
|
+
db: baseDb,
|
|
31
|
+
redis: options.context.redis,
|
|
32
|
+
consumers: eventConsumers,
|
|
33
|
+
...(options.readiness ?? {}),
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
if (options.metrics) {
|
|
37
|
+
registerMetricsRoute(app, observability.meter, options.metrics);
|
|
38
|
+
}
|
|
39
|
+
else if (process.env["NODE_ENV"] === "production") {
|
|
40
|
+
bootLog.warn("/metrics is off: no `metrics` option, so nothing is measured or scraped. " +
|
|
41
|
+
"Set PROMETHEUS_METRICS_TOKEN (min 32 chars) and spread resolveObservabilityWiring(token) into the server options.");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export function mountAuthRoutes(app, wiring, sessionCookies) {
|
|
45
|
+
const { options, dispatcher, jwt, clientIpResolver } = wiring;
|
|
46
|
+
if (options.auth) {
|
|
47
|
+
assertSinglePrincipalStatusProvider(options.registry, options.auth);
|
|
48
|
+
app.route("/api", createAuthRoutes(dispatcher, jwt, {
|
|
49
|
+
...options.auth,
|
|
50
|
+
secureCookies: sessionCookies.secure,
|
|
51
|
+
resolver: clientIpResolver,
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export function mountClientErrorRoute(app, wiring) {
|
|
56
|
+
const { rateLimitResolver, tracedRedis, clientIpResolver, observability, jwt } = wiring;
|
|
57
|
+
app.route("/api", createClientErrorRoute({
|
|
58
|
+
resolver: rateLimitResolver ??
|
|
59
|
+
(tracedRedis ? createRateLimitResolver({ redis: tracedRedis }) : undefined),
|
|
60
|
+
clientIpResolver,
|
|
61
|
+
meter: observability.meter,
|
|
62
|
+
identifySession: (c) => identifyOptionalSession(c, jwt),
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
export function mountDispatcherRoutes(app, wiring) {
|
|
66
|
+
const { options, dispatcher, sseBroker } = wiring;
|
|
67
|
+
app.route("/api", createApiRoutes(dispatcher, {
|
|
68
|
+
...(options.sseHeartbeatMs !== undefined ? { sseHeartbeatMs: options.sseHeartbeatMs } : {}),
|
|
69
|
+
}));
|
|
70
|
+
app.route("/api", createSseRoute(sseBroker, {
|
|
71
|
+
anonymousLiveEntities: collectAnonymousLiveEntities(options.registry),
|
|
72
|
+
entityReadAccess: collectEntityReadAccess(options.registry),
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
75
|
+
export function mountSchemaRoute(app, options) {
|
|
76
|
+
// GET /api/schema — the only way a client obtains the AppSchema. Behind
|
|
77
|
+
// jwtGuard (NON_PUBLIC_API_PATHS), so anonymousAccess's synthesised user
|
|
78
|
+
// also gets rejected below — the schema never reaches an unauthenticated
|
|
79
|
+
// caller. The FULL schema is built lazily once — the registry is
|
|
80
|
+
// immutable for this server's lifetime, so it's the same on every
|
|
81
|
+
// request — then projected per caller-role-set (a role only
|
|
82
|
+
// sees the screens/navs/workspaces/content-collections it may reach,
|
|
83
|
+
// not the whole app's schema) and cached per role key. Tenant is
|
|
84
|
+
// deliberately NOT part of the key: the projection depends only on
|
|
85
|
+
// roles, and per-tenant caching would grow unboundedly across tenants
|
|
86
|
+
// that share the same role set. What IS part of the key: the sorted set of
|
|
87
|
+
// features the caller's tenant has switched off (r.toggleable) — few
|
|
88
|
+
// distinct sets, so the cache stays small. The resolver is read per request
|
|
89
|
+
// because run{Dev,Prod}App fill it in after the server is built.
|
|
90
|
+
let fullSchema;
|
|
91
|
+
const projectedSchemaCache = new Map();
|
|
92
|
+
app.get(`/api${Routes.schema}`, async (c) => {
|
|
93
|
+
const user = getUser(c);
|
|
94
|
+
if (isMissingOrAnonymousUser(user)) {
|
|
95
|
+
return unauthenticatedResponse(c);
|
|
96
|
+
}
|
|
97
|
+
const effectiveFeatures = options.dispatcherOptions?.effectiveFeatures;
|
|
98
|
+
const disabledFeatureNames = effectiveFeatures === undefined
|
|
99
|
+
? []
|
|
100
|
+
: await resolveDisabledFeatureNames(options.registry, effectiveFeatures, user.tenantId);
|
|
101
|
+
const roleKey = JSON.stringify([[...new Set(user?.roles ?? [])].sort(), disabledFeatureNames]);
|
|
102
|
+
let cached = projectedSchemaCache.get(roleKey);
|
|
103
|
+
if (cached === undefined) {
|
|
104
|
+
if (fullSchema === undefined) {
|
|
105
|
+
fullSchema = buildAppSchema(options.registry, {
|
|
106
|
+
searchAdapterMissing: !options.context.searchAdapter,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
const projected = projectAppSchemaForRoles(stripDisabledFeaturesFromAppSchema(fullSchema, options.registry, disabledFeatureNames), user?.roles ?? []);
|
|
110
|
+
const json = JSON.stringify(projected);
|
|
111
|
+
cached = { json, etag: computeStrongEtag(json) };
|
|
112
|
+
projectedSchemaCache.set(roleKey, cached);
|
|
113
|
+
}
|
|
114
|
+
const cacheHeaders = { "Cache-Control": "private, no-cache", ETag: cached.etag };
|
|
115
|
+
if (etagMatches(c.req.header("If-None-Match") ?? null, cached.etag)) {
|
|
116
|
+
return c.body(null, 304, cacheHeaders);
|
|
117
|
+
}
|
|
118
|
+
return c.body(cached.json, 200, {
|
|
119
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
120
|
+
...cacheHeaders,
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
export function mountFileRoutes(app, wiring) {
|
|
125
|
+
const { options, dispatcher, fileProviderResolver } = wiring;
|
|
126
|
+
// Mount upload/download routes whenever a file provider is resolvable (a
|
|
127
|
+
// file-provider plugin is mounted, or a resolver was injected). They resolve
|
|
128
|
+
// the provider per-tenant through file-foundation — no `files` option; route
|
|
129
|
+
// policy comes from createFilesFeature(opts?). Gating on the resolver (not on
|
|
130
|
+
// declared file fields) keeps unattached uploads working and matches the old
|
|
131
|
+
// "files option present → routes" behavior.
|
|
132
|
+
if (fileProviderResolver) {
|
|
133
|
+
const fileDb = options.context.db; // @cast-boundary engine-bridge
|
|
134
|
+
if (!fileDb)
|
|
135
|
+
throw new Error("file routes require db in context");
|
|
136
|
+
const routeOptions = readFilesRouteOptions(options.registry);
|
|
137
|
+
const canReadRecord = createRecordReadCheck(options.registry, dispatcher.query);
|
|
138
|
+
app.route("/api", createFileRoutes({
|
|
139
|
+
db: fileDb,
|
|
140
|
+
registry: options.registry,
|
|
141
|
+
resolveProvider: fileProviderResolver,
|
|
142
|
+
canReadRecord,
|
|
143
|
+
canWriteRecord: createRecordWriteCheck({
|
|
144
|
+
registry: options.registry,
|
|
145
|
+
canReadRecord,
|
|
146
|
+
tenantDbFor: (tenantId) => createProjectingTenantDb(fileDb, tenantId, options.registry),
|
|
147
|
+
}),
|
|
148
|
+
...(routeOptions.accessGuard ? { accessGuard: routeOptions.accessGuard } : {}),
|
|
149
|
+
...(routeOptions.privilegedRoles ? { privilegedRoles: routeOptions.privilegedRoles } : {}),
|
|
150
|
+
...(routeOptions.unclaimedUploadReaders
|
|
151
|
+
? { unclaimedUploadReaders: routeOptions.unclaimedUploadReaders }
|
|
152
|
+
: {}),
|
|
153
|
+
...(routeOptions.maxUploadSize ? { maxUploadSize: routeOptions.maxUploadSize } : {}),
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
export function mountFeatureHttpRoutes(app, wiring, sessionOnlyHttpRouteGuards) {
|
|
158
|
+
// Feature-declared HTTP routes (r.httpRoute). Mount after /api/* so /api/* always
|
|
159
|
+
// takes precedence; feature routes must be outside that prefix (the boot validator
|
|
160
|
+
// enforces this). deps.app is the outer app, so the handler can call /api/query
|
|
161
|
+
// internally through app.fetch(...) and use the same auth path as a real HTTP call.
|
|
162
|
+
// deps.systemQuery deliberately bypasses that path for routes that must enforce a
|
|
163
|
+
// FIXED tenant (for example, legal-pages always uses SYSTEM_TENANT_ID), rather than
|
|
164
|
+
// spoofing it through the X-Tenant header. That header looks like a normal client
|
|
165
|
+
// header to anonymousAccess resolution, so resolverTrust: "authoritative" configs
|
|
166
|
+
// correctly reject it as a tenant override.
|
|
167
|
+
for (const feature of wiring.options.registry.features.values()) {
|
|
168
|
+
for (const route of Object.values(feature.httpRoutes)) {
|
|
169
|
+
mountFeatureHttpRoute(app, route, wiring, sessionOnlyHttpRouteGuards);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function mountFeatureHttpRoute(app, route, wiring, sessionOnlyHttpRouteGuards) {
|
|
174
|
+
const { dispatcher, clientIpResolver, rateLimitResolver, observability } = wiring;
|
|
175
|
+
// @wrapper-known semantic-alias
|
|
176
|
+
const honoHandler = async (c) => route.handler(c, {
|
|
177
|
+
app,
|
|
178
|
+
// createAnonymousUser, NOT createSystemUser: systemQuery's
|
|
179
|
+
// synthesized user must clear the SAME access gate a real
|
|
180
|
+
// anonymous visitor would, no more — regardless of the route's
|
|
181
|
+
// own `anonymous` mode. The system role would ALSO satisfy that
|
|
182
|
+
// gate here, but it can read fields gated to "system" that
|
|
183
|
+
// "anonymous" can't (filterReadFields is a plain role-in-map
|
|
184
|
+
// check) — a systemQuery caller reading a system-gated field
|
|
185
|
+
// would leak it into the response. The forced tenant already
|
|
186
|
+
// comes from bypassing the HTTP layer entirely; no elevated
|
|
187
|
+
// role is needed or wanted on top of that.
|
|
188
|
+
systemQuery: makeSystemQuery(c, dispatcher, clientIpResolver),
|
|
189
|
+
clientIp: clientIpResolver.resolve(clientIpSourceFromHonoContext(c)),
|
|
190
|
+
});
|
|
191
|
+
// Without a resolver (no Redis in the context — dev/test stacks) the
|
|
192
|
+
// declared limit is skipped rather than failing the boot of every app
|
|
193
|
+
// that mounts a bundled feature whose routes carry a default limit.
|
|
194
|
+
const routeLimit = route.rateLimit && rateLimitResolver
|
|
195
|
+
? [
|
|
196
|
+
httpRouteRateLimit({
|
|
197
|
+
resolver: rateLimitResolver,
|
|
198
|
+
rateLimit: route.rateLimit,
|
|
199
|
+
routeKey: `${route.method} ${route.path}`,
|
|
200
|
+
clientIpResolver,
|
|
201
|
+
meter: observability.meter,
|
|
202
|
+
}),
|
|
203
|
+
]
|
|
204
|
+
: [];
|
|
205
|
+
mountHonoRoute(app, route.method, route.path, honoHandler, [
|
|
206
|
+
...routeLimit,
|
|
207
|
+
...(route.anonymous ? [] : sessionOnlyHttpRouteGuards),
|
|
208
|
+
]);
|
|
209
|
+
}
|
|
210
|
+
export function installNoRouteMatchMarker(app) {
|
|
211
|
+
// Marks "no route matched this path" so tryHonoFirst (server-runtime)
|
|
212
|
+
// can tell it apart from a matched route's OWN deliberate 404 (e.g.
|
|
213
|
+
// default-deny reads like file-derivatives' public-variant route) —
|
|
214
|
+
// without this, tryHonoFirst's only signal was the status code, and a
|
|
215
|
+
// matched route answering 404 got silently rewritten to the SPA shell
|
|
216
|
+
// with status 200. Must be the LAST thing wired
|
|
217
|
+
// on `app`: this only fires when the router found no handler at all, so
|
|
218
|
+
// a route's own `c.text(..., 404)` never passes through here. A handler
|
|
219
|
+
// that calls `c.notFound()` instead of building its own Response DOES
|
|
220
|
+
// route through this same handler and stays indistinguishable from a
|
|
221
|
+
// routing miss — pre-existing Hono semantics, not something this fix
|
|
222
|
+
// changes; deliberate 404s must build their own Response.
|
|
223
|
+
// The header is an internal signal only — tryHonoFirst and every direct
|
|
224
|
+
// app.fetch() passthrough strip it before a response reaches a client.
|
|
225
|
+
app.notFound((c) => c.text("Not Found", 404, { [NO_ROUTE_MATCH_HEADER_NAME]: "1" }));
|
|
226
|
+
}
|
|
227
|
+
// Method-switch shared by r.httpRoute and extraRoutes — one place to keep
|
|
228
|
+
// the two mounting paths from drifting on which Hono methods get a
|
|
229
|
+
// convenience-call vs. app.on().
|
|
230
|
+
export function mountHonoRoute(app, method, path,
|
|
231
|
+
// biome-ignore lint/suspicious/noExplicitAny: Hono context generics are invisible at the framework boundary
|
|
232
|
+
handler, middlewares = []) {
|
|
233
|
+
// Guards go into the route's own handler chain, never a method-gated
|
|
234
|
+
// app.use: Hono serves HEAD through the GET route with c.req.method still
|
|
235
|
+
// "HEAD", so a `method === c.req.method` gate would skip them for HEAD.
|
|
236
|
+
if (middlewares.length > 0) {
|
|
237
|
+
// [path]: only Hono's array-path overload accepts a variable-length handler spread.
|
|
238
|
+
app.on(method, [path], ...middlewares, handler);
|
|
239
|
+
// skip: guarded route already mounted with its guard chain
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
switch (method) {
|
|
243
|
+
case "GET":
|
|
244
|
+
app.get(path, handler);
|
|
245
|
+
break;
|
|
246
|
+
case "POST":
|
|
247
|
+
app.post(path, handler);
|
|
248
|
+
break;
|
|
249
|
+
case "PUT":
|
|
250
|
+
app.put(path, handler);
|
|
251
|
+
break;
|
|
252
|
+
case "PATCH":
|
|
253
|
+
app.patch(path, handler);
|
|
254
|
+
break;
|
|
255
|
+
case "DELETE":
|
|
256
|
+
app.delete(path, handler);
|
|
257
|
+
break;
|
|
258
|
+
case "OPTIONS":
|
|
259
|
+
case "HEAD":
|
|
260
|
+
// Hono's on() for the methods without a convenience method.
|
|
261
|
+
app.on(method, path, handler);
|
|
262
|
+
break;
|
|
263
|
+
default:
|
|
264
|
+
assertUnreachable(method, "http method");
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
// Shared systemQuery builder for r.httpRoute and extraRoutes (anonymous +
|
|
268
|
+
// signature entries). requestContext.run must wrap the dispatcher call —
|
|
269
|
+
// both route kinds run outside the requestIdMiddleware chain that normally
|
|
270
|
+
// populates it, and `rateLimit: {per: "ip", ...}` on a handler invoked
|
|
271
|
+
// through systemQuery is otherwise silent dead-code (enforceRateLimit reads
|
|
272
|
+
// requestContext.get()?.ip, undefined without this wrap).
|
|
273
|
+
export function makeSystemQuery(
|
|
274
|
+
// biome-ignore lint/suspicious/noExplicitAny: Hono context generics are invisible at the framework boundary
|
|
275
|
+
c, dispatcher, clientIpResolver) {
|
|
276
|
+
return (type, payload, tenantId) => requestContext.run(requestContext.get() ?? buildRequestContextData(c, clientIpResolver), () => dispatcher.query(type, payload, createAnonymousUser(tenantId)));
|
|
277
|
+
}
|
|
278
|
+
// Shared by entry:"user" extra routes and GET /api/schema — both require a
|
|
279
|
+
// real, signed-in principal and reject the synthesised anonymousAccess user
|
|
280
|
+
// (SessionUser.roles includes ANONYMOUS_ROLE) the same way.
|
|
281
|
+
export function isMissingOrAnonymousUser(user) {
|
|
282
|
+
return !user || isAnonymousSessionUser(user);
|
|
283
|
+
}
|
|
284
|
+
export function unauthenticatedResponse(c) {
|
|
285
|
+
return c.json({
|
|
286
|
+
error: {
|
|
287
|
+
code: "unauthenticated",
|
|
288
|
+
httpStatus: 401,
|
|
289
|
+
message: "this route requires a signed-in user",
|
|
290
|
+
i18nKey: "auth.errors.missingToken",
|
|
291
|
+
},
|
|
292
|
+
}, 401);
|
|
293
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Hono } from "hono";
|
|
2
|
+
import { type TenantLifecycleStatusResolver } from "./auth-middleware.ts";
|
|
3
|
+
import type { ServerWiring } from "./server-wiring.ts";
|
|
4
|
+
export declare function mountWebSocketRoutes(app: Hono, wiring: Pick<ServerWiring, "options" | "dispatcher" | "clientIpResolver">, tenantLifecycleResolver: TenantLifecycleStatusResolver | undefined): void;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { createFallbackLogger } from "../logging/index.js";
|
|
2
|
+
import { getAuthTokenExpiry, getUser, } from "./auth-middleware.js";
|
|
3
|
+
import { clientIpSourceFromHonoContext } from "./client-ip.js";
|
|
4
|
+
import { isWebSocketOriginAllowed, normalizeOrigin, rejectOrigin } from "./origin-middleware.js";
|
|
5
|
+
import { requestContext } from "./request-context.js";
|
|
6
|
+
import { isMissingOrAnonymousUser, unauthenticatedResponse } from "./server-routes.js";
|
|
7
|
+
import { buildWebSocketSessionRevalidator, createWebSocketConnectionLimiter, hasWebSocketUpgradeServer, isWebSocketUpgradeRequest, WEBSOCKET_DEFAULT_MAX_CONNECTIONS_PER_USER, WEBSOCKET_DEFAULT_MAX_MESSAGE_BYTES, } from "./websocket-route.js";
|
|
8
|
+
export function mountWebSocketRoutes(app, wiring, tenantLifecycleResolver) {
|
|
9
|
+
const { options, dispatcher, clientIpResolver } = wiring;
|
|
10
|
+
// r.webSocketRoute — GET routes under /api/ws/*, so the jwt/pat/rate-limit
|
|
11
|
+
// chain above already ran. Origin/CSRF guards skip GETs, hence the own check.
|
|
12
|
+
const webSocketOriginAllowlist = options.auth?.allowedOrigins?.length
|
|
13
|
+
? new Set(options.auth.allowedOrigins.map(normalizeOrigin))
|
|
14
|
+
: undefined;
|
|
15
|
+
const webSocketRoutePaths = new Map();
|
|
16
|
+
const webSocketConnectionLimiter = createWebSocketConnectionLimiter();
|
|
17
|
+
for (const feature of options.registry.features.values()) {
|
|
18
|
+
for (const route of Object.values(feature.webSocketRoutes)) {
|
|
19
|
+
const owner = webSocketRoutePaths.get(route.path);
|
|
20
|
+
if (owner !== undefined) {
|
|
21
|
+
throw new Error(`[kumiko] WebSocket route "${route.path}" is declared by both feature "${owner}" and ` +
|
|
22
|
+
`"${feature.name}" — paths must be unique across features.`);
|
|
23
|
+
}
|
|
24
|
+
webSocketRoutePaths.set(route.path, feature.name);
|
|
25
|
+
app.get(route.path, buildWebSocketRouteHandler(route, {
|
|
26
|
+
dispatcher,
|
|
27
|
+
clientIpResolver,
|
|
28
|
+
originAllowlist: webSocketOriginAllowlist,
|
|
29
|
+
...(options.auth?.sessionChecker ? { sessionChecker: options.auth.sessionChecker } : {}),
|
|
30
|
+
...(tenantLifecycleResolver
|
|
31
|
+
? { resolveTenantLifecycleStatus: tenantLifecycleResolver }
|
|
32
|
+
: {}),
|
|
33
|
+
connectionLimiter: webSocketConnectionLimiter,
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const webSocketLog = createFallbackLogger("websocket");
|
|
39
|
+
function webSocketErrorResponse(c, status, code, message) {
|
|
40
|
+
return c.json({ error: { code, httpStatus: status, message } }, status);
|
|
41
|
+
}
|
|
42
|
+
function buildWebSocketRouteHandler(route, shared) {
|
|
43
|
+
return async (c) => {
|
|
44
|
+
if (!isWebSocketOriginAllowed(c, shared.originAllowlist))
|
|
45
|
+
return rejectOrigin(c);
|
|
46
|
+
const user = getUser(c);
|
|
47
|
+
if (isMissingOrAnonymousUser(user))
|
|
48
|
+
return unauthenticatedResponse(c);
|
|
49
|
+
if (!isWebSocketUpgradeRequest(c.req.raw)) {
|
|
50
|
+
return webSocketErrorResponse(c, 426, "websocket_upgrade_required", "this route only accepts WebSocket upgrade requests");
|
|
51
|
+
}
|
|
52
|
+
const honoEnv = c.env;
|
|
53
|
+
if (!hasWebSocketUpgradeServer(honoEnv)) {
|
|
54
|
+
const message = "webSocketUpgradeFetch not wired: pass it to buildBunServeOptions";
|
|
55
|
+
webSocketLog.error(message, { path: route.path });
|
|
56
|
+
return webSocketErrorResponse(c, 501, "websocket_upgrade_not_wired", message);
|
|
57
|
+
}
|
|
58
|
+
// The slot is taken before connect (a refused attempt must not run it) and stays synchronous with
|
|
59
|
+
// the check, so concurrent upgrades can't overshoot the cap. Every path without a live socket frees it.
|
|
60
|
+
const releaseConnectionSlot = shared.connectionLimiter.tryAcquire(`${route.path}\n${user.tenantId}\n${user.id}`, route.maxConnectionsPerUser ?? WEBSOCKET_DEFAULT_MAX_CONNECTIONS_PER_USER);
|
|
61
|
+
if (!releaseConnectionSlot) {
|
|
62
|
+
return webSocketErrorResponse(c, 429, "websocket_connection_limit", "too many open WebSocket connections for this user");
|
|
63
|
+
}
|
|
64
|
+
let upgraded = false;
|
|
65
|
+
try {
|
|
66
|
+
const handlers = await route.connect(c, {
|
|
67
|
+
user,
|
|
68
|
+
query: (type, payload) => shared.dispatcher.query(type, payload, user),
|
|
69
|
+
write: (type, payload) => shared.dispatcher.write(type, payload, user),
|
|
70
|
+
clientIp: shared.clientIpResolver.resolve(clientIpSourceFromHonoContext(c)),
|
|
71
|
+
});
|
|
72
|
+
if (handlers instanceof Response)
|
|
73
|
+
return handlers;
|
|
74
|
+
const captured = requestContext.get();
|
|
75
|
+
const requestContextData = captured ? withoutAbortSignal(captured) : undefined;
|
|
76
|
+
const revalidateSession = buildWebSocketSessionRevalidator({
|
|
77
|
+
user,
|
|
78
|
+
sessionChecker: shared.sessionChecker,
|
|
79
|
+
resolveTenantLifecycleStatus: shared.resolveTenantLifecycleStatus,
|
|
80
|
+
tokenExpiresAtSec: getAuthTokenExpiry(c),
|
|
81
|
+
});
|
|
82
|
+
upgraded = honoEnv.server.upgrade(c.req.raw, {
|
|
83
|
+
data: {
|
|
84
|
+
handlers,
|
|
85
|
+
maxMessageBytes: route.maxMessageBytes ?? WEBSOCKET_DEFAULT_MAX_MESSAGE_BYTES,
|
|
86
|
+
requestContextData,
|
|
87
|
+
revalidateSession,
|
|
88
|
+
releaseConnectionSlot,
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
if (!upgraded) {
|
|
92
|
+
return webSocketErrorResponse(c, 400, "websocket_upgrade_failed", "the WebSocket upgrade was rejected");
|
|
93
|
+
}
|
|
94
|
+
// Bun ignores the returned Response after a successful upgrade.
|
|
95
|
+
return new Response(null);
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
if (!upgraded)
|
|
99
|
+
releaseConnectionSlot();
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
// The request's AbortSignal fires when the upgrade request ends, which would
|
|
104
|
+
// abort every later handler running under the captured context.
|
|
105
|
+
function withoutAbortSignal(data) {
|
|
106
|
+
const { signal: _signal, ...rest } = data;
|
|
107
|
+
return rest;
|
|
108
|
+
}
|