@cosmicdrift/kumiko-framework 0.420.0 → 0.422.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.
@@ -77,7 +77,7 @@ type ActionFormPreview = { // Preview panel above the submit button: runs a quer
77
77
  };
78
78
  type ActionFormPreviewList = { // Rows of the preview panel, read from an array in the preview query's result.
79
79
  field: string; // Flat field name of an array in the query result; an entry that is no object is skipped.
80
- columns: { field: string; label: string; type?: ActionFormValueType; }[];
80
+ columns: { field: string; label: string; type?: ActionFormValueType | "file"; }[];
81
81
  };
82
82
  type ActionFormRedirect = { // Redirect target plus the success-payload field carrying the navigation id.
83
83
  screen: string; // Same target forms as the string `redirect`: short screen ID (same-feature) or a fully-qualified cross-feature screen QN.
@@ -1337,7 +1337,7 @@ type RenderEditProps<TValues extends FormValues, TCtx = unknown> = {
1337
1337
  schema?: z.ZodType;
1338
1338
  onSubmit?: (result: SubmitResult<unknown>, values: TValues) => void; // `values` are the form values at the moment the submit succeeded.
1339
1339
  payloadMode?: "values" | "changes";
1340
- buildPayload?: (snapshot: FormSnapshot<TValues>) => unknown;
1340
+ buildPayload?: (snapshot: FormSnapshot<TValues>, shapedValues: unknown) => unknown;
1341
1341
  serverFieldPathPrefix?: string; // Prefix to strip from server validation issue paths before mapping them onto form fields — see SubmitConfig.serverFieldPathPrefix.
1342
1342
  onDelete?: () => Promise<DispatcherError | void> | DispatcherError | void; // Returning the rejected write's error shows it in the form-error banner; returning nothing means the delete went through.
1343
1343
  onCancel?: () => void;
@@ -75,6 +75,7 @@ type AuthRoutesConfig = {
75
75
  trustedProxyHops?: number;
76
76
  postAuthLanding?: PostAuthLandingResolver;
77
77
  resolver?: ClientIpResolver;
78
+ previewLogin?: PreviewLoginConfig;
78
79
  };
79
80
  type EmailVerificationConfig = {
80
81
  requestHandler: string;
@@ -94,6 +95,10 @@ type PasswordResetConfig = {
94
95
  requestHandler: string;
95
96
  confirmHandler: string;
96
97
  };
98
+ type PreviewLoginConfig = {
99
+ loginKey: string;
100
+ resolveOwnerSession: (dispatcher: Dispatcher) => Promise<SessionUser | undefined>;
101
+ };
97
102
  type SessionChecker = AuthSessionChecker;
98
103
  type SessionCreator = (user: SessionUser, meta: SessionMetadata) => Promise<string>;
99
104
  type SessionMetadata = {
@@ -2166,7 +2171,7 @@ type SubmitConfig<TValues extends FormValues = FormValues> = {
2166
2171
  payloadMode?: SubmitPayloadMode;
2167
2172
  stripEmptySeeds?: boolean; // Only applies to payloadMode "values".
2168
2173
  omitFields?: string[]; // Top-level payload keys removed right before dispatch, for fields that are shown or validated but must not reach the write handler.
2169
- buildPayload?: (snapshot: FormSnapshot<TValues>) => unknown;
2174
+ buildPayload?: (snapshot: FormSnapshot<TValues>, shapedValues: unknown) => unknown;
2170
2175
  serverFieldPathPrefix?: string;
2171
2176
  validateScope?: string[]; // Restricts submit()'s internal validate() call to these field names — same contract as validate()'s `scope` param.
2172
2177
  };
@@ -35,7 +35,15 @@ the `table` block renders and behaves as before.
35
35
  updates every id in one write, bounded by `.max(MAX_BULK_SELECTION)` and
36
36
  reading each id through the tenant-scoped executor. The form has a `preview`:
37
37
  the `task:set-status-preview` query returns the affected tasks with old and
38
- new status from the same plan function the handler applies.
38
+ new status from the same plan function the handler applies. A preview list
39
+ column with `type: "file"` shows a FileRef id as file name and download link.
40
+ - `submitThrough`: a screen can open the form with
41
+ `useNavigateWithInitialValues(screen, values, { submitThrough: { handler:
42
+ "task-board:write:task:set-status-via", wrap: { via: "inbox" }, valuesKey:
43
+ "values" } })`. The submit then goes to `task:set-status-via` as
44
+ `{ via, values }`; that handler calls `task:set-status` through
45
+ `ctx.dispatch.write` and returns its data unchanged plus `via`, because the
46
+ form reads its redirect and success facts from the response.
39
47
  - `table.grouping`: the server groups the list by status; each header shows the
40
48
  group's count and estimate sum, "done" starts collapsed and the view menu
41
49
  offers grouping by priority or none.
@@ -359,6 +367,33 @@ describe("form bulk action handler", () => {
359
367
  ]);
360
368
  });
361
369
 
370
+ test("the submitThrough wrapper applies the inner write and passes its data through", async () => {
371
+ const created = await Promise.all(
372
+ ["Via A", "Via B"].map((title) =>
373
+ stack.http.writeOk<{ data: { id: string } }>(
374
+ "task-board:write:task:create",
375
+ { title },
376
+ user,
377
+ ),
378
+ ),
379
+ );
380
+ const taskIds = created.map((task) => task.data.id);
381
+ const result = await stack.http.writeOk<{ count: number; via: string }>(
382
+ "task-board:write:task:set-status-via",
383
+ { via: "inbox", values: { taskIds, status: "done" } },
384
+ user,
385
+ );
386
+ expect(result).toEqual({ count: 2, via: "inbox" });
387
+ const list = await stack.http.queryOk<{ rows: { title: string; status: string }[] }>(
388
+ "task-board:query:task:list",
389
+ { sort: "title" },
390
+ user,
391
+ );
392
+ expect(list.rows.filter((row) => row.title.startsWith("Via")).map((row) => row.status)).toEqual(
393
+ ["done", "done"],
394
+ );
395
+ });
396
+
362
397
  test("the preview query shows the same plan the handler applies", async () => {
363
398
  const created = await Promise.all(
364
399
  ["Plan A", "Plan B"].map((title) =>
@@ -372,13 +407,13 @@ describe("form bulk action handler", () => {
372
407
  const taskIds = created.map((task) => task.data.id);
373
408
  const preview = await stack.http.queryOk<{
374
409
  count: number;
375
- tasks: { title: string; before: string; after: string }[];
410
+ tasks: { title: string; before: string; after: string; attachmentId: null }[];
376
411
  }>("task-board:query:task:set-status-preview", { taskIds, status: "blocked" }, user);
377
412
  expect(preview).toEqual({
378
413
  count: 1,
379
414
  tasks: [
380
- { title: "Plan A", before: "open", after: "blocked" },
381
- { title: "Plan B", before: "blocked", after: "blocked" },
415
+ { title: "Plan A", before: "open", after: "blocked", attachmentId: null },
416
+ { title: "Plan B", before: "blocked", after: "blocked", attachmentId: null },
382
417
  ],
383
418
  });
384
419
  });
@@ -722,6 +757,26 @@ export function createTaskBoardFeature(
722
757
  },
723
758
  });
724
759
 
760
+ // Target of `useNavigateWithInitialValues(screen, values, { submitThrough })`: the form
761
+ // submits `{ ...wrap, [valuesKey]: values }` here. The wrapper returns the inner data
762
+ // unchanged (plus `via`) because the form reads its redirect id and success facts from it.
763
+ r.writeHandler({
764
+ name: "task:set-status-via",
765
+ schema: z.object({
766
+ via: z.string(),
767
+ values: setStatusInput.extend({ note: z.string().optional() }),
768
+ }),
769
+ access: openAccess.access,
770
+ handler: async (event, ctx) => {
771
+ const inner = await ctx.dispatch.write("task-board:write:task:set-status", {
772
+ ...event.payload.values,
773
+ });
774
+ if (!inner.isSuccess) return inner;
775
+ const innerData = typeof inner.data === "object" && inner.data !== null ? inner.data : {};
776
+ return { isSuccess: true as const, data: { ...innerData, via: event.payload.via } };
777
+ },
778
+ });
779
+
725
780
  // The preview runs the same plan the write handler runs, so the two cannot drift apart.
726
781
  r.queryHandler({
727
782
  name: "task:set-status-preview",
@@ -735,7 +790,12 @@ export function createTaskBoardFeature(
735
790
  if ("missingId" in plan) throw new NotFoundError("task");
736
791
  return {
737
792
  count: plan.rows.filter((row) => row.before !== row.after).length,
738
- tasks: plan.rows.map(({ title, before, after }) => ({ title, before, after })),
793
+ tasks: plan.rows.map(({ title, before, after }) => ({
794
+ title,
795
+ before,
796
+ after,
797
+ attachmentId: null,
798
+ })),
739
799
  };
740
800
  },
741
801
  });
@@ -768,6 +828,8 @@ export function createTaskBoardFeature(
768
828
  { field: "title", label: "Task" },
769
829
  { field: "before", label: "Now" },
770
830
  { field: "after", label: "New" },
831
+ // A FileRef id (null here) is shown with file name and download link.
832
+ { field: "attachmentId", label: "Attachment", type: "file" },
771
833
  ],
772
834
  },
773
835
  },
@@ -33,7 +33,14 @@ the boot with a clear message when the env is incomplete.
33
33
  signals to the host.
34
34
  - **`seeds`**: `{ demoTenant, demoAdminFromEnv, sysadminFromEnv, run }`
35
35
  replaces hand-written tenant and admin seeds; needs the auth features (not
36
- mounted here).
36
+ mounted here). `bootstrapAdminFromEnv: { ensureRoles: true }` adds roles
37
+ that `roles` gained since the first boot to the owner's existing membership
38
+ on every boot (additive, never removes).
39
+ - **`previewLogin`**: `{ loginKey }` mounts `GET /__kumiko/preview-login?exp=&sig=`,
40
+ which signs the bootstrap owner in (302 to `/`, the normal auth cookies) when
41
+ `sig` is the hex HMAC-SHA256 of `kumiko-preview-login:<exp>` under `loginKey`
42
+ and `exp` lies at most about 90 seconds ahead. Any other link answers 403.
43
+ Without the option or with an empty key the route does not exist.
37
44
  - **`billing`**: `{ stripe: { priceToTier }, defaultTier }` mounts the Stripe
38
45
  bridge and the tier-sync webhook route; needs `billing-foundation` and
39
46
  `tier-engine`.
@@ -99,6 +106,7 @@ const PRODUCTION_BOOT_ENV: Readonly<Record<string, string>> = {
99
106
  S3_REGION: "eu-central",
100
107
  S3_ACCESS_KEY: "access",
101
108
  S3_SECRET_KEY: "secret",
109
+ PREVIEW_LOGIN_KEY: "a".repeat(64),
102
110
  };
103
111
 
104
112
  function withoutKey(key: string): Record<string, string> {
@@ -156,6 +164,19 @@ describe("prod boot options recipe", () => {
156
164
  await expect(bootValidate(envSource)).rejects.toThrow(/kmsMode "required"/);
157
165
  });
158
166
  });
