@cosmicdrift/kumiko-dev-server 0.151.1 → 0.153.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 (48) hide show
  1. package/package.json +5 -8
  2. package/src/__tests__/build-prod-bundle.integration.test.ts +1 -1
  3. package/src/__tests__/compose-stacks.test.ts +1 -1
  4. package/src/__tests__/discover-format.test.ts +1 -1
  5. package/src/__tests__/env-schema.integration.test.ts +1 -1
  6. package/src/__tests__/walkthrough.integration.test.ts +1 -1
  7. package/src/build.ts +1 -1
  8. package/src/create-kumiko-server.ts +12 -6
  9. package/src/index.ts +4 -12
  10. package/src/run-dev-app.ts +12 -8
  11. package/src/scaffold-app.ts +9 -4
  12. package/src/schema-apply.ts +4 -1
  13. package/src/schema-check-core.ts +1 -1
  14. package/src/setup-test-stack-from-features.ts +4 -1
  15. package/src/__tests__/boot-extra-context.test.ts +0 -140
  16. package/src/__tests__/build-prod-bundle.test.ts +0 -278
  17. package/src/__tests__/cache-headers.test.ts +0 -83
  18. package/src/__tests__/compose-features-mfa-wiring.integration.test.ts +0 -308
  19. package/src/__tests__/compose-features-wiring.integration.test.ts +0 -382
  20. package/src/__tests__/compose-features.test.ts +0 -128
  21. package/src/__tests__/config-seed-boot.integration.test.ts +0 -158
  22. package/src/__tests__/inject-schema.test.ts +0 -62
  23. package/src/__tests__/pii-boot-gate.test.ts +0 -68
  24. package/src/__tests__/renderer-web-css-relocation.integration.test.ts +0 -85
  25. package/src/__tests__/renderer-web-shell-sentinel.test.ts +0 -35
  26. package/src/__tests__/require-env.test.ts +0 -29
  27. package/src/__tests__/resolve-auth-mail.test.ts +0 -69
  28. package/src/__tests__/resolve-tailwind-cli.test.ts +0 -81
  29. package/src/__tests__/run-prod-app-env-source.test.ts +0 -157
  30. package/src/__tests__/run-prod-app-spec.test.ts +0 -57
  31. package/src/__tests__/run-prod-app.integration.test.ts +0 -915
  32. package/src/__tests__/session-wiring.test.ts +0 -51
  33. package/src/__tests__/try-hono-first.test.ts +0 -63
  34. package/src/boot/__tests__/job-run-logger.test.ts +0 -26
  35. package/src/boot/apply-boot-seeds.ts +0 -19
  36. package/src/boot/boot-crypto.ts +0 -82
  37. package/src/boot/job-run-logger.ts +0 -51
  38. package/src/build-prod-bundle.ts +0 -692
  39. package/src/compose-features.ts +0 -164
  40. package/src/extra-routes-deps.ts +0 -47
  41. package/src/inject-schema.ts +0 -30
  42. package/src/pii-boot-gate.ts +0 -62
  43. package/src/resolve-tailwind-cli.ts +0 -45
  44. package/src/run-prod-app-boot-context.ts +0 -241
  45. package/src/run-prod-app-static-files.ts +0 -273
  46. package/src/run-prod-app.ts +0 -1158
  47. package/src/session-wiring.ts +0 -29
  48. package/src/try-hono-first.ts +0 -46
