@cosmicdrift/kumiko-framework 0.274.0 → 0.276.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-framework",
3
- "version": "0.274.0",
3
+ "version": "0.276.0",
4
4
  "description": "Framework core — engine, pipeline, API, DB, and every other bit that makes Kumiko go.",
5
5
  "license": "BUSL-1.1",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -198,7 +198,7 @@
198
198
  "./package.json": "./package.json"
199
199
  },
200
200
  "dependencies": {
201
- "@cosmicdrift/kumiko-types": "0.274.0",
201
+ "@cosmicdrift/kumiko-types": "0.276.0",
202
202
  "bullmq": "^5.76.7",
203
203
  "bun-types": "^1.3.13",
204
204
  "hono": "^4.13.1",
@@ -214,7 +214,7 @@
214
214
  "zod": "^4.4.3"
215
215
  },
216
216
  "devDependencies": {
217
- "@cosmicdrift/kumiko-dispatcher-live": "0.274.0",
217
+ "@cosmicdrift/kumiko-dispatcher-live": "0.276.0",
218
218
  "bun-types": "^1.3.13",
219
219
  "pino-pretty": "^13.1.3"
220
220
  },
package/src/changes.json CHANGED
@@ -1,4 +1,25 @@
1
1
  [
2
+ {
3
+ "version": "0.276.0",
4
+ "type": "improvement",
5
+ "title": "entityEdit and actionForm screens accept `slots.titleAction`, rendered on the right of the form title.",
6
+ "detail": "`ScreenSlots.titleAction` mounts an `extensionSectionComponents` entry in the form title row (same props as `slots.header`: screenId, entityName, entityId, values). `FormProps.titleAction` carries it to the primitives; the web `DefaultForm` renders it right-aligned next to title and subtitle in `<testId>-title-action`, in both the card and the chromeless layout. Native primitives may ignore it.",
7
+ "migration": "No action required — purely additive."
8
+ },
9
+ {
10
+ "version": "0.275.0",
11
+ "type": "breaking",
12
+ "title": "JobContext.db is a tenant-filtered TenantDb; unfiltered job access needs r.job({ escapeHatch }) or r.systemScope() (fw#2914).",
13
+ "detail": "Job handlers no longer receive the unfiltered boot `DbConnection` as `ctx.db`. `JobContext.db` is now a `TenantDb` in \"tenant\" mode, bound to the job's resolved tenant (`_tenantId`, `payload.tenantId`, or `SYSTEM_TENANT_ID` for tenant-less cron jobs). Reads see that tenant plus `SYSTEM_TENANT_ID` reference rows, and writes are scoped to it. `JobDefinition` gains `escapeHatch?: { reason }`: it grants `ctx.db.unsafeRaw(reason)` for that job and reports an `\"unsafe-raw\"` escape-hatch audit event through `_escapeHatchAuditSink` (deduplicated like handler grants). Without it, `ctx.db.unsafeRaw` throws `AccessDeniedError`. `r.systemScope()` features keep `ctx.systemDb` unchanged. `r.job` throws at registration for an `escapeHatch` with an empty reason. Framework `soft-delete` cleanup jobs run on the tenant-filtered `TenantDb` without a grant. Bundled cross-tenant jobs now declare `escapeHatch`: auth-mfa reencrypt, sessions cleanup, form-draft cleanup, secrets rotate, files-tenant-data sweep-orphaned-derivatives, data-retention retention-cleanup, inbound-mail-retention, tenant-lifecycle run-tenant-destruction, and user-data-rights run-export-jobs/run-forget-cleanup. The systemScope features config, jobs and workflow-runner use `ctx.systemDb.unsafeRaw`. The exported `rotateJob` (secrets) and `sweepOrphanedDerivativesJob` (files-tenant-data) take the raw `DbConnection` as a third argument.",
14
+ "migration": "Jobs that only read and write their own tenant through `ctx.db` method calls or `selectMany/fetchOne/insertOne/updateMany/deleteMany(ctx.db, ...)` need no change. A job that treated `ctx.db` as a `DbConnection` (casts, `asRawClient`, `countWhere`, `upsert*`, `incrementCounter`, `createTenantDb(ctx.db, ...)`, `runProjectionsForEvent(..., ctx.db)`, or `\"raw\" in db ? db.raw : db`) must declare the grant and fetch the runner explicitly. Use `r.job({ name, trigger, escapeHatch: { reason: \"<why>\" }, handler: async (payload, ctx) => work(ctx.db.unsafeRaw(\"<why>\")) })`; keep the `unsafeRaw` call inside the inline `handler` next to `escapeHatch` so `guard-escape-hatch-declared` recognizes the declaration. `r.systemScope()` features use `ctx.systemDb.unsafeRaw(reason)` instead. WARNING: a job that is not migrated but passes a foreign `where.tenantId` through `ctx.db` does not fail; the filter silently narrows it to the job's own tenant (`SYSTEM_TENANT_ID` for tenant-less cron jobs), so cross-tenant sweeps silently read nothing. Audit every cross-tenant job. Hand-built `JobContext` objects in tests need `db: createTenantDb(conn, tenantId)` (plus `systemDb` for systemScope jobs). Direct callers of `rotateJob`/`sweepOrphanedDerivativesJob` pass the raw connection as the third argument."
15
+ },
16
+ {
17
+ "version": "0.274.0",
18
+ "type": "improvement",
19
+ "title": "A money field can declare `currency: { kind: \"tenant\" }` to source its currency from the tenant-settings config key.",
20
+ "detail": "`createMoneyField` accepts an optional `currency: MoneyCurrencySource` — a discriminated union (exported from `@cosmicdrift/kumiko-framework/engine/types`), currently only `{ kind: \"tenant\" }`, left room for #2839's later `literal`/`field` variants. The declaration reaches the client app schema (`buildAppSchema`'s field projection). In an entityEdit form (create and update), a rendered money field that declares `{ kind: \"tenant\" }` reads the tenant's currency via the existing `config:query:values` query (key `tenant-settings:config:currency`) instead of `entity.defaultCurrency ?? \"EUR\"`: an empty value's initial amount and currency come from the tenant's setting, and the form waits for that query rather than momentarily showing/submitting `EUR` while it is in flight. A field's already-stored value always keeps its own currency, unaffected by the declaration. A field without the declaration is unchanged.",
21
+ "migration": "No action required — purely additive; a money field without `currency` declared keeps today's `entity.defaultCurrency ?? \"EUR\"` behavior."
22
+ },
2
23
  {
3
24
  "version": "0.274.0",
4
25
  "type": "breaking",
@@ -622,6 +622,28 @@ describe("buildAppSchema", () => {
622
622
  expect("defaultCurrency" in app.features[0]!.entities["thing"]!).toBe(false);
623
623
  });
624
624
 
625
+ test("money field's `currency: { kind: 'tenant' }` declaration survives the projection (fw#2933)", () => {
626
+ const entity = {
627
+ defaultCurrency: "USD",
628
+ fields: {
629
+ price: { type: "money", currency: { kind: "tenant" } },
630
+ cost: { type: "money" },
631
+ },
632
+ } as unknown as EntityDefinition;
633
+
634
+ const f = defineFeature("ent", (r) => {
635
+ r.entity("thing", entity);
636
+ });
637
+ const app = buildAppSchema(createRegistry([f]));
638
+ const projected = app.features[0]!.entities["thing"] as unknown as {
639
+ fields: Record<string, Record<string, unknown>>;
640
+ };
641
+
642
+ expect(projected.fields["price"]?.["currency"]).toEqual({ kind: "tenant" });
643
+ expect(projected.fields["cost"]?.["currency"]).toBeUndefined();
644
+ expect(JSON.parse(JSON.stringify(projected))).toEqual(projected);
645
+ });
646
+
625
647
  test("text format, timestamp locatedBy, file accept/maxSize, image variants and decimal scale survive the projection", () => {
626
648
  // Regression: all of these are read by the edit view-model (password
627
649
  // masking, wall-clock input, upload constraints, preview variant, derived
@@ -0,0 +1,85 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { createApp, createRegistry, dedupeFeatures, defineFeature } from "../index";
3
+
4
+ describe("dedupeFeatures", () => {
5
+ test("same reference mounted twice collapses to one entry, order preserved", () => {
6
+ const shared = defineFeature("shared", () => {});
7
+ const other = defineFeature("other", () => {});
8
+
9
+ const result = dedupeFeatures([shared, other, shared]);
10
+
11
+ expect(result).toEqual([shared, other]);
12
+ expect(result[0]).toBe(shared);
13
+ });
14
+
15
+ test("registry builds when the same reference is mounted twice", () => {
16
+ const shared = defineFeature("shared", () => {});
17
+
18
+ expect(() => createRegistry([shared, shared])).not.toThrow();
19
+ });
20
+
21
+ test("two instances with shallow-equal dedupeOptions collapse — first instance kept", () => {
22
+ const a = defineFeature("x", () => {}, { dedupeOptions: { limit: 3 } });
23
+ const b = defineFeature("x", () => {}, { dedupeOptions: { limit: 3 } });
24
+ const other = defineFeature("y", () => {});
25
+
26
+ const result = dedupeFeatures([a, other, b]);
27
+
28
+ expect(result).toEqual([a, other]);
29
+ expect(result[0]).toBe(a);
30
+ });
31
+
32
+ test("differing primitive dedupeOptions throws with a 'different options' message", () => {
33
+ const a = defineFeature("x", () => {}, { dedupeOptions: { limit: 3 } });
34
+ const b = defineFeature("x", () => {}, { dedupeOptions: { limit: 5 } });
35
+
36
+ expect(() => dedupeFeatures([a, b])).toThrow(/Duplicate feature: "x".*different options/);
37
+ });
38
+
39
+ test("same function reference in dedupeOptions collapses", () => {
40
+ const onTrigger = () => {};
41
+ const a = defineFeature("x", () => {}, { dedupeOptions: { onTrigger } });
42
+ const b = defineFeature("x", () => {}, { dedupeOptions: { onTrigger } });
43
+
44
+ const result = dedupeFeatures([a, b]);
45
+
46
+ expect(result).toEqual([a]);
47
+ });
48
+
49
+ test("different function reference in dedupeOptions throws", () => {
50
+ const a = defineFeature("x", () => {}, { dedupeOptions: { onTrigger: () => {} } });
51
+ const b = defineFeature("x", () => {}, { dedupeOptions: { onTrigger: () => {} } });
52
+
53
+ expect(() => dedupeFeatures([a, b])).toThrow(/Duplicate feature: "x".*different options/);
54
+ });
55
+
56
+ test("{ a: undefined } and {} are treated as shallow-equal (missing key == undefined)", () => {
57
+ const a = defineFeature("x", () => {}, { dedupeOptions: { a: undefined } });
58
+ const b = defineFeature("x", () => {}, { dedupeOptions: {} });
59
+
60
+ const result = dedupeFeatures([a, b]);
61
+
62
+ expect(result).toEqual([a]);
63
+ });
64
+
65
+ test("two distinct instances with no dedupeOptions throw with a 'distinct instances' message", () => {
66
+ const a = defineFeature("x", () => {});
67
+ const b = defineFeature("x", () => {});
68
+
69
+ expect(() => dedupeFeatures([a, b])).toThrow(
70
+ /Duplicate feature: "x" mounted twice as distinct instances/,
71
+ );
72
+ });
73
+
74
+ test("createApp boots end-to-end with a feature mounted twice via dedupeOptions", () => {
75
+ const a = defineFeature("x", () => {}, { dedupeOptions: {} });
76
+ const b = defineFeature("x", () => {}, { dedupeOptions: {} });
77
+
78
+ expect(() =>
79
+ createApp({
80
+ roles: ["Admin"],
81
+ features: [a, b],
82
+ }),
83
+ ).not.toThrow();
84
+ });
85
+ });
@@ -0,0 +1,82 @@
1
+ // fw#2914 — soft-delete cleanup runs through the real job runner with ctx.db as a
2
+ // tenant-filtered TenantDb: a run purges only its own tenant's expired rows.
3
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
4
+ import { asRawClient } from "../../bun-db/query";
5
+ import { selectMany } from "../../db/query";
6
+ import { buildEntityTable } from "../../db/table-builder";
7
+ import { setupTestStack, type TestStack, TestUsers, unsafeCreateEntityTable } from "../../stack";
8
+ import { waitFor } from "../../testing";
9
+ import {
10
+ createEntity,
11
+ createTextField,
12
+ defineEntityCreateHandler,
13
+ defineEntityDeleteHandler,
14
+ defineFeature,
15
+ } from "../index";
16
+ import { SOFT_DELETE_CLEANUP_JOB } from "../soft-delete-cleanup";
17
+
18
+ const itemEntity = createEntity({
19
+ table: "fw2914_sdc_items",
20
+ softDelete: true,
21
+ fields: {
22
+ label: createTextField({ required: true, personal: false, reason: "test_fixture" }),
23
+ },
24
+ });
25
+ const itemTable = buildEntityTable("item", itemEntity);
26
+
27
+ const feature = defineFeature("sdcjob", (r) => {
28
+ r.entity("item", itemEntity);
29
+ r.writeHandler(defineEntityCreateHandler("item", itemEntity, { access: { roles: ["Admin"] } }));
30
+ r.writeHandler(defineEntityDeleteHandler("item", itemEntity, { access: { roles: ["Admin"] } }));
31
+ });
32
+
33
+ let stack: TestStack;
34
+
35
+ beforeAll(async () => {
36
+ stack = await setupTestStack({
37
+ features: [feature],
38
+ jobs: {
39
+ consumerLane: "worker",
40
+ getActiveTenantIds: async () => [TestUsers.admin.tenantId],
41
+ },
42
+ });
43
+ await unsafeCreateEntityTable(stack.db, itemEntity, "item");
44
+ });
45
+
46
+ afterAll(async () => {
47
+ await stack.cleanup();
48
+ });
49
+
50
+ async function createExpiredDeletedItem(user: typeof TestUsers.admin): Promise<string> {
51
+ const created = await stack.http.writeOk<{ id: string }>(
52
+ "sdcjob:write:item:create",
53
+ { label: `expired-${user.tenantId}` },
54
+ user,
55
+ );
56
+ await stack.http.writeOk("sdcjob:write:item:delete", { id: created.id }, user);
57
+ // kumiko-lint-ignore raw-sql test fixture ages deletedAt past the default grace period
58
+ await asRawClient(stack.db).unsafe(
59
+ `UPDATE fw2914_sdc_items SET deleted_at = now() - interval '400 days' WHERE id = $1`,
60
+ [created.id],
61
+ );
62
+ return created.id;
63
+ }
64
+
65
+ describe("soft-delete cleanup job smoke run on a tenant-filtered JobContext.db (fw#2914)", () => {
66
+ test("a per-tenant fan-out run purges only the active tenant's expired soft-deleted rows", async () => {
67
+ const ownId = await createExpiredDeletedItem(TestUsers.admin);
68
+ const foreignId = await createExpiredDeletedItem(TestUsers.otherTenant);
69
+ const jobRunner = stack.jobRunner;
70
+ if (!jobRunner) throw new Error("setupTestStack({ jobs }) did not wire a jobRunner");
71
+
72
+ await jobRunner.dispatch(SOFT_DELETE_CLEANUP_JOB, {});
73
+
74
+ await waitFor(async () => {
75
+ const own = await selectMany(stack.db, itemTable, { id: ownId });
76
+ expect(own).toHaveLength(0);
77
+ });
78
+ const foreign = await selectMany(stack.db, itemTable, { id: foreignId });
79
+ expect(foreign).toHaveLength(1);
80
+ expect(foreign[0]?.["isDeleted"]).toBe(true);
81
+ });
82
+ });
@@ -1,4 +1,5 @@
1
1
  import { validateEntityFieldEncryptionAvailable } from "../../db/entity-field-encryption";
2
+ import { dedupeFeatures } from "../dedupe-features";
2
3
  import { QnTypes, qualifyEntityName } from "../qualified-name";
3
4
  import type { FeatureDefinition } from "../types";
4
5
  import { validateAccessDeclarations } from "./access-declarations";
@@ -91,9 +92,10 @@ export type ValidateBootOptions = {
91
92
  * Throws on the first error found — fail fast.
92
93
  */
93
94
  export function validateBoot(
94
- features: readonly FeatureDefinition[],
95
+ rawFeatures: readonly FeatureDefinition[],
95
96
  options?: ValidateBootOptions,
96
97
  ): void {
98
+ const features = dedupeFeatures(rawFeatures);
97
99
  const featureMap = new Map<string, FeatureDefinition>();
98
100
  for (const f of features) {
99
101
  featureMap.set(f.name, f);
@@ -497,6 +497,11 @@ function projectField(fieldDef: FieldDefinition): FieldDefinition {
497
497
  out["variants"] = def["variants"];
498
498
  // decimal, incl. embedded sub-fields: rounding of derived embedded-list cells.
499
499
  if (typeof def["scale"] === "number") out["scale"] = def["scale"];
500
+ // money: declared currency source (MoneyCurrencySource, fw#2933) — without
501
+ // it the renderer can't tell a "currency: { kind: 'tenant' }" field apart
502
+ // from an undeclared one and always falls back to entity.defaultCurrency.
503
+ if (isPlainObject(def["currency"]) && isJsonSafeValue(def["currency"]))
504
+ out["currency"] = def["currency"];
500
505
  // embedded lists: row-count bounds, computed cells, totals row, and the
501
506
  // sibling-money-field totals check (fw#2497).
502
507
  if (typeof def["minItems"] === "number") out["minItems"] = def["minItems"];
@@ -97,6 +97,15 @@ export type { ConcurrencyMode };
97
97
  const _concurrencyModeExhaustive: Record<ConcurrencyMode, unknown> = ConcurrencyModes;
98
98
  void _concurrencyModeExhaustive;
99
99
 
100
+ // --- Money Currency Sources ---
101
+ // Canonical definition lives in kumiko-types/fields (client-safe, next to
102
+ // MoneyCurrencySource) so renderer code can import it without pulling in
103
+ // runtime-only engine code (fw#2937). Re-exported here for server callers
104
+ // already importing framework/engine (bundled-features/src/tenant-settings/
105
+ // constants.ts TenantSettingsConfig.currency reuses this same constant, so
106
+ // the two stay in sync by construction).
107
+ export { TENANT_CURRENCY_CONFIG_KEY } from "@cosmicdrift/kumiko-types/fields";
108
+
100
109
  // --- SSE Channels ---
101
110
 
102
111
  export function tenantChannel(tenantId: TenantId): string {
@@ -1,4 +1,5 @@
1
1
  import { type ValidateBootOptions, validateBoot } from "./boot-validator";
2
+ import { dedupeFeatures } from "./dedupe-features";
2
3
  import { createRegistry } from "./registry";
3
4
  import type { FeatureDefinition, Registry } from "./types";
4
5
  import { DEFAULT_CURRENCIES } from "./types";
@@ -20,6 +21,7 @@ export type App = {
20
21
  };
21
22
 
22
23
  export function createApp(config: AppConfig): App {
24
+ const features = dedupeFeatures(config.features);
23
25
  const validRoles = new Set(config.roles);
24
26
 
25
27
  // "system" is reserved for SYSTEM_USER — cannot be used as an app role
@@ -32,7 +34,7 @@ export function createApp(config: AppConfig): App {
32
34
 
33
35
  // Validate all roles referenced by features exist in app-defined roles.
34
36
  // openToAll access has no role list — nothing to validate there.
35
- for (const feature of config.features) {
37
+ for (const feature of features) {
36
38
  for (const handler of Object.values(feature.writeHandlers)) {
37
39
  if (handler.access && "roles" in handler.access) {
38
40
  for (const role of handler.access.roles) {
@@ -83,7 +85,7 @@ export function createApp(config: AppConfig): App {
83
85
  const currencies = [...new Set([...DEFAULT_CURRENCIES, ...(config.currencies ?? [])])];
84
86
 
85
87
  // Validate defaultCurrency on entities that have money fields
86
- for (const feature of config.features) {
88
+ for (const feature of features) {
87
89
  for (const [entityName, entity] of Object.entries(feature.entities ?? {})) {
88
90
  // A top-level money field isn't the only way an entity can hold money —
89
91
  // an embedded-list's sub-schema (e.g. invoice lines) can carry a money
@@ -110,10 +112,10 @@ export function createApp(config: AppConfig): App {
110
112
  }
111
113
 
112
114
  // Run boot-time validation before creating registry
113
- validateBoot(config.features, config.validateBootOptions);
115
+ validateBoot(features, config.validateBootOptions);
114
116
 
115
117
  return {
116
- registry: createRegistry(config.features),
118
+ registry: createRegistry(features),
117
119
  roles: config.roles,
118
120
  softDeleteDefault,
119
121
  currencies,
@@ -0,0 +1,46 @@
1
+ import type { FeatureDefinition } from "./types";
2
+
3
+ function dedupeOptionsShallowEqual(
4
+ a: Readonly<Record<string, unknown>>,
5
+ b: Readonly<Record<string, unknown>>,
6
+ ): boolean {
7
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
8
+ for (const key of keys) {
9
+ if (!Object.is(a[key], b[key])) return false;
10
+ }
11
+ return true;
12
+ }
13
+
14
+ function isInterchangeable(existing: FeatureDefinition, next: FeatureDefinition): boolean {
15
+ if (existing === next) return true;
16
+ if (existing.dedupeOptions !== undefined && next.dedupeOptions !== undefined) {
17
+ return dedupeOptionsShallowEqual(existing.dedupeOptions, next.dedupeOptions);
18
+ }
19
+ return false;
20
+ }
21
+
22
+ // First occurrence wins: runtimes late-bind closure state (sessions' autoRevoke) on the kept instance.
23
+ export function dedupeFeatures(features: readonly FeatureDefinition[]): FeatureDefinition[] {
24
+ const byName = new Map<string, FeatureDefinition>();
25
+ const result: FeatureDefinition[] = [];
26
+
27
+ for (const feature of features) {
28
+ const existing = byName.get(feature.name);
29
+ if (existing === undefined) {
30
+ byName.set(feature.name, feature);
31
+ result.push(feature);
32
+ continue;
33
+ }
34
+ if (isInterchangeable(existing, feature)) continue;
35
+ if (existing.dedupeOptions !== undefined && feature.dedupeOptions !== undefined) {
36
+ throw new Error(
37
+ `Duplicate feature: "${feature.name}" mounted twice with different options — mount it once or pass identical options`,
38
+ );
39
+ }
40
+ throw new Error(
41
+ `Duplicate feature: "${feature.name}" mounted twice as distinct instances — mount it once`,
42
+ );
43
+ }
44
+
45
+ return result;
46
+ }
@@ -29,9 +29,14 @@ function resolveFeatureNamesArgs(
29
29
  return unwrapArrayForm(args, "features");
30
30
  }
31
31
 
32
+ export type DefineFeatureSettings = {
33
+ readonly dedupeOptions?: Readonly<Record<string, unknown>>;
34
+ };
35
+
32
36
  export function defineFeature<const TName extends string, TExports = undefined>(
33
37
  name: TName,
34
38
  setup: (r: FeatureRegistrar<TName>) => TExports,
39
+ settings?: DefineFeatureSettings,
35
40
  ): FeatureDefinition & { readonly exports: TExports } {
36
41
  const state = createInitialFeatureBuilderState();
37
42
 
@@ -158,5 +163,6 @@ export function defineFeature<const TName extends string, TExports = undefined>(
158
163
  storeTables: state.storeTables,
159
164
  ...(state.treeActions !== undefined && { treeActions: state.treeActions }),
160
165
  ...(state.envSchema !== undefined && { envSchema: state.envSchema }),
166
+ ...(settings?.dedupeOptions !== undefined && { dedupeOptions: settings.dedupeOptions }),
161
167
  };
162
168
  }
@@ -68,8 +68,8 @@ const FEATURES: readonly RealFeature[] = [
68
68
  {
69
69
  path: "packages/bundled-features/src/sessions/feature.ts",
70
70
  expectedFeatureName: "sessions",
71
- recognisedKinds: ["hook", "writeHandler", "queryHandler"],
72
- errorMethodNames: ["storeTable", "job"],
71
+ recognisedKinds: ["hook", "writeHandler", "queryHandler", "job"],
72
+ errorMethodNames: ["storeTable"],
73
73
  },
74
74
  {
75
75
  path: "packages/bundled-features/src/auth-email-password/feature.ts",
@@ -181,9 +181,18 @@ export function buildConfigEventsJobsMethods<TName extends string>(
181
181
  handler as JobHandlerFn,
182
182
  ]
183
183
  : (() => {
184
- const { name, handler: h, ...rest } = jobNameOrDefinition;
185
- return [name, rest, h] as const;
184
+ const { name: definedJobName, handler: h, ...rest } = jobNameOrDefinition;
185
+ return [definedJobName, rest, h] as const;
186
186
  })();
187
+ if (
188
+ jobOptions.escapeHatch !== undefined &&
189
+ jobOptions.escapeHatch.reason.trim().length === 0
190
+ ) {
191
+ throw new Error(
192
+ `[Feature ${name}] r.job("${jobName}") declares { escapeHatch: { reason: "" } } — ` +
193
+ "the reason must be a non-empty string explaining why this job needs unfiltered database access.",
194
+ );
195
+ }
187
196
  // Resolve NameOrRef(s) in trigger.on. Multi-Trigger-Form: Array
188
197
  // wird zu Array von resolved strings, Single bleibt single string —
189
198
  // job-runner unterscheidet anhand Array.isArray.
@@ -44,11 +44,13 @@ export {
44
44
  OnDeleteStrategies,
45
45
  SystemHookNames,
46
46
  SystemHookPriorities,
47
+ TENANT_CURRENCY_CONFIG_KEY,
47
48
  tenantChannel,
48
49
  } from "./constants";
49
50
  export type { App, AppConfig } from "./create-app";
50
51
  export { createApp } from "./create-app";
51
52
  export { crossTenantOverrideDenied } from "./cross-tenant";
53
+ export { dedupeFeatures } from "./dedupe-features";
52
54
  export { defineFeature } from "./define-feature";
53
55
  export type {
54
56
  PagedQueryHandlerDefinition,
@@ -1,4 +1,5 @@
1
1
  import { validateExtensionPreSaveWiring } from "./boot-validator/entity-handler";
2
+ import { dedupeFeatures } from "./dedupe-features";
2
3
  import { buildRegistryFacade } from "./registry-facade";
3
4
  import {
4
5
  populateClaimsAndAuth,
@@ -44,7 +45,8 @@ import type { FeatureDefinition, Registry } from "./types";
44
45
  // This is where the magic happens. By "magic" I mean: precomputed maps.
45
46
  // I build everything once at boot (hooks, relations, searchable fields, ...)
46
47
  // so nothing has to iterate over objects at runtime. O(1) instead of O(n*m).
47
- export function createRegistry(features: readonly FeatureDefinition[]): Registry {
48
+ export function createRegistry(rawFeatures: readonly FeatureDefinition[]): Registry {
49
+ const features = dedupeFeatures(rawFeatures);
48
50
  const state = createInitialState();
49
51
 
50
52
  for (const feature of features) {
@@ -42,9 +42,10 @@ export const softDeleteCleanupJob: JobHandlerFn = async (_payload, ctx) => {
42
42
  throw new Error("soft-delete cleanup: ctx.db + ctx.registry required (JobContext incomplete)");
43
43
  }
44
44
  // perTenant fan-out → one run per active tenant, systemUser scoped to it.
45
- // The job's db is the boot DbConnection (NOT tenant-scoped), so every delete
46
- // is explicitly tenant-filtered below — otherwise a tenant with a short grace
47
- // would purge another tenant's still-within-grace rows.
45
+ // The job's db is a tenant-filtered TenantDb, but every delete is still
46
+ // explicitly tenant-filtered below as defense-in-depth — otherwise a
47
+ // tenant with a short grace would purge another tenant's still-within-grace
48
+ // rows.
48
49
  const tenantId = ctx.systemUser?.tenantId ?? ctx._tenantId;
49
50
  if (tenantId === undefined) {
50
51
  // skip: cron fired without a perTenant fan-out tenant — nothing scoped to purge
@@ -119,6 +119,7 @@ export type {
119
119
  LocatedTimestampFieldDef,
120
120
  LongTextFieldDef,
121
121
  LongTextFindability,
122
+ MoneyCurrencySource,
122
123
  MoneyFieldDef,
123
124
  MultiSelectFieldDef,
124
125
  NumberFieldDef,
@@ -49,7 +49,7 @@ const systemScopedFeature = defineFeature("jobsystemdb-system", (r) => {
49
49
  results.push({
50
50
  name: "system",
51
51
  present: true,
52
- boundToRawDb: tenantDbRunner(checked) === ctx.db,
52
+ boundToRawDb: tenantDbRunner(checked) === tenantDbRunner(ctx.db),
53
53
  foreignTenantThrew,
54
54
  });
55
55
  });
@@ -0,0 +1,162 @@
1
+ // fw#2914 — JobContext.db is a tenant-filtered TenantDb; unfiltered access needs r.job({ escapeHatch }).
2
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3
+ import { type BunTestDb, createTestDb } from "../../bun-db/__tests__/bun-test-db";
4
+ import type { DbRunner } from "../../db/connection";
5
+ import { table, text, uuid } from "../../db/dialect";
6
+ import { insertOne, selectMany } from "../../db/query";
7
+ import { createRegistry, defineFeature, type Registry } from "../../engine";
8
+ import type { EscapeHatchUseEvent, JobContext } from "../../engine/types";
9
+ import { AccessDeniedError } from "../../errors";
10
+ import { createTestRedis, type TestRedis, testTenantId, unsafePushTables } from "../../stack";
11
+ import { waitFor } from "../../testing";
12
+ import { createJobRunner, type JobRunner } from "../job-runner";
13
+
14
+ const itemsTable = table("fw2914_job_items", {
15
+ id: uuid("id").primaryKey().defaultRandom(),
16
+ tenantId: uuid("tenant_id").notNull(),
17
+ label: text("label").notNull(),
18
+ });
19
+
20
+ const ownTenant = testTenantId(1);
21
+ const foreignTenant = testTenantId(2);
22
+ const DECLARED_REASON = "fw#2914 integration test — job counts items of every tenant";
23
+
24
+ type Outcome = {
25
+ readonly job: "undeclared" | "declared";
26
+ readonly mode?: string;
27
+ readonly tenantId?: string;
28
+ readonly labels?: readonly string[];
29
+ readonly foreignWhereLabels?: readonly string[];
30
+ readonly unsafeRawDenied?: boolean;
31
+ readonly rawLabels?: readonly string[];
32
+ };
33
+
34
+ const outcomes: Outcome[] = [];
35
+ const auditEvents: EscapeHatchUseEvent[] = [];
36
+
37
+ function labelsOf(rows: readonly { label: string }[]): string[] {
38
+ return rows.map((row) => row.label).sort();
39
+ }
40
+
41
+ const jobsFeature = defineFeature("jobtenantdb", (r) => {
42
+ r.job("undeclared", { trigger: { manual: true } }, async (_payload, ctx) => {
43
+ const own = await selectMany<{ label: string }>(ctx.db, itemsTable);
44
+ const foreignWhere = await selectMany<{ label: string }>(ctx.db, itemsTable, {
45
+ tenantId: foreignTenant,
46
+ });
47
+ let unsafeRawDenied = false;
48
+ try {
49
+ ctx.db.unsafeRaw("fw#2914 integration test — undeclared job reaching for raw");
50
+ } catch (err) {
51
+ unsafeRawDenied = err instanceof AccessDeniedError;
52
+ }
53
+ outcomes.push({
54
+ job: "undeclared",
55
+ mode: ctx.db.mode,
56
+ tenantId: ctx.db.tenantId,
57
+ labels: labelsOf(own),
58
+ foreignWhereLabels: labelsOf(foreignWhere),
59
+ unsafeRawDenied,
60
+ });
61
+ });
62
+
63
+ r.job({
64
+ name: "declared",
65
+ trigger: { manual: true },
66
+ escapeHatch: { reason: DECLARED_REASON },
67
+ handler: async (_payload, ctx) => {
68
+ const raw = ctx.db.unsafeRaw(DECLARED_REASON);
69
+ const rows = await selectMany<{ label: string }>(raw, itemsTable);
70
+ outcomes.push({ job: "declared", rawLabels: labelsOf(rows) });
71
+ },
72
+ });
73
+ });
74
+
75
+ let testDb: BunTestDb;
76
+ let testRedis: TestRedis;
77
+ let registry: Registry;
78
+ let jobRunner: JobRunner;
79
+
80
+ beforeAll(async () => {
81
+ testDb = await createTestDb();
82
+ testRedis = await createTestRedis();
83
+ await unsafePushTables(testDb.db, { fw2914_job_items: itemsTable });
84
+ await insertOne(testDb.db, itemsTable, { tenantId: ownTenant, label: "own" });
85
+ await insertOne(testDb.db, itemsTable, { tenantId: foreignTenant, label: "foreign" });
86
+
87
+ registry = createRegistry([jobsFeature]);
88
+ const redisUrl = `redis://${testRedis.redis.options.host}:${testRedis.redis.options.port}/${testRedis.redis.options.db}`;
89
+ jobRunner = createJobRunner({
90
+ registry,
91
+ context: {
92
+ db: testDb.db,
93
+ _escapeHatchAuditSink: async (event) => {
94
+ auditEvents.push(event);
95
+ },
96
+ },
97
+ redisUrl,
98
+ consumerLane: "worker",
99
+ queueNamePrefix: `kumiko-job-tenant-db-test-${Date.now()}`,
100
+ getActiveTenantIds: async () => [ownTenant],
101
+ });
102
+ await jobRunner.start();
103
+ });
104
+
105
+ afterAll(async () => {
106
+ await jobRunner.stop();
107
+ await testDb.cleanup();
108
+ await testRedis.cleanup();
109
+ });
110
+
111
+ describe("JobContext.db (fw#2914)", () => {
112
+ test("is tenant-filtered to the job's tenant and unsafeRaw is denied without escapeHatch", async () => {
113
+ outcomes.length = 0;
114
+ auditEvents.length = 0;
115
+ await jobRunner.dispatch("jobtenantdb:job:undeclared", { tenantId: ownTenant });
116
+
117
+ await waitFor(() => {
118
+ const outcome = outcomes.find((o) => o.job === "undeclared");
119
+ expect(outcome).toBeDefined();
120
+ expect(outcome?.mode).toBe("tenant");
121
+ expect(outcome?.tenantId).toBe(ownTenant);
122
+ expect(outcome?.labels).toEqual(["own"]);
123
+ expect(outcome?.foreignWhereLabels).toEqual(["own"]);
124
+ expect(outcome?.unsafeRawDenied).toBe(true);
125
+ });
126
+ expect(auditEvents).toHaveLength(0);
127
+ });
128
+
129
+ test("escapeHatch on r.job grants unfiltered access and reports one unsafe-raw audit event", async () => {
130
+ outcomes.length = 0;
131
+ auditEvents.length = 0;
132
+ await jobRunner.dispatch("jobtenantdb:job:declared", { tenantId: ownTenant });
133
+
134
+ await waitFor(() => {
135
+ const outcome = outcomes.find((o) => o.job === "declared");
136
+ expect(outcome?.rawLabels).toEqual(["foreign", "own"]);
137
+ expect(auditEvents).toHaveLength(1);
138
+ });
139
+ expect(auditEvents[0]).toMatchObject({
140
+ handler: "jobtenantdb:job:declared",
141
+ kind: "unsafe-raw",
142
+ reason: DECLARED_REASON,
143
+ tenantId: ownTenant,
144
+ });
145
+ });
146
+
147
+ test("r.job rejects an escapeHatch with an empty reason at registration", () => {
148
+ const register = () =>
149
+ defineFeature("jobtenantdb-empty", (r) => {
150
+ r.job("bad", { trigger: { manual: true }, escapeHatch: { reason: " " } }, async () => {});
151
+ });
152
+ expect(register).toThrow(/r\.job\("bad"\) declares \{ escapeHatch: \{ reason: "" \} \}/);
153
+ });
154
+
155
+ test("JobContext.db is not assignable to a raw DbRunner", () => {
156
+ const acceptsRunner = (runner: DbRunner): DbRunner => runner;
157
+ const ctx = { db: undefined } as unknown as JobContext;
158
+ // @ts-expect-error — JobContext.db is a TenantDb, not a raw DbRunner (fw#2914)
159
+ const leaked = () => acceptsRunner(ctx.db);
160
+ expect(typeof leaked).toBe("function");
161
+ });
162
+ });
@@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
2
  import { Queue } from "bullmq";
3
3
  import { z } from "zod";
4
4
  import { requestContext } from "../../api/request-context";
5
+ import { tenantDbRunner } from "../../db/tenant-db-runner";
5
6
  import { createRegistry, defineFeature } from "../../engine";
6
7
  import type {
7
8
  AppContext,
@@ -910,7 +911,7 @@ describe("perTenant across multiple runner instances", () => {
910
911
  async (_payload, ctx) => {
911
912
  log.push({
912
913
  tenantId: String(ctx.systemUser.tenantId),
913
- runnerTag: ctx.db as unknown as string, // @cast-boundary test fixture
914
+ runnerTag: tenantDbRunner(ctx.db) as unknown as string, // @cast-boundary test fixture — runner context db is a tag string
914
915
  });
915
916
  },
916
917
  );
@@ -1012,7 +1013,7 @@ describe("perTenant across multiple runner instances", () => {
1012
1013
  await sleep(80);
1013
1014
  log.push({
1014
1015
  tenantId: String(ctx.systemUser.tenantId),
1015
- runnerTag: ctx.db as unknown as string, // @cast-boundary test fixture
1016
+ runnerTag: tenantDbRunner(ctx.db) as unknown as string, // @cast-boundary test fixture — runner context db is a tag string
1016
1017
  });
1017
1018
  });
1018
1019
  });
@@ -2,7 +2,7 @@ import { Queue, Worker } from "bullmq";
2
2
  import { Redis } from "ioredis";
3
3
  import { requestContext } from "../api/request-context";
4
4
  import type { DbConnection, DbRow } from "../db/connection";
5
- import { createTenantDb, createUncheckedSystemDb } from "../db/tenant-db";
5
+ import { createTenantDb, createUncheckedSystemDb, type TenantDb } from "../db/tenant-db";
6
6
  import { createDerivativesContext } from "../derivatives/derivatives-context";
7
7
  import { createSystemUser } from "../engine/system-user";
8
8
  import {
@@ -551,20 +551,24 @@ export function createJobRunner(options: JobRunnerOptions): JobRunner {
551
551
  // unchecked cross-tenant escape hatch for such a job.
552
552
  const tenantScopedDb = configDb ? createTenantDb(configDb, tenantId, "system") : undefined;
553
553
  const isSystemJob = registry.isJobSystemScoped(jobName);
554
+ // One reporter for ctx.systemDb and ctx.db.unsafeRaw() so both dedupe in the same window.
555
+ const reportEscapeHatch = createEscapeHatchReporter({
556
+ handler: jobName,
557
+ tenantId,
558
+ actor: jobSystemUser.id,
559
+ sink: context._escapeHatchAuditSink,
560
+ log: context.log,
561
+ });
554
562
  const systemDb =
555
563
  isSystemJob && tenantScopedDb
556
- ? createUncheckedSystemDb(
557
- tenantScopedDb,
558
- undefined,
559
- createEscapeHatchReporter({
560
- handler: jobName,
561
- tenantId,
562
- actor: jobSystemUser.id,
563
- sink: context._escapeHatchAuditSink,
564
- log: context.log,
565
- }),
566
- )
564
+ ? createUncheckedSystemDb(tenantScopedDb, undefined, reportEscapeHatch)
567
565
  : undefined;
566
+ const jobDb = configDb
567
+ ? createTenantDb(configDb, tenantId, "tenant", context.tracer, context.meter, undefined, {
568
+ unsafeRaw: jobDef.escapeHatch,
569
+ report: reportEscapeHatch,
570
+ })
571
+ : undefined;
568
572
  const config =
569
573
  context._configAccessorFactory && tenantScopedDb
570
574
  ? context._configAccessorFactory({
@@ -589,9 +593,8 @@ export function createJobRunner(options: JobRunnerOptions): JobRunner {
589
593
  let memberReader: MemberReader | undefined;
590
594
  const jobContext: JobContext = {
591
595
  ...context,
592
- // Same union as configDb above — job runners are always constructed
593
- // with a real DbConnection; JobContext requires it non-optional.
594
- db: configDb as DbConnection, // @cast-boundary db-operator
596
+ // Undefined only for a runner built without a db; JobContext requires db non-optional.
597
+ db: jobDb as TenantDb, // @cast-boundary db-operator
595
598
  files,
596
599
  derivatives,
597
600
  ...(notify !== undefined && { notify }),