167
+
168
+ describe("prod boot options recipe: previewLogin", () => {
169
+ test("a loginKey shorter than 32 characters aborts the boot", async () => {
170
+ const logSpy = spyOn(console, "log").mockImplementation(() => {});
171
+ try {
172
+ await expect(
173
+ bootValidate({ ...PRODUCTION_BOOT_ENV, PREVIEW_LOGIN_KEY: "too-short" }),
174
+ ).rejects.toThrow(/previewLogin\.loginKey/);
175
+ } finally {
176
+ logSpy.mockRestore();
177
+ }
178
+ });
179
+ });
159
180
  ```
160
181
 
161
182
  ### src/app.ts
@@ -178,7 +199,7 @@ export function appFeatures(): RunProdAppOptions["features"] {
178
199
 
179
200
  type BootOptions = Pick<
180
201
  RunProdAppOptions,
181
- "mail" | "kmsMode" | "fileStorage" | "demoMode" | "signals"
202
+ "mail" | "kmsMode" | "fileStorage" | "demoMode" | "signals" | "previewLogin"
182
203
  >;
183
204
 
184
205
  export function bootOptions(envSource: Record<string, string | undefined>): BootOptions {
@@ -191,6 +212,8 @@ export function bootOptions(envSource: Record<string, string | undefined>): Boot
191
212
  notice: { text: { en: "This demo is read-only.", de: "Diese Demo ist schreibgeschützt." } },
192
213
  },
193
214
  signals: { drainTimeoutMs: 20_000 },
215
+ // Preview deployments only: the link signs the owner in without the MFA gate.
216
+ previewLogin: { loginKey: envSource["PREVIEW_LOGIN_KEY"] ?? "" },
194
217
  };
195
218
  }
196
219
  ```