@@ -1,1158 +0,0 @@
1
- // runProdApp — production-grade Bootstrap-Wrapper für Kumiko-Apps.
2
- //
3
- // Symmetrisch zu runDevApp, aber:
4
- // - DATABASE_URL / REDIS_URL / JWT_SECRET aus env (fail-fast bei Boot,
5
- // keine ephemeralen Test-DBs)
6
- // - Hard Schema-Drift-Gate: prüft kumiko/migrations vs. _kumiko_migrations
7
- // + tableExists für jede erwartete Tabelle. KEIN Auto-CREATE TABLE im
8
- // Boot — Migration ist ein CI-Step (`bun kumiko schema apply`), Boot
9
- // validiert nur. Verhindert Race-Conditions bei Multi-Replica-Deploys
10
- // + macht Schema-Stand reviewbar in der Pull-Request.
11
- // - Idempotente Seeds: laufen nur wenn DB leer (über `isDbEmpty`-Probe
12
- // pro Seed). Re-Boots nach erstem Seed sind no-op.
13
- // - HTTP-Server via Bun.serve mit graceful SIGTERM/SIGINT → drain().
14
- // - Auth-Routes + bundled-features auto-mix wenn `auth:` gesetzt
15
- // (gleiche Logik wie runDevApp).
16
- //
17
- // App-Author schreibt:
18
- // await runProdApp({ features, auth, anonymousAccess, seeds });
19
- //
20
- // Container/Coolify setzt:
21
- // DATABASE_URL=postgresql://...
22
- // REDIS_URL=redis://...
23
- // JWT_SECRET=<random-32+>
24
- // PORT=3000
25
- // KUMIKO_INSTANCE_ID=<stable per replica>
26
-
27
- import {
28
- AuthErrors,
29
- AuthHandlers,
30
- type AuthMailLocale,
31
- type AuthPaths,
32
- type EmailVerificationOptions,
33
- type InviteOptions,
34
- type PasswordResetOptions,
35
- type SignupOptions,
36
- } from "@cosmicdrift/kumiko-bundled-features/auth-email-password";
37
- import {
38
- type SeedAdminOptions,
39
- seedAdmin,
40
- } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/seeding";
41
- import { AUTH_MFA_FEATURE, AuthMfaHandlers } from "@cosmicdrift/kumiko-bundled-features/auth-mfa";
42
- import {
43
- createPatResolver,
44
- PAT_FEATURE,
45
- patRateLimitFromFeature,
46
- patScopesFromFeature,
47
- } from "@cosmicdrift/kumiko-bundled-features/personal-access-tokens";
48
- import { SESSIONS_FEATURE } from "@cosmicdrift/kumiko-bundled-features/sessions";
49
- import { TenantQueries } from "@cosmicdrift/kumiko-bundled-features/tenant";
50
- import {
51
- resolveTenantLifecycleGate,
52
- TENANT_LIFECYCLE_FEATURE,
53
- } from "@cosmicdrift/kumiko-bundled-features/tenant-lifecycle";
54
- import { UserQueries } from "@cosmicdrift/kumiko-bundled-features/user";
55
- import {
56
- createInMemoryLoginRateLimiter,
57
- createSseBroker,
58
- type SseBroker,
59
- } from "@cosmicdrift/kumiko-framework/api";
60
- import {
61
- configureBlindIndexKey,
62
- configurePiiSubjectKms,
63
- type KmsAdapter,
64
- } from "@cosmicdrift/kumiko-framework/crypto";
65
- import {
66
- configureEntityFieldEncryption,
67
- createDbConnection,
68
- type DbRunner,
69
- } from "@cosmicdrift/kumiko-framework/db";
70
- import {
71
- buildAppSchema,
72
- collectWriteHandlerQns,
73
- createRegistry,
74
- type EffectiveFeaturesResolver,
75
- type FeatureDefinition,
76
- findTierResolverUsage,
77
- type TierResolverPlugin,
78
- validateAppCustomScreenWriteQns,
79
- validateBoot,
80
- } from "@cosmicdrift/kumiko-framework/engine";
81
- import {
82
- type AllInOneEntrypoint,
83
- type ApiEntrypoint,
84
- createAllInOneEntrypoint,
85
- createApiEntrypoint,
86
- } from "@cosmicdrift/kumiko-framework/entrypoint";
87
- import {
88
- type ComposedEnvSchema,
89
- KumikoBootError,
90
- parseEnv,
91
- } from "@cosmicdrift/kumiko-framework/env";
92
- import { type DryRunMode, renderDryRun } from "@cosmicdrift/kumiko-framework/env/dry-run";
93
- import {
94
- createEsOperationsTable,
95
- createSeedMigrationContext,
96
- runPendingSeedMigrations,
97
- } from "@cosmicdrift/kumiko-framework/es-ops";
98
- import {
99
- assertKumikoSchemaCurrent,
100
- SchemaDriftError,
101
- } from "@cosmicdrift/kumiko-framework/migrations";
102
- import type {
103
- ObservabilityOptions,
104
- ObservabilityProvider,
105
- } from "@cosmicdrift/kumiko-framework/observability";
106
- import {
107
- createDispatcher,
108
- createEntityCache,
109
- createEventDedup,
110
- createIdempotencyGuard,
111
- } from "@cosmicdrift/kumiko-framework/pipeline";
112
- import type { MasterKeyProvider } from "@cosmicdrift/kumiko-framework/secrets";
113
- import { warnIfNonUtcServerTimeZone } from "@cosmicdrift/kumiko-framework/time";
114
- import Redis from "ioredis";
115
- import { applyBootSeeds } from "./boot/apply-boot-seeds";
116
- import { resolveBootCrypto } from "./boot/boot-crypto";
117
- import { jobRunLoggerCallbacks } from "./boot/job-run-logger";
118
- import { buildComposeAuthOptions, composeFeatures } from "./compose-features";
119
- import { type ExtraRoutesSystemDeps, makeDispatchSystemWrite } from "./extra-routes-deps";
120
- import { assertPiiBootInvariants } from "./pii-boot-gate";
121
- import {
122
- addConfigAccessorFactory,
123
- buildBootExtraContext,
124
- buildProdSessionAuth,
125
- resolveAuthMail,
126
- } from "./run-prod-app-boot-context";
127
- import { buildStaticFallback } from "./run-prod-app-static-files";
128
- import {
129
- type ProdSessionsOption,
130
- resolveProdSessionsConfig,
131
- shouldWireProdSessions,
132
- } from "./session-wiring";
133
-
134
- /**
135
- * Bun.serve-Options für Production.
136
- *
137
- * Spec: idleTimeout: 0 (= disabled). SSE-Streams werden via Heartbeat
138
- * lebend gehalten (siehe SSE_HEARTBEAT_INTERVAL_MS in framework/api/
139
- * sse-route.ts), kein Bun-side Idle-Cleanup nötig. Mit dem Default
140
- * von 10 s killt Bun nach jedem Heartbeat-Gap die Connection mit
141
- * halbem HTTP/2-RST_STREAM → Browser ERR_HTTP2_PROTOCOL_ERROR.
142
- *
143
- * Spec-Test in __tests__/run-prod-app-spec.test.ts pinst die 0 gegen
144
- * "looks like a leak"-Reverts.
145
- */
146
- export {
147
- addConfigAccessorFactory,
148
- buildBootExtraContext,
149
- resolveAuthMail,
150
- } from "./run-prod-app-boot-context";
151
- export { staticCachePolicy } from "./run-prod-app-static-files";
152
-
153
- export function buildBunServeOptions(
154
- port: number,
155
- fetchHandler: (req: Request) => Response | Promise<Response>,
156
- ): {
157
- readonly port: number;
158
- readonly fetch: (req: Request) => Response | Promise<Response>;
159
- readonly idleTimeout: number;
160
- } {
161
- return { port, fetch: fetchHandler, idleTimeout: 0 };
162
- }
163
-
164
- // Strict env-var read. Throws with a clear hint when missing — better
165
- // than discovering a Postgres-connection-refused 30s into the boot.
166
- // `src` defaults to process.env but is threaded from the caller's envSource
167
- // so the boot-path reads the SAME env-quelle that was validated above —
168
- // injected dummies in test-mode must not silently fall back to process.env.
169
- export function requireEnv(
170
- name: string,
171
- src: Record<string, string | undefined> = process.env,
172
- context = "runProdApp",
173
- ): string {
174
- const value = src[name];
175
- if (value === undefined || value === "") {
176
- const advice =
177
- context === "runProdApp"
178
- ? "Set it in your container env / .env.production / Coolify secrets."
179
- : "Set it in your .env / shell before running the dev server.";
180
- throw new Error(`${context}: required env var "${name}" is missing or empty. ${advice}`);
181
- }
182
- return value;
183
- }
184
-
185
- // Optional env helper — returns undefined for missing, string for set.
186
- // Used for KUMIKO_INSTANCE_ID, JWT_ISSUER and other "nice to have" knobs.
187
- function readEnv(
188
- name: string,
189
- src: Record<string, string | undefined> = process.env,
190
- ): string | undefined {
191
- const value = src[name];
192
- return value === undefined || value === "" ? undefined : value;
193
- }
194
-
195
- // `boot` is the C1 smoke-test path — validators run, no DB/Redis connect,
196
- // exit after registry-build. Render-modes (human|json|pulumi|k8s|1)
197
- // inspect the env-schema and exit before any feature wiring.
198
- type RunMode = DryRunMode | "boot";
199
-
200
- function parseRunMode(raw: string | undefined): RunMode | null {
201
- if (!raw) return null;
202
- const v = raw.toLowerCase();
203
- if (v === "1" || v === "true" || v === "human") return "human";
204
- if (v === "json" || v === "pulumi" || v === "k8s" || v === "boot") return v;
205
- // biome-ignore lint/suspicious/noConsole: boot-time warn for typo discovery
206
- console.warn(
207
- `[runProdApp] KUMIKO_DRY_RUN_ENV="${raw}" unrecognized ` +
208
- `(expected 1|human|json|pulumi|k8s|boot); continuing with normal boot.`,
209
- );
210
- return null;
211
- }
212
-
213
- function isRenderMode(mode: RunMode | null): mode is DryRunMode {
214
- return mode !== null && mode !== "boot";
215
- }
216
-
217
- function defaultBootErrorReporter(err: KumikoBootError): never {
218
- // biome-ignore lint/suspicious/noConsole: boot-time error, no logger configured yet
219
- console.error(err.format());
220
- process.exit(1);
221
- }
222
-
223
- // Returned from runProdApp when KUMIKO_DRY_RUN_ENV is set AND envSource
224
- // was passed (= test-mode). The handle is intentionally inert — listen()
225
- // and stop() are no-ops; tests inspect the dry-run console output and
226
- // move on.
227
- function makeDryRunHandle(): ProdAppHandle {
228
- const noop = async () => {
229
- /* dry-run handle: no server was constructed */
230
- };
231
- return {
232
- // @cast-boundary dry-run-mode: no ApiEntrypoint exists because no
233
- // boot ran; the handle only surfaces test/CLI inspection and the
234
- // entrypoint is never reached by callers in dry-run.
235
- entrypoint: undefined as unknown as ApiEntrypoint,
236
- fetch: () => new Response("dry-run", { status: 503 }),
237
- listen: noop,
238
- stop: noop,
239
- };
240
- }
241
-
242
- /** Wrapper-API für den Password-Reset-Flow.
243
- *
244
- * Seit der delivery-Migration trägt PasswordResetOptions selbst `appUrl`
245
- * (+ appName/locale) und der Handler mailt via ctx.notify — kein
246
- * sendResetEmail-Callback mehr. Apps geben `auth.mail` (Convenience,
247
- * resolveAuthMail baut die appUrl) ODER einen expliziten Block. */
248
- export type PasswordResetSetup = PasswordResetOptions;
249
-
250
- /** Wrapper-API für den Email-Verification-Flow. Symmetrisch zu
251
- * PasswordResetSetup — = EmailVerificationOptions (appUrl via delivery). */
252
- export type EmailVerificationSetup = EmailVerificationOptions;
253
-
254
- /** Wrapper-API für Magic-Link Self-Signup. = SignupOptions (appUrl, die
255
- * Mail geht via delivery/ctx.notify wie reset/verify). Anders als reset/
256
- * verify gibt's KEIN hmacSecret — Signup-Tokens sind opaque random in
257
- * Redis, nicht HMAC-signed. */
258
- export type SignupSetup = SignupOptions;
259
-
260
- /** Wrapper-API für Tenant-Invite Magic-Link. = InviteOptions (appUrl, die
261
- * Invite-Mail geht via delivery wie reset/verify/signup). Drei accept-
262
- * Branches im framework; handler-names sind hardcoded in run-prod-app aus
263
- * AuthHandlers (analog signup). */
264
- export type InviteSetup = InviteOptions;
265
-
266
- /** Auth-Mail-Convenience-Optionen — shared zwischen runProdApp + runDevApp.
267
- * Verdrahtet alle 4 Mail-Flows aus einem env-SMTP-Transport + Standard-
268
- * Templates (siehe `auth.mail` + resolveAuthMail). */
269
- export type AuthMailOptions = {
270
- /** App-Basis-URL inkl. Schema (z.B. "https://app.example.com"). */
271
- readonly baseUrl: string;
272
- /** App-Name für Mail-Subject + Body. Default "Account". */
273
- readonly appName?: string;
274
- /** Locale für die Mail-Templates. Default "de". */
275
- readonly locale?: AuthMailLocale;
276
- /** "strict" blockt Login bis emailVerified; "off" mountet ohne Gate. */
277
- readonly emailVerificationMode?: "strict" | "off";
278
- /** Fallback-From-Adresse wenn `SMTP_FROM`-env fehlt (env gewinnt). */
279
- readonly from?: string;
280
- /** Einzelne Auth-Pfade überschreiben (Default DEFAULT_AUTH_PATHS). */
281
- readonly paths?: Partial<AuthPaths>;
282
- };
283
-
284
- export type RunProdAppAuthOptions = {
285
- /** Initial admin user. Seeded once (idempotent — re-boots check first
286
- * whether the email is already in the users table). */
287
- readonly admin: SeedAdminOptions;
288
- /** Optional override of the login error → HTTP status map. */
289
- readonly loginErrorStatusMap?: Readonly<Record<string, number>>;
290
- /** Opt-in: revocable server-side sessions. Caller MUSS
291
- * `createSessionsFeature()` zu `features` adden — runProdApp wired
292
- * hier nur die Auth-Callbacks (creator/revoker/checker) gegen die
293
- * echte db-connection, plus sessionStrictMode=true.
294
- *
295
- * Standardverhalten ohne diese Option: stateless JWTs ohne sid
296
- * (legacy-Verhalten, Karten­haus existing-Apps unangefasst). */
297
- readonly sessions?: ProdSessionsOption;
298
- /** Auth-Mail-Convenience: verdrahtet alle 4 Mail-Flows (passwordReset,
299
- * emailVerification, signup, invite) aus `auth.mail.baseUrl` + Standard-
300
- * Pfaden. Alle vier mailen via delivery (ctx.notify) — ersetzt das per-App
301
- * hand-gerollte `send*Email`-Callback-Wiring.
302
- *
303
- * Null-Transport-Guard: ohne `SMTP_HOST`-env wird KEIN Mail-Flow
304
- * verdrahtet (Routes blieben sonst 500). Eine App die einen einzelnen
305
- * Flow custom braucht, setzt `passwordReset`/`signup`/… explizit —
306
- * der explizite Block gewinnt über den mail-Default.
307
- *
308
- * Bewusste Entscheidung: `mail` mountet ALLE 4 Flows inkl. signup +
309
- * invite (Self-Registration on). Wer nur reset+verify will, lässt `mail`
310
- * weg und setzt die gewünschten Flows explizit — kein impliziter
311
- * Self-Signup. */
312
- readonly mail?: AuthMailOptions;
313
- /** Password-reset flow. When set, /api/auth/request-password-reset +
314
- * /api/auth/reset-password are mounted as public routes UND der
315
- * request/confirm-Handler im auth-email-password-Feature wird
316
- * registriert (sonst dispatchen die Routes ins Leere → 500).
317
- * Überschreibt den `mail`-Default für genau diesen Flow. */
318
- readonly passwordReset?: PasswordResetSetup;
319
- /** Email-verification flow. Symmetric to passwordReset. */
320
- readonly emailVerification?: EmailVerificationSetup;
321
- /** Self-Signup flow (Magic-Link). When set, /api/auth/signup-request +
322
- * /api/auth/signup-confirm are mounted; signup-confirm mintet JWT +
323
- * Cookies wie ein erfolgreicher login (Auto-Login direkt nach
324
- * Activation). */
325
- readonly signup?: SignupSetup;
326
- /** Tenant-Invite flow (Magic-Link). When set, /api/auth/invite-accept,
327
- * /api/auth/invite-accept-with-login, /api/auth/invite-signup-complete
328
- * are mounted. */
329
- readonly invite?: InviteSetup;
330
- /** Domain attribute for both auth cookies (see
331
- * AuthRoutesConfig.cookieDomain). Set to the registrable parent
332
- * domain when login and app live on different subdomains. */
333
- readonly cookieDomain?: string;
334
- /** Server-side Origin allowlist for the CSRF guard (see
335
- * AuthRoutesConfig.allowedOrigins). REQUIRED once `cookieDomain` is set —
336
- * buildServer fails closed otherwise. Apex + admin host, never tenant
337
- * subdomains. */
338
- readonly allowedOrigins?: readonly string[];
339
- /** Opt out of the Origin guard (see AuthRoutesConfig.unsafeSkipOriginCheck)
340
- * — accept the wide-cookie CSRF risk explicitly instead of setting
341
- * `allowedOrigins`. */
342
- readonly unsafeSkipOriginCheck?: boolean;
343
- };
344
-
345
- /** Hook for app-specific seeding — runs after the admin (when auth is
346
- * active). Each seed is responsible for its own idempotence (seeds are
347
- * expected to check "is my row already there?" before inserting). */
348
- export type ProdSeedFn = (deps: {
349
- db: import("@cosmicdrift/kumiko-framework/db").DbConnection;
350
- }) => Promise<void>;
351
-
352
- /** Boot-Time-Deps die `extraContext` + `anonymousAccess` Factories als
353
- * Argument bekommen. Closure dann in der returned Config (z.B. ein
354
- * TenantResolver der gegen `db` queriet, oder ein extraContext-Provider
355
- * der direkt SSE-Events publishen will). Single-source: identisch zu
356
- * setupTestStack's extraContext-Factory-Shape damit Test/Prod gleich
357
- * aussehen. */
358
- export type RunProdAppDeps = {
359
- readonly db: import("@cosmicdrift/kumiko-framework/db").DbConnection;
360
- readonly redis: import("ioredis").default;
361
- readonly registry: import("@cosmicdrift/kumiko-framework/engine").Registry;
362
- readonly sseBroker: SseBroker;
363
- };
364
-
365
- export type AnonymousAccessOption =
366
- | import("@cosmicdrift/kumiko-framework/api").ServerOptions["anonymousAccess"]
367
- | ((
368
- deps: RunProdAppDeps,
369
- ) => import("@cosmicdrift/kumiko-framework/api").ServerOptions["anonymousAccess"]);
370
-
371
- export type ExtraContextOption =
372
- | Record<string, unknown>
373
- | ((deps: RunProdAppDeps) => Record<string, unknown>);
374
-
375
- /** Per-Host Routing-Entscheidung für den staticDir-Fallback. Wird aus
376
- * hostDispatch returned. Drei Modi:
377
- * - "html": eine bestimmte HTML-Datei (relativ zu staticDir) servieren,
378
- * mit optionaler Schema-Injection und CSP. Schema-Injection MUSS
379
- * explizit eingeschaltet werden (default false) — Public-Domain-
380
- * Antworten leaken sonst die volle Admin-UI-Schema-Topologie.
381
- * - "redirect": 301/302 an die angegebene Location.
382
- * - "not-found": klar abweisen (z.B. unbekannte Subdomain).
383
- *
384
- * Wird NUR konsultiert wenn der Pfad sonst auf den HTML-Fallback gehen
385
- * würde — also für "/", "/index.html", oder SPA-Routen die weder Hono
386
- * matched noch eine konkrete Disk-Datei treffen. Asset-Pfade (/assets/*)
387
- * und API-Pfade laufen unabhängig vom Host. */
388
- export type HostDispatchResult =
389
- | {
390
- readonly kind: "html";
391
- readonly file: string;
392
- readonly injectSchema?: boolean;
393
- readonly csp?: string;
394
- }
395
- | { readonly kind: "redirect"; readonly to: string; readonly status?: 301 | 302 }
396
- | { readonly kind: "not-found" };
397
-
398
- export type HostDispatchFn = (req: {
399
- readonly host: string;
400
- readonly path: string;
401
- /** Query-String inkl. führendem `?`, `""` wenn keiner. Redirects die
402
- * den Pfad auf einen anderen Host umbiegen (z.B. Auth-Routen mit
403
- * `?token=` aus alten Mail-Links) MÜSSEN ihn an `to` anhängen. */
404
- readonly search: string;
405
- }) => HostDispatchResult;
406
-
407
- export type RunProdAppOptions = {
408
- /** App-specific features. config/user/tenant/auth-email-password are
409
- * auto-mixed when `auth:` is set — don't add them yourself. */
410
- readonly features: readonly FeatureDefinition[];
411
- /** Listen-Port. Default 3000 (or $PORT). */
412
- readonly port?: number;
413
- /** Auth-mode: standard features + routes wired, admin seeded. */
414
- readonly auth?: RunProdAppAuthOptions;
415
- /** Custom seed functions, run after the admin seed (when auth-mode). */
416
- readonly seeds?: readonly ProdSeedFn[];
417
- /** Pfad zum seeds-Directory für ES-Operations / Seed-Migrations
418
- * (file-basiert wie drizzle-migrate). Wenn gesetzt + KUMIKO_SKIP_ES_OPS
419
- * != "1": runProdApp scannt das Verzeichnis nach `<id>.ts` Files,
420
- * diff vs kumiko_es_operations-Table, läuft pending in Tx.
421
- * Plan: kumiko-platform/docs/plans/features/es-ops.md */
422
- readonly seedsDir?: string;
423
- /** Anonymous-access for public endpoints (same shape as runDevApp).
424
- * Akzeptiert entweder einen statischen Config-Object ODER eine
425
- * Factory `({db, redis, registry}) => Config` — die Factory wird
426
- * einmal zur Boot-Zeit aufgerufen, NACHDEM db/redis/registry konstruiert
427
- * sind. Der Caller closure'd typischerweise db/redis/registry in den
428
- * TenantResolver damit z.B. ein Subdomain → Tenant-Lookup gegen die
429
- * DB möglich ist (siehe samples/showcases/publicstatus für das
430
- * Multi-Tenant-Pattern). */
431
- readonly anonymousAccess?: AnonymousAccessOption;
432
- /** Static-file root for HTML / assets. Served on the catch-all route
433
- * for any path that doesn't match an /api/ handler. Use this for the
434
- * public status page HTML, embed widget JS, etc. */
435
- readonly staticDir?: string;
436
- /** Host-aware Routing-Hook für Multi-Tenant + Multi-App-Deployments
437
- * (z.B. publicstatus's `<sub>.publicstatus.eu` (Public-Page) +
438
- * `admin.publicstatus.eu` (Admin-UI) + `publicstatus.eu` (Apex/
439
- * Marketing) im SELBEN Container).
440
- *
441
- * Wird aufgerufen wenn der staticDir-Fallback einen HTML-Response
442
- * generieren würde (Root oder SPA-Route). Default-Verhalten ohne
443
- * hostDispatch: index.html mit Schema-Injection (Single-App).
444
- *
445
- * Sicherheitshinweis: Schema-Injection (`__KUMIKO_SCHEMA__`) leakt
446
- * die Admin-UI-Topologie (alle Screens, Felder, Layouts) ans HTML.
447
- * Public-Domain-Antworten sollen das NIEMALS — `injectSchema` ist
448
- * daher default false und MUSS pro Host explizit eingeschaltet
449
- * werden. CSP-Header pro Host können zusätzlich Asset-Pfade
450
- * einschränken. */
451
- readonly hostDispatch?: HostDispatchFn;
452
- /** Pfad zu kumiko/migrations für den Boot-Gate. Default "./kumiko/
453
- * migrations" relativ zum process-cwd (wo die App gestartet wird —
454
- * bei Container-Deploys typischerweise der App-Workspace-Root, weil
455
- * WORKDIR im Dockerfile dorthin zeigt). Boot wirft SchemaDriftError
456
- * wenn Migrations pending sind oder erwartete Tabellen fehlen.
457
- * Setze auf `false` um den Gate komplett zu deaktivieren — nur für
458
- * Setups die ihren eigenen Schema-Check fahren (z.B. bring-your-own-
459
- * ORM). Standard-Apps lassen das default. */
460
- readonly migrations?: { readonly dir: string } | false;
461
- /** Extra AppContext keys. Framework-Defaults werden zur Boot-Zeit
462
- * unter den Factory-Werten ergänzt, App-Werte gewinnen immer:
463
- * - `textContent` (createTextContentApi(db)) — immer
464
- * - `secrets` (createSecretsContext) — nur wenn das `secrets`-Feature
465
- * gemountet ist (sonst kein KEK-env-Zwang für Apps ohne secrets)
466
- * - `configResolver` — im Auth-Mode (env-config-overrides)
467
- * Akzeptiert einen statischen Object ODER eine Factory
468
- * `({db, redis, registry}) => Record<string, unknown>` — gleiches
469
- * Pattern wie `anonymousAccess`. Eine App die einen dieser Keys selbst
470
- * setzt (z.B. eigener configResolver) überschreibt den Default. */
471
- readonly extraContext?: ExtraContextOption;
472
- /** MasterKeyProvider für die auto-verdrahtete `ctx.secrets`. Default:
473
- * `createEnvMasterKeyProvider` (KEK aus `KUMIKO_SECRETS_MASTER_KEY_V<n>`).
474
- * Override für KMS-Backends (AWS/GCP/Azure) statt env-KEK. Nur relevant
475
- * wenn das `secrets`-Feature gemountet ist. */
476
- readonly masterKey?: MasterKeyProvider;
477
- /** Subject-Key-Adapter für Crypto-Shredding (DSGVO Art. 17). Wenn gesetzt,
478
- * steht er Feature-Code als `ctx.kms` zur Verfügung und der Boot prüft
479
- * seine health() — die App startet nicht gegen ein unerreichbares KMS
480
- * (Silent-Start würde jeden PII-Read mit 503 beantworten). Kein Default:
481
- * ohne Adapter bleibt Crypto-Shredding aus. */
482
- readonly kms?: KmsAdapter;
483
- /** 32-Byte-Key (base64) für Blind-Index-HMACs auf `lookupable`-Feldern
484
- * (env: KUMIKO_BLIND_INDEX_KEY, `openssl rand -base64 32`). Bewusst
485
- * getrennt vom PLATFORM_KEK und nicht Teil des KmsAdapter-Contracts.
486
- * Pflicht sobald `kms` gesetzt ist UND ein Feature lookupable-Felder
487
- * deklariert — sonst bricht jeder Equality-Lookup auf Ciphertext
488
- * (Login by email!) und der Boot failt hart. */
489
- readonly blindIndexKey?: string;
490
- /** Explizites Opt-out aus dem harten PII-Boot-Gate: Features deklarieren
491
- * pii/userOwned/tenantOwned-Felder, aber es ist (noch) kein `kms`
492
- * provisioniert — die Felder liegen dann als KLARTEXT in Rows und
493
- * Events und DSGVO-Erasure via Crypto-Shredding ist unmöglich. Der Wert
494
- * ist eine Begründung für den Audit-Trail (z.B. "kms rollout pending,
495
- * infra#188"). Ohne Flag und ohne `kms` bricht der Boot ab. */
496
- readonly allowPlaintextPii?: string;
497
- /** Deploy-Topologie. Default `true` (Single-Container): dieser Prozess
498
- * fährt HTTP + BEIDE Job-Lanes (api + worker) + den Event-Dispatcher
499
- * (MSP-Anwendung) inline — via `createAllInOneEntrypoint`. Damit laufen
500
- * worker-Lane-Crons (z.B. der Daten-Export `run-export-jobs`, default
501
- * `runIn:"worker"`) und r.multiStreamProjection ohne separaten Worker.
502
- *
503
- * `false` NUR mit einem dezidierten Worker-Deployment setzen: dann fährt
504
- * dieser Prozess API-only (`createApiEntrypoint`), und worker-Lane-Jobs
505
- * + MSPs werden NICHT mehr lokal angewandt — der Worker muss sie
506
- * übernehmen, sonst bleiben Export-Jobs pending und die Read-Side leer
507
- * (2026-06-11-Incident-Klasse). */
508
- readonly runSingleInstance?: boolean;
509
- /** Job-Block. Wenn das Feature `r.job(...)` registriert, wird er
510
- * automatisch verdrahtet (siehe runSingleInstance). */
511
- readonly jobs?: {
512
- /** BullMQ-Queue-Prefix (default "kumiko"). */
513
- readonly queueNamePrefix?: string;
514
- };
515
- /** Event-Dispatcher (MSP-Anwendung) im API-Process. Default AN —
516
- * runProdApp ist das Single-Container-Deployment, es gibt keinen
517
- * Worker-Process der multiStreamProjections anwenden könnte. Bis
518
- * 2026-06-11 fehlte der Dispatcher hier komplett: jede MSP-basierte
519
- * Read-Projektion (z.B. custom-fields jsonb) blieb in Prod leer,
520
- * kumiko_event_consumers blieb ohne Rows. `disabled: true` nur für
521
- * Setups mit dezidiertem Worker-Process. */
522
- readonly eventDispatcher?: {
523
- readonly disabled?: boolean;
524
- /** Poll-Intervall des Dispatcher-Loops (default siehe
525
- * createEventDispatcher). LISTEN/NOTIFY-Wiring kommt mit einem
526
- * späteren pgClient-Pass-through. */
527
- readonly pollIntervalMs?: number;
528
- };
529
- /** Mount-Point für app-eigene HTTP-Routes außerhalb des Dispatcher-
530
- * Systems. Aufgerufen NACH /api/* + /health, VOR der static-fallback —
531
- * perfekt für GET-Endpoints die kein JSON liefern: /feed.xml,
532
- * /og-image, /sitemap.xml, /robots.txt-mit-Logik. Bekommt das raw
533
- * Hono-app + die Connection-Deps (db/redis) zum Querying.
534
- *
535
- * Naming: `deps` statt `ctx` weil im Framework `ctx` der HandlerContext
536
- * mit user/tenant/registry ist — hier ist der Scope absichtlich kleiner
537
- * (Routes laufen außerhalb der Auth/Tenant-Pipeline). */
538
- readonly extraRoutes?: (app: import("hono").Hono, deps: ExtraRoutesSystemDeps) => void;
539
- /** When true (default), Bun.serve is started before runProdApp resolves —
540
- * the common case: `await runProdApp({...})` boots the server and the
541
- * process stays up listening on PORT. Set to false in tests that drive
542
- * the fetch-handler directly (Bun.serve isn't available under vitest +
543
- * node), then call handle.listen() manually if needed. */
544
- readonly autoListen?: boolean;
545
- /** Feature-toggle resolver — durchgereicht an createApiEntrypoint's
546
- * dispatcherOptions. Sprint-8 Tier-Composition: per-Tenant unterschied-
547
- * liche features aktiv via globalFeatureToggleRuntime. Pattern:
548
- * createLateBoundHolder + post-boot runtime.initialize in einem
549
- * seed-fn (db ist erst nach migrations + features ready). */
550
- readonly effectiveFeatures?: EffectiveFeaturesResolver;
551
- /** Composed Zod-schema for env-validation (from `composeEnvSchema({
552
- * features, extend })` in @cosmicdrift/kumiko-framework/env). When set:
553
- * - `process.env` is parsed against it BEFORE any boot work; missing
554
- * or invalid vars throw a `KumikoBootError` listing ALL problems
555
- * at once (not first-fail).
556
- * - `KUMIKO_DRY_RUN_ENV=human|json|pulumi|k8s` introspects the schema
557
- * and prints the env-var inventory, then exits without booting.
558
- *
559
- * 9.1 is additive: features that still read `process.env` directly
560
- * keep working. Migration to the schema is Sprint-9.2-9.5. */
561
- readonly envSchema?: ComposedEnvSchema;
562
- /** Prefix for `pulumi config set <prefix><CamelCase(VAR)>` in dry-run
563
- * output and boot-error suggestions. Without this, suggestions use
564
- * bare `camelCase(VAR)` and ops has to guess the app prefix. */
565
- readonly pulumiPrefix?: string;
566
- /** Handler for KumikoBootError. Default: print formatted error to
567
- * stderr and `process.exit(1)` so the container restarts with a
568
- * visible log line. Override in tests that drive runProdApp directly
569
- * (avoid the exit). Return type is `void` rather than `never` to keep
570
- * test-overrides honest — if a reporter returns, runProdApp falls
571
- * through to a regular `throw err` as the safety net. */
572
- readonly bootErrorReporter?: (err: KumikoBootError) => void;
573
- /** Override `process.env` for env-validation. Default: `process.env`.
574
- * Tests use this to feed crafted env-maps without polluting the
575
- * global. */
576
- readonly envSource?: Record<string, string | undefined>;
577
- /** Observability-Provider (Tracer + Meter). Default: Noop (kein Overhead,
578
- * kein `/metrics`-Endpoint). Setze `createPrometheusMeter()`-basierten
579
- * Provider + `metrics` um `/metrics` real zu exposen (publicstatus#91). */
580
- readonly observability?: ObservabilityProvider;
581
- /** Konfiguriert die Auto-Instrumentation des resolvierten Observability-
582
- * Providers (siehe `BaseEntrypointOptions.observabilityOptions`). */
583
- readonly observabilityOptions?: ObservabilityOptions;
584
- /** Aktiviert den `/metrics`-Endpoint (Open-Metrics-Format). Ohne einen
585
- * PrometheusMeter-basierten `observability`-Provider antwortet `/metrics`
586
- * mit 503 + Misconfiguration-Hinweis statt echter Metriken. */
587
- readonly metrics?: import("@cosmicdrift/kumiko-framework/api").ServerOptions["metrics"];
588
- };
589
-
590
- export type ProdAppHandle = {
591
- /** The composed entrypoint — AllInOne (runSingleInstance, default) or
592
- * Api-only (runSingleInstance:false). In KUMIKO_DRY_RUN_ENV mode WITH
593
- * `envSource` injected (test path), no boot ran and this slot is an
594
- * undefined-cast — do not access. Production dry-run hits
595
- * `process.exit(0)` before returning a handle. */
596
- readonly entrypoint: ApiEntrypoint | AllInOneEntrypoint;
597
- /** The fetch-handler — wired into Bun.serve in production, called
598
- * directly in tests. Composes Hono + static-fallback. */
599
- readonly fetch: (req: Request) => Promise<Response> | Response;
600
- /** Active Bun-server (only set when listen() was called — tests skip
601
- * listen() because Bun.serve isn't available under vitest/node). */
602
- server?: ReturnType<typeof Bun.serve>;
603
- /** Bind to PORT and start serving. Production calls this; tests don't. */
604
- readonly listen: (port?: number) => Promise<void>;
605
- readonly stop: () => Promise<void>;
606
- };
607
-
608
- export async function runProdApp(options: RunProdAppOptions): Promise<ProdAppHandle> {
609
- // 0. Env-Schema validation + dry-run modes. Runs FIRST so:
610
- // - operators can introspect env-requirements without a real boot
611
- // (no DB connection needed, KUMIKO_DRY_RUN_ENV=… → render + exit)
612
- // - missing/invalid env-vars produce a structured KumikoBootError
613
- // with ALL problems aggregated (not first-fail), before we waste
614
- // seconds on a Postgres connection that was never configured.
615
- //
616
- // Both code paths are no-ops when no envSchema is passed — Sprint-9
617
- // migration is per-feature additive; pre-migration apps keep the
618
- // legacy `requireEnv("DATABASE_URL")` checks below.
619
- //
620
- // Ordering invariant: this step runs BEFORE the Temporal polyfill,
621
- // so env-schemas MUST use only Temporal-free Zod types. Don't author
622
- // `z.iso.date()`/`Temporal.Instant` fields on env-vars — they'd crash
623
- // at parse-time before the polyfill loads. Plain strings + .regex /
624
- // .min / .email / .url cover every env-var shape we've actually
625
- // needed in 9.1's audit (37 references, 25 distinct vars).
626
- const envSource = options.envSource ?? process.env;
627
- const runMode = parseRunMode(envSource["KUMIKO_DRY_RUN_ENV"]);
628
- if (options.envSchema) {
629
- if (isRenderMode(runMode)) {
630
- // biome-ignore lint/suspicious/noConsole: dry-run output IS the deliverable
631
- console.log(
632
- renderDryRun(options.envSchema, runMode, {
633
- ...(options.pulumiPrefix ? { pulumiPrefix: options.pulumiPrefix } : {}),
634
- sources: options.envSchema.sources,
635
- }),
636
- );
637
- // Tests inject envSource and want a return-value, not exit. Detecting
638
- // "this is a test" via envSource is brittle; instead exit when running
639
- // against the real process.env (the deploy-flow), return otherwise.
640
- if (options.envSource === undefined) {
641
- process.exit(0);
642
- }
643
- return makeDryRunHandle();
644
- }
645
- // boot-mode AND normal-boot both run env-validation. boot-mode wants
646
- // a real env-check (all required vars present + schema-valid) before
647
- // it asserts feature-wiring works.
648
- try {
649
- parseEnv(options.envSchema.schema, envSource, {
650
- sources: options.envSchema.sources,
651
- ...(options.pulumiPrefix ? { pulumiPrefix: options.pulumiPrefix } : {}),
652
- });
653
- } catch (err) {
654
- if (err instanceof KumikoBootError) {
655
- const reporter = options.bootErrorReporter ?? defaultBootErrorReporter;
656
- reporter(err);
657
- }
658
- throw err;
659
- }
660
- }
661
-
662
- // 1. Polyfill before anything else — feature code references Temporal.
663
- const { ensureTemporalPolyfill } = await import("@cosmicdrift/kumiko-framework/time");
664
- await ensureTemporalPolyfill();
665
-
666
- // 2. Env-vars: fail-fast. Better a 0s boot crash with a clear error
667
- // than a 30s timeout chasing a Postgres connection that was never
668
- // configured.
669
- const databaseUrl = requireEnv("DATABASE_URL", envSource);
670
- const redisUrl = requireEnv("REDIS_URL", envSource);
671
- const jwtSecret = requireEnv("JWT_SECRET", envSource);
672
- const jwtIssuer = readEnv("JWT_ISSUER", envSource);
673
- const instanceId = readEnv("KUMIKO_INSTANCE_ID", envSource);
674
- const port = options.port ?? Number.parseInt(envSource["PORT"] ?? "3000", 10);
675
-
676
- // biome-ignore lint/suspicious/noConsole: boot-time progress hint, no logger configured this early
677
- console.log(`[runProdApp] booting Kumiko stack on port ${port}…`);
678
-
679
- // auth.mail → expandiert in die expliziten Flow-Felder, bevor sie sowohl
680
- // die Feature-Side (buildComposeAuthOptions) als auch das Routes-Fragment
681
- // unten speisen. Ab hier IMMER effectiveAuth statt options.auth lesen.
682
- const effectiveAuth = options.auth
683
- ? resolveAuthMail(options.auth, jwtSecret, envSource)
684
- : undefined;
685
-
686
- // 3. Feature registry. Auth-mode auto-mixes config/user/tenant/auth-email-
687
- // password via composeFeatures — same source-of-truth as runDevApp
688
- // AND the per-app drizzle-Schema-Generator, so Migration und Runtime
689
- // sehen exakt dieselbe Liste. Built BEFORE any connection so boot-mode
690
- // can validate wiring and exit without opening a Postgres/Redis socket.
691
- const composeAuthOptions = buildComposeAuthOptions(effectiveAuth);
692
- const features = composeFeatures(options.features, {
693
- includeBundled: !!effectiveAuth,
694
- ...(composeAuthOptions && { authOptions: composeAuthOptions }),
695
- });
696
-
697
- validateBoot(features);
698
- warnIfNonUtcServerTimeZone();
699
- validateAppCustomScreenWriteQns(process.cwd(), collectWriteHandlerQns(features));
700
- assertPiiBootInvariants(features, {
701
- kms: options.kms,
702
- blindIndexKey: options.blindIndexKey,
703
- allowPlaintextPii: options.allowPlaintextPii,
704
- mode: "prod",
705
- });
706
- const registry = createRegistry(features);
707
-
708
- // C1 boot-mode exit: validators ran + registry built; no DB/Redis client
709
- // is constructed at all in this branch (the eager `new Redis(...)` below
710
- // would otherwise open a TCP connect just to immediately disconnect it).
711
- if (runMode === "boot") {
712
- // biome-ignore lint/suspicious/noConsole: boot-mode output IS the deliverable
713
- console.log(
714
- `[runProdApp] boot validation OK (${features.length} features, ${registry.features.size} registry entries)`,
715
- );
716
- if (options.envSource === undefined) {
717
- process.exit(0);
718
- }
719
- return makeDryRunHandle();
720
- }
721
-
722
- // 4. Connections — Postgres + Redis. The Redis client is shared by
723
- // idempotency, event-dedup, entity-cache, rate-limit; failing to
724
- // construct here surfaces the misconfig immediately. `new Redis(...)`
725
- // connects eagerly, so it must stay AFTER the boot-mode exit above.
726
- // KMS health gate: an app configured for crypto-shredding must not boot
727
- // against an unreachable key store — a silent start would answer every
728
- // PII read with 503. Runs BEFORE connections so an abort leaks nothing.
729
- if (options.kms) {
730
- const kmsHealth = await options.kms.health();
731
- if (!kmsHealth.ok) {
732
- throw new Error(
733
- `[runProdApp] BOOT ABORTED — KMS health check failed (latency ${kmsHealth.latencyMs}ms)`,
734
- );
735
- }
736
- }
737
-
738
- const { db, close: closeDb } = createDbConnection(databaseUrl);
739
- const redis = new Redis(redisUrl, { maxRetriesPerRequest: null });
740
-
741
- // Sprint-8a Tier-Composition auto-wire: scan features for a
742
- // tenantTierResolver-extension. If found AND user didn't supply own
743
- // effectiveFeatures, build the resolver here (db + registry are
744
- // available) before the dispatcher is constructed. App-Author sees
745
- // nothing — `createTierEngineFeature(opts)` mounts + framework auto-wires.
746
- let resolvedEffectiveFeatures: EffectiveFeaturesResolver | undefined = options.effectiveFeatures;
747
- if (resolvedEffectiveFeatures === undefined) {
748
- const tierResolverUsage = findTierResolverUsage(features);
749
- if (tierResolverUsage) {
750
- const plugin = tierResolverUsage.options as TierResolverPlugin;
751
- resolvedEffectiveFeatures = await plugin.build({ db, registry });
752
- }
753
- }
754
-
755
- // 5. Schema-Drift-Gate (drizzle-frei, kumiko/migrations). `kumiko schema
756
- // apply` läuft als Deploy-Step VOR dem Container-Rollout. Boot prüft nur:
757
- // (a) Alle Migrations aus kumiko/migrations/*.sql sind in
758
- // _kumiko_migrations applied (+ checksum unverändert)
759
- // (b) Alle Tabellen aus kumiko/migrations/.snapshot.json existieren
760
- // Drift = Boot-Error mit klarer Meldung (kein Auto-Heal — mehrere
761
- // Container-Replicas würden sonst race-conditionen fahren). Opt-out via
762
- // `migrations: false` für custom Schema-Setups.
763
- if (options.migrations !== false) {
764
- const migrationsDir = options.migrations?.dir ?? "./kumiko/migrations";
765
- // biome-ignore lint/suspicious/noConsole: boot-time progress hint
766
- console.log(`[runProdApp] checking schema drift (${migrationsDir})…`);
767
- try {
768
- await assertKumikoSchemaCurrent(db, migrationsDir);
769
- } catch (err) {
770
- if (err instanceof SchemaDriftError) {
771
- // biome-ignore lint/suspicious/noConsole: terminal error message
772
- console.error(`\n[runProdApp] BOOT ABORTED — ${err.message}\n`);
773
- }
774
- throw err;
775
- }
776
- }
777
-
778
- // 6. Pipeline pieces — same default config as runDevApp's setupTestStack.
779
- const idempotency = createIdempotencyGuard(redis, { ttlSeconds: 60 });
780
- const eventDedup = createEventDedup(redis, { ttlSeconds: 60 });
781
- const entityCache = createEntityCache(redis, { ttlSeconds: 60 });
782
-
783
- // 7. Lifecycle is built by createApiEntrypoint when not supplied —
784
- // we let the entrypoint own it and read it back through the handle
785
- // for SIGTERM.
786
- //
787
- // extraContext + anonymousAccess sind factory-union: entweder direktes
788
- // Object oder Function die {db, redis, registry} bekommt und das Object
789
- // returned. Factory-Form gilt als bevorzugt für Cases die zur Boot-Zeit
790
- // gegen die DB resolven müssen (z.B. Subdomain-Tenant-Lookup im
791
- // tenantResolver) — die Factory closure'd `db` und der Resolver kann
792
- // sie zur Request-Zeit aufrufen.
793
- // sseBroker hier bauen (statt's createApiEntrypoint intern machen zu
794
- // lassen) damit extraContext-Factories ihn schon zur Boot-Zeit closure'n
795
- // können — z.B. ein extraContext-Provider der direkt SSE-Events
796
- // publisht. Wir reichen denselben Broker dann an createApiEntrypoint
797
- // durch (sseBroker?-option), damit der Server-internal-Broadcast und
798
- // App-spezifische Publishes über genau einen Broker laufen.
799
- const sseBroker = createSseBroker();
800
- const deps: RunProdAppDeps = { db, redis, registry, sseBroker };
801
- const resolvedExtraContext =
802
- typeof options.extraContext === "function"
803
- ? options.extraContext(deps)
804
- : (options.extraContext ?? {});
805
-
806
- // Framework-Default-Provider zuerst, App-Werte (resolvedExtraContext)
807
- // gewinnen immer (z.B. money-horse's eigener configResolver).
808
- const bootCrypto = resolveBootCrypto(envSource, options.masterKey);
809
- // App-wide cipher for `encrypted: true` entity fields — executors resolve
810
- // it lazily, entities without encrypted fields never touch it.
811
- configureEntityFieldEncryption(bootCrypto.entityFieldCipher);
812
- // Subject-key KMS for pii-annotated fields (crypto-shredding, #724).
813
- // No adapter = engine off, plaintext as before — the warning keeps the gap
814
- // visible until the prod-grade PgKmsAdapter (phase E) makes a hard boot
815
- // gate viable (InMemory in prod would lose every DEK on restart).
816
- configurePiiSubjectKms(options.kms);
817
- // Blind-Index-Key (#818) — Boot-Gate: mit aktivem KMS würden lookupable-
818
- // Felder als Ciphertext gespeichert, ohne Key gäbe es keinen bidx-Arm und
819
- // jeder Equality-Lookup (Login by email!) liefe ins Leere. Fail-fast statt
820
- // silent-broken-auth.
821
- configureBlindIndexKey(options.blindIndexKey);
822
- const autoExtraContext = buildBootExtraContext({
823
- db,
824
- features,
825
- envSource,
826
- registry,
827
- hasAuth: !!effectiveAuth,
828
- sseBroker,
829
- crypto: bootCrypto,
830
- ...(options.kms && { kms: options.kms }),
831
- });
832
- const extraContext = addConfigAccessorFactory(
833
- { ...autoExtraContext, ...resolvedExtraContext },
834
- registry,
835
- );
836
- const resolvedAnonymousAccess =
837
- typeof options.anonymousAccess === "function"
838
- ? options.anonymousAccess(deps)
839
- : options.anonymousAccess;
840
-
841
- // Sessions opt-in: db ist hier schon konkret (createDbConnection oben),
842
- // also direkt verdrahten — kein late-bound nötig wie bei runDevApp.
843
- // sessionStrictMode=true: Prod-Sessions sollen nicht stillschweigend
844
- // von einem JWT-ohne-sid umgangen werden können. sessionMassRevoker
845
- // (4. callback aus createSessionCallbacks) ist nicht Teil der
846
- // AuthRoutesConfig-Surface — der geht via bindAutoRevokeFromFeature ans
847
- // sessions-Feature (Password-Change/-Reset revoked alle Sessions), nicht
848
- // über die auth-routes.
849
- // Secure-by-default: if the sessions feature is mounted, server-side revocation +
850
- // sessionStrictMode + auto-revoke-on-password-change are wired automatically;
851
- // `auth.sessions` only overrides the config, and `auth.sessions: false` is the
852
- // explicit opt-out (back to stateless JWTs).
853
- const sessionsFeature = features.find((f) => f.name === SESSIONS_FEATURE);
854
- const mfaFeature = features.find((f) => f.name === AUTH_MFA_FEATURE);
855
- const sessionAuthFragment = shouldWireProdSessions(
856
- Boolean(effectiveAuth),
857
- sessionsFeature !== undefined,
858
- effectiveAuth?.sessions,
859
- )
860
- ? buildProdSessionAuth(
861
- db,
862
- resolveProdSessionsConfig(effectiveAuth?.sessions),
863
- sessionsFeature,
864
- mfaFeature,
865
- )
866
- : undefined;
867
-
868
- // PAT opt-in: if the personal-access-tokens feature is mounted, wire its
869
- // resolver (bearer PATs → SessionUser, before jwt.verify). Scopes come from
870
- // the feature's exports — the same declaration its handlers use.
871
- const patFeature = features.find((f) => f.name === PAT_FEATURE);
872
- let patAuthFragment:
873
- | {
874
- patResolver: ReturnType<typeof createPatResolver>;
875
- patRateLimiter: ReturnType<typeof createInMemoryLoginRateLimiter>;
876
- }
877
- | undefined;
878
- if (effectiveAuth && patFeature) {
879
- const rl = patRateLimitFromFeature(patFeature);
880
- patAuthFragment = {
881
- patResolver: createPatResolver({ db, scopes: patScopesFromFeature(patFeature) }),
882
- patRateLimiter: createInMemoryLoginRateLimiter(rl.maxRequests, rl.windowMs),
883
- };
884
- }
885
-
886
- const tenantLifecycleFeature = features.find((f) => f.name === TENANT_LIFECYCLE_FEATURE);
887
- const tenantLifecycleAuthFragment = tenantLifecycleFeature
888
- ? {
889
- resolveTenantLifecycleStatus: async (tenantId: string) => {
890
- const gate = await resolveTenantLifecycleGate(db, tenantId);
891
- return gate ? { status: gate.status } : null;
892
- },
893
- }
894
- : undefined;
895
-
896
- const baseEntrypointOptions = {
897
- registry,
898
- context: {
899
- db,
900
- redis,
901
- entityCache,
902
- registry,
903
- ...extraContext,
904
- },
905
- sseBroker,
906
- jwtSecret,
907
- ...(jwtIssuer && { jwtIssuer }),
908
- ...(instanceId && { instanceId }),
909
- dispatcherOptions: {
910
- idempotency,
911
- ...(resolvedEffectiveFeatures && { effectiveFeatures: resolvedEffectiveFeatures }),
912
- },
913
- eventDedup,
914
- ...(options.observability && { observability: options.observability }),
915
- ...(options.observabilityOptions && { observabilityOptions: options.observabilityOptions }),
916
- ...(options.metrics && { metrics: options.metrics }),
917
- ...(effectiveAuth && {
918
- auth: {
919
- membershipQuery: TenantQueries.memberships,
920
- userQuery: UserQueries.findForAuth,
921
- loginHandler: AuthHandlers.login,
922
- loginErrorStatusMap: effectiveAuth.loginErrorStatusMap ?? {
923
- [AuthErrors.invalidCredentials]: 401,
924
- [AuthErrors.noMembership]: 403,
925
- },
926
- ...(effectiveAuth.cookieDomain !== undefined && {
927
- cookieDomain: effectiveAuth.cookieDomain,
928
- }),
929
- ...(effectiveAuth.allowedOrigins !== undefined && {
930
- allowedOrigins: effectiveAuth.allowedOrigins,
931
- }),
932
- ...(effectiveAuth.unsafeSkipOriginCheck !== undefined && {
933
- unsafeSkipOriginCheck: effectiveAuth.unsafeSkipOriginCheck,
934
- }),
935
- ...sessionAuthFragment,
936
- ...patAuthFragment,
937
- ...tenantLifecycleAuthFragment,
938
- ...(mfaFeature && { mfaVerifyHandler: AuthMfaHandlers.verify }),
939
- ...(effectiveAuth.passwordReset && {
940
- passwordReset: {
941
- requestHandler: AuthHandlers.requestPasswordReset,
942
- confirmHandler: AuthHandlers.resetPassword,
943
- },
944
- }),
945
- ...(effectiveAuth.emailVerification && {
946
- emailVerification: {
947
- requestHandler: AuthHandlers.requestEmailVerification,
948
- confirmHandler: AuthHandlers.verifyEmail,
949
- },
950
- }),
951
- ...(effectiveAuth.signup && {
952
- signup: {
953
- requestHandler: AuthHandlers.signupRequest,
954
- confirmHandler: AuthHandlers.signupConfirm,
955
- },
956
- }),
957
- ...(effectiveAuth.invite && {
958
- invite: {
959
- acceptHandler: AuthHandlers.inviteAccept,
960
- acceptWithLoginHandler: AuthHandlers.inviteAcceptWithLogin,
961
- signupCompleteHandler: AuthHandlers.inviteSignupComplete,
962
- },
963
- }),
964
- },
965
- }),
966
- ...(resolvedAnonymousAccess && { anonymousAccess: resolvedAnonymousAccess }),
967
- };
968
-
969
- // Deploy-Topologie. Default (Single-Container): createAllInOneEntrypoint
970
- // fährt HTTP + BEIDE Job-Lanes (zwei Runner, jeder schedult seine eigene
971
- // Lane-Crons → kein Double-Fire) + Event-Dispatcher inline. So laufen
972
- // worker-Lane-Crons (run-export-jobs default runIn:"worker") UND MSPs ohne
973
- // separaten Worker-Process — die Asymmetrie, an der der Daten-Export hing.
974
- // runSingleInstance:false → API-only; ein dezidierter Worker MUSS dann die
975
- // worker-Lane + MSPs übernehmen (api-Lane-Jobs laufen weiter lokal).
976
- // Default single-instance. eventDispatcher.disabled ist die Alt-Art, MSPs
977
- // diesem Prozess wegzunehmen (dezidierter Worker) — als runSingleInstance:
978
- // false honorieren (api-only, kein lokaler Dispatcher), damit der explizite
979
- // Flag Vorrang behält aber Bestands-Caller nicht brechen.
980
- const runSingleInstance = options.runSingleInstance ?? options.eventDispatcher?.disabled !== true;
981
- const hasJobs = registry.getAllJobs().size > 0;
982
- const queueNamePrefix = options.jobs?.queueNamePrefix;
983
- const jobLogger = jobRunLoggerCallbacks(registry, db);
984
- const dispatcherTunables =
985
- options.eventDispatcher?.pollIntervalMs !== undefined
986
- ? { pollIntervalMs: options.eventDispatcher.pollIntervalMs }
987
- : {};
988
-
989
- const entrypoint: ApiEntrypoint | AllInOneEntrypoint = runSingleInstance
990
- ? createAllInOneEntrypoint({
991
- ...baseEntrypointOptions,
992
- redisUrl,
993
- ...jobLogger,
994
- ...(queueNamePrefix !== undefined && { queueNamePrefix }),
995
- ...(!options.eventDispatcher?.disabled && { eventDispatcher: dispatcherTunables }),
996
- })
997
- : createApiEntrypoint({
998
- ...baseEntrypointOptions,
999
- ...(hasJobs && {
1000
- jobs: {
1001
- redisUrl,
1002
- runLocalJobs: true,
1003
- ...jobLogger,
1004
- ...(queueNamePrefix !== undefined && { queueNamePrefix }),
1005
- },
1006
- }),
1007
- });
1008
-
1009
- // 8. Build the AppSchema once + serialize. Wird beim Static-Fallback
1010
- // in die index.html injiziert damit createKumikoApp() im Browser
1011
- // `window.__KUMIKO_SCHEMA__` synchron lesen kann — gleicher Pfad
1012
- // wie im dev-server, damit der Client-Code keine Sonderfall-
1013
- // Branch zwischen dev/prod braucht. Boot-once weil Features
1014
- // nach dem Start nicht mehr ändern.
1015
- // TODO: Sobald per-Tenant- oder per-User-Schema kommt (Feature-Toggles
1016
- // pro Tenant, Auth-Rolle gated Screens), muss die Injection pro
1017
- // Request rendern — staticDir-Fallback einen render(req)-Hook bekommen
1018
- // statt eines fixed JSON-Strings. Heute: registry-static, also OK.
1019
- const appSchemaJson = JSON.stringify(buildAppSchema(registry));
1020
-
1021
- // 9. Seeds: admin first, then config-seeds from r.config({seeds}),
1022
- // then app-specific. All idempotent — runProdApp doesn't gate
1023
- // "first boot" via flag, every seed-step checks its own
1024
- // preconditions. Config-seeds rely on a deterministic
1025
- // aggregate-id so re-boot becomes a version_conflict skip.
1026
- if (effectiveAuth) {
1027
- await seedAdmin(db, effectiveAuth.admin);
1028
- }
1029
- await applyBootSeeds({
1030
- registry,
1031
- db,
1032
- ...(bootCrypto.configCipher && { cipher: bootCrypto.configCipher }),
1033
- });
1034
- for (const seed of options.seeds ?? []) {
1035
- await seed({ db });
1036
- }
1037
-
1038
- // ES-Operations / Seed-Migrations (Phase 1). Läuft NACH applyBootSeeds +
1039
- // existing seeds-array — die deklarativen Seeds sind die "always-insert-
1040
- // if-missing"-Schicht; seed-migrations sind die "diff-and-update"-
1041
- // Schicht für Drift den existing Seeds nicht erfassen können (z.B.
1042
- // Membership-Roles-Change nach initialer Seed-Erstellung).
1043
- if (options.seedsDir !== undefined && envSource["KUMIKO_SKIP_ES_OPS"] !== "1") {
1044
- await createEsOperationsTable(db);
1045
- const seedDispatcher = createDispatcher(registry, {
1046
- db,
1047
- redis,
1048
- entityCache,
1049
- registry,
1050
- ...extraContext,
1051
- });
1052
- await runPendingSeedMigrations({
1053
- db,
1054
- seedsDir: options.seedsDir,
1055
- appliedBy: "boot",
1056
- registry, // → dry-run-validator catched handler-QN-typos vor dem write
1057
- // @wrapper-known semantic-alias
1058
- createContext: (dbRunner: DbRunner) =>
1059
- createSeedMigrationContext({ dispatcher: seedDispatcher, dbRunner }),
1060
- });
1061
- }
1062
-
1063
- await entrypoint.start();
1064
-
1065
- // 10. App-eigene HTTP-Routes mounten — vor dem static-fallback. Hono
1066
- // matcht in Eintrags-Reihenfolge, also greifen explizite Routen
1067
- // der App (z.B. /feed.xml) bevor der Static-Fallback nach Disk-
1068
- // Files sucht. Eingehende /api/*-Pfade sind schon vom dispatcher
1069
- // belegt; extraRoutes sollte die nicht überschreiben (kein
1070
- // enforce, das ist Author-Verantwortung).
1071
- if (options.extraRoutes) {
1072
- options.extraRoutes(entrypoint.app, {
1073
- db,
1074
- redis,
1075
- registry,
1076
- dispatchSystemWrite: makeDispatchSystemWrite(entrypoint.dispatcher),
1077
- });
1078
- }
1079
-
1080
- // 11. Build the fetch-handler. Static-fallback for non-/api/ paths
1081
- // wired via a wrapper so Hono owns /api/* + extraRoutes and disk
1082
- // owns the rest. Tests use this directly; listen() wraps it in
1083
- // Bun.serve.
1084
- const fetchHandler = options.staticDir
1085
- ? buildStaticFallback(
1086
- entrypoint.app.fetch.bind(entrypoint.app),
1087
- options.staticDir,
1088
- appSchemaJson,
1089
- options.hostDispatch,
1090
- )
1091
- : entrypoint.app.fetch.bind(entrypoint.app);
1092
-
1093
- // 11. Mark lifecycle ready — health/ready flips to 200 after this.
1094
- entrypoint.lifecycle.markReady();
1095
-
1096
- const handle: ProdAppHandle = {
1097
- entrypoint,
1098
- fetch: fetchHandler,
1099
- listen: async (listenPort = port) => {
1100
- // Bun.serve is the production HTTP. Tests don't call listen()
1101
- // because vitest runs under Node where Bun.serve doesn't exist.
1102
- // Options-Shape (inkl. idleTimeout: 0 für SSE) liegt in der
1103
- // exportierten buildBunServeOptions-Funktion — siehe ihren
1104
- // Header für die Begründung.
1105
- if (typeof (globalThis as { Bun?: unknown }).Bun === "undefined") {
1106
- // Klare Fehlermeldung statt nackter ReferenceError. Trifft wenn
1107
- // jemand listen() unter Node/vitest aufruft ohne autoListen:false
1108
- // — hilft beim Debug, statt sich an "Bun is not defined" abzumühen.
1109
- throw new Error(
1110
- "[runProdApp] listen() requires Bun runtime (Bun.serve). " +
1111
- "Under Node/vitest pass `autoListen: false` and call the returned `fetch()` directly.",
1112
- );
1113
- }
1114
- handle.server = Bun.serve(buildBunServeOptions(listenPort, fetchHandler));
1115
-
1116
- // SIGTERM/SIGINT — graceful shutdown. Only registered when we
1117
- // actually own a Bun-server, otherwise the test process picks up
1118
- // signals it shouldn't respond to.
1119
- let shuttingDown = false;
1120
- const shutdown = async (signal: string) => {
1121
- if (shuttingDown) return;
1122
- shuttingDown = true;
1123
- // biome-ignore lint/suspicious/noConsole: boot-time progress hint, no logger configured this early
1124
- console.log(`[runProdApp] ${signal} received — draining…`);
1125
- try {
1126
- await handle.stop();
1127
- // biome-ignore lint/suspicious/noConsole: boot-time progress hint, no logger configured this early
1128
- console.log("[runProdApp] graceful shutdown complete.");
1129
- } catch (e) {
1130
- // biome-ignore lint/suspicious/noConsole: shutdown-time error, only path is stderr
1131
- console.error("[runProdApp] error during shutdown:", e);
1132
- } finally {
1133
- process.exit(0);
1134
- }
1135
- };
1136
- process.on("SIGTERM", () => void shutdown("SIGTERM"));
1137
- process.on("SIGINT", () => void shutdown("SIGINT"));
1138
-
1139
- // biome-ignore lint/suspicious/noConsole: boot-time progress hint, no logger configured this early
1140
- console.log(`[runProdApp] ready on http://0.0.0.0:${listenPort}`);
1141
- },
1142
- stop: async () => {
1143
- await entrypoint.stop();
1144
- handle.server?.stop();
1145
- await closeDb();
1146
- redis.disconnect();
1147
- },
1148
- };
1149
-
1150
- // 12. Auto-listen unless explicitly suppressed (tests pass autoListen:
1151
- // false because Bun.serve isn't available under vitest/node).
1152
- // Production path: `await runProdApp({...})` and the server is up.
1153
- if (options.autoListen !== false) {
1154
- await handle.listen();
1155
- }
1156
-
1157
- return handle;
1158
- }