@cosmicdrift/kumiko-framework 0.420.0 → 0.421.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.
@@ -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 = {
@@ -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.421.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.421.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.421.0",
230
230
  "bun-types": "^1.4.4",
231
231
  "fflate": "^0.8.3",
232
232
  "meilisearch": "^0.62.0",