@@ -0,0 +1,15 @@
1
+ import { Hono } from "hono";
2
+ import type { Dispatcher } from "../pipeline/dispatcher.ts";
3
+ import type { AuthRoutesConfig } from "./auth-routes-types.ts";
4
+ import type { JwtHelper } from "./jwt.ts";
5
+ export declare const PREVIEW_LOGIN_PATH = "/__kumiko/preview-login";
6
+ export declare function previewLoginSignature(loginKey: string, exp: string): string;
7
+ /** exp must lie in the future but no further than lifetime + tolerance, so a leaked key cannot mint long-lived links. */
8
+ export declare function isValidPreviewLoginLink(args: {
9
+ readonly loginKey: string;
10
+ readonly exp: string | undefined;
11
+ readonly sig: string | undefined;
12
+ readonly nowSeconds: number;
13
+ }): boolean;
14
+ /** Separate from createAuthRoutes: the path lies outside /api, so it must not ride the /api guard chain. */
15
+ export declare function createPreviewLoginRoutes(dispatcher: Dispatcher, jwt: JwtHelper, config: AuthRoutesConfig): Hono | undefined;
@@ -0,0 +1,77 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { Hono } from "hono";
3
+ import { createFallbackLogger } from "../logging/utils.js";
4
+ import { createAuthRouteContext } from "./auth-routes-context.js";
5
+ const log = createFallbackLogger("preview-login");
6
+ export const PREVIEW_LOGIN_PATH = "/__kumiko/preview-login";
7
+ const PREVIEW_LOGIN_LIFETIME_SECONDS = 60;
8
+ const PREVIEW_LOGIN_CLOCK_TOLERANCE_SECONDS = 30;
9
+ const EXP_FORMAT = /^\d{1,12}$/;
10
+ const SIG_FORMAT = /^[0-9a-fA-F]{64}$/;
11
+ export function previewLoginSignature(loginKey, exp) {
12
+ return createHmac("sha256", loginKey).update(`kumiko-preview-login:${exp}`).digest("hex");
13
+ }
14
+ /** exp must lie in the future but no further than lifetime + tolerance, so a leaked key cannot mint long-lived links. */
15
+ export function isValidPreviewLoginLink(args) {
16
+ const { loginKey, exp, sig, nowSeconds } = args;
17
+ if (loginKey === "" || exp === undefined || sig === undefined)
18
+ return false;
19
+ if (!EXP_FORMAT.test(exp) || !SIG_FORMAT.test(sig))
20
+ return false;
21
+ const expSeconds = Number(exp);
22
+ if (expSeconds <= nowSeconds)
23
+ return false;
24
+ if (expSeconds >
25
+ nowSeconds + PREVIEW_LOGIN_LIFETIME_SECONDS + PREVIEW_LOGIN_CLOCK_TOLERANCE_SECONDS) {
26
+ return false;
27
+ }
28
+ const expected = Buffer.from(previewLoginSignature(loginKey, exp), "hex");
29
+ const given = Buffer.from(sig, "hex");
30
+ return expected.length === given.length && timingSafeEqual(expected, given);
31
+ }
32
+ // ponytail: per-process single-use store (sig -> exp seconds); enough for a one-instance preview,
33
+ // use a shared KV (Redis SET NX) if previews ever run multi-instance.
34
+ function consumeOnce(consumedSigs, sig, expSeconds) {
35
+ const now = Math.floor(Date.now() / 1000);
36
+ for (const [key, exp] of consumedSigs) {
37
+ if (exp + PREVIEW_LOGIN_CLOCK_TOLERANCE_SECONDS < now)
38
+ consumedSigs.delete(key);
39
+ }
40
+ if (consumedSigs.has(sig))
41
+ return false;
42
+ consumedSigs.set(sig, expSeconds);
43
+ return true;
44
+ }
45
+ /** Separate from createAuthRoutes: the path lies outside /api, so it must not ride the /api guard chain. */
46
+ export function createPreviewLoginRoutes(dispatcher, jwt, config) {
47
+ const previewLogin = config.previewLogin;
48
+ if (previewLogin === undefined || previewLogin.loginKey === "")
49
+ return undefined;
50
+ const ctx = createAuthRouteContext(dispatcher, jwt, config);
51
+ const consumedSigs = new Map();
52
+ const app = new Hono();
53
+ app.get(PREVIEW_LOGIN_PATH, async (c) => {
54
+ c.header("Cache-Control", "no-store");
55
+ const valid = isValidPreviewLoginLink({
56
+ loginKey: previewLogin.loginKey,
57
+ exp: c.req.query("exp"),
58
+ sig: c.req.query("sig"),
59
+ nowSeconds: Math.floor(Date.now() / 1000),
60
+ });
61
+ if (!valid)
62
+ return c.body(null, 403);
63
+ const sig = (c.req.query("sig") ?? "").toLowerCase();
64
+ if (!consumeOnce(consumedSigs, sig, Number(c.req.query("exp"))))
65
+ return c.body(null, 403);
66
+ const owner = await previewLogin.resolveOwnerSession(dispatcher);
67
+ if (owner === undefined) {
68
+ consumedSigs.delete(sig);
69
+ log.error("preview login refused: the owner account is missing or not active");
70
+ return c.body(null, 503);
71
+ }
72
+ const claims = await dispatcher.resolveAuthClaims(owner);
73
+ await ctx.mintSessionAndRespond(c, Object.keys(claims).length > 0 ? { ...owner, claims } : owner);
74
+ return c.redirect("/", 302);
75
+ });
76
+ return app;
77
+ }
@@ -1,4 +1,5 @@
1
1
  import type { SessionUser } from "../engine/types/index.ts";
2
+ import type { Dispatcher } from "../pipeline/dispatcher.ts";
2
3
  import type { AuthSessionChecker, TokenVerifier } from "./auth-middleware.ts";
3
4
  import type { ClientIpResolver } from "./client-ip.ts";
4
5
  import type { PostAuthLandingResolver } from "./post-auth-landing.ts";
@@ -51,6 +52,11 @@ export type AuthRoutesConfig = {
51
52
  trustedProxyHops?: number;
52
53
  postAuthLanding?: PostAuthLandingResolver;
53
54
  resolver?: ClientIpResolver;
55
+ previewLogin?: PreviewLoginConfig;
56
+ };
57
+ export type PreviewLoginConfig = {
58
+ readonly loginKey: string;
59
+ readonly resolveOwnerSession: (dispatcher: Dispatcher) => Promise<SessionUser | undefined>;
54
60
  };
55
61
  export type PasswordResetConfig = {
56
62
  requestHandler: string;
@@ -9,6 +9,7 @@ import { collectAnonymousLiveEntities } from "./anonymous-live-entities.js";
9
9
  import { NO_ROUTE_MATCH_HEADER_NAME } from "./api-constants.js";
10
10
  import { identifyOptionalSession } from "./auth-middleware.js";
11
11
  import { createAuthRoutes } from "./auth-routes.js";
12
+ import { createPreviewLoginRoutes } from "./auth-routes-preview-login.js";
12
13
  import { createClientErrorRoute } from "./client-error-route.js";
13
14
  import { collectEntityReadAccess, collectEntityRowReadMaps } from "./entity-read-access.js";
14
15
  import { createExportRoutes } from "./export/export-route.js";
@@ -44,6 +45,13 @@ export function mountAuthRoutes(app, wiring, sessionCookies) {
44
45
  secureCookies: sessionCookies.secure,
45
46
  resolver: clientIpResolver,
46
47
  }));
48
+ const previewLogin = createPreviewLoginRoutes(dispatcher, jwt, {
49
+ ...options.auth,
50
+ secureCookies: sessionCookies.secure,
51
+ resolver: clientIpResolver,
52
+ });
53
+ if (previewLogin)
54
+ app.route("/", previewLogin);
47
55
  }
48
56
  }
49
57
  export function mountClientErrorRoute(app, wiring) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-framework",
3
- "version": "0.420.0",
3
+ "version": "0.422.0",
4
4
  "description": "Framework core — engine, pipeline, API, DB, and every other bit that makes Kumiko go.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -204,7 +204,7 @@
204
204
  "./package.json": "./package.json"
205
205
  },
206
206
  "dependencies": {
207
- "@cosmicdrift/kumiko-types": "0.420.0",
207
+ "@cosmicdrift/kumiko-types": "0.422.0",
208
208
  "bullmq": "^5.81.5",
209
209
  "hono": "^4.13.14",
210
210
  "i18next": "^26.5.12",
@@ -226,7 +226,7 @@
226
226
  }
227
227
  },
228
228
  "devDependencies": {
229
- "@cosmicdrift/kumiko-testing": "0.420.0",
229
+ "@cosmicdrift/kumiko-testing": "0.422.0",
230
230
  "bun-types": "^1.4.4",
231
231
  "fflate": "^0.8.3",
232
232
  "meilisearch": "^0.62.0",