@cosmicdrift/kumiko-samples 0.424.0 → 0.424.1

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-samples",
3
- "version": "0.424.0",
3
+ "version": "0.424.1",
4
4
  "description": "Source trees of the Kumiko sample recipes, sample apps and bundled features in repo layout, for tooling such as few-shot corpus builds.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-bundled-features",
3
- "version": "0.424.0",
3
+ "version": "0.424.1",
4
4
  "description": "Built-in features — tenant, user, auth, delivery. The stuff you'd rewrite anyway, already typed.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -76,6 +76,8 @@ export type LoginResult =
76
76
 
77
77
  type Membership = { readonly tenantId: TenantId; readonly roles: readonly string[] };
78
78
 
79
+ const MembershipList = z.array(z.object({ tenantId: z.string(), roles: z.array(z.string()) }));
80
+
79
81
  // result is always a WriteFailure at construction (every reject() call site
80
82
  // passes one) — typing it that way, not WriteResult<LoginResult>, lets other
81
83
  // handlers with a different success-data type reuse these gates unchanged.
@@ -286,6 +288,56 @@ export async function gateBuildSession(
286
288
  return { kind: "auth-session", session };
287
289
  }
288
290
 
291
+ export type VerifiedUserLookup = { readonly email: string } | { readonly userId: string };
292
+
293
+ // Login gate chain AFTER an app-defined method (ID token, email code) proved
294
+ // the identity: account status, membership choice, claims. No password or
295
+ // lockout gate. A lookup by email requires a verified address,
296
+ // otherwise an attacker who pre-registered the victim's email with a known
297
+ // password would share the account the victim later reaches via this method.
298
+ // A lookup by userId trusts that the app linked the identity itself. There is
299
+ // no MFA gate: boot refuses to combine auth-mfa with sessionExchangeHandlers.
300
+ export async function sessionForVerifiedUser(
301
+ ctx: HandlerContext,
302
+ lookup: VerifiedUserLookup,
303
+ ): Promise<WriteResult<{ readonly kind: "auth-session"; readonly session: SessionUser }>> {
304
+ const systemUser = createSystemUser(SYSTEM_USER_ID);
305
+ const found = parseAuthUserRow(
306
+ await ctx.dispatch.queryAs(
307
+ systemUser,
308
+ UserQueries.findForAuth,
309
+ "email" in lookup ? { email: lookup.email } : { id: lookup.userId },
310
+ ),
311
+ );
312
+ if (!found || found.isDeleted) return invalidCredentials();
313
+
314
+ if ("email" in lookup) {
315
+ const emailGate = gateEnforceEmailVerified(found, true);
316
+ if (!emailGate.ok) return emailGate.result;
317
+ }
318
+
319
+ const statusGate = gateEnforceAccountStatus(found);
320
+ if (!statusGate.ok) return statusGate.result;
321
+
322
+ const memberships = MembershipList.parse(
323
+ await ctx.dispatch.queryAs(systemUser, TENANT_MEMBERSHIPS_QUERY, { userId: found.id }),
324
+ );
325
+
326
+ const membershipGate = await gateResolveMembership(ctx, found, memberships);
327
+ if (!membershipGate.ok) return membershipGate.result;
328
+ const { chosen, mergedRoles } = membershipGate.value;
329
+
330
+ const session = await gateBuildSession(
331
+ ctx,
332
+ found.id,
333
+ chosen.tenantId,
334
+ mergedRoles,
335
+ found.timezone,
336
+ found.locale,
337
+ );
338
+ return { isSuccess: true, data: session };
339
+ }
340
+
289
341
  // Login — unauthenticated entry point. The route is wired public (no JWT
290
342
  // middleware), dispatching with the framework's anonymous identity for the
291
343
  // handler's access check. Everything inside the handler goes through
@@ -31,6 +31,10 @@ export type {
31
31
  SignupOptions,
32
32
  } from "./feature.ts";
33
33
  export { authEmailPasswordEnvSchema, createAuthEmailPasswordFeature } from "./feature.ts";
34
+ export {
35
+ sessionForVerifiedUser,
36
+ type VerifiedUserLookup,
37
+ } from "./handlers/login.write.ts";
34
38
  export { AuthMailNotificationTypes } from "./mail-notifications.ts";
35
39
  export {
36
40
  AUTH_SELF_REGISTRATION_FEATURE,
@@ -1 +1,8 @@
1
- []
1
+ [
2
+ {
3
+ "version": "0.424.1",
4
+ "type": "fix",
5
+ "title": "resolveToken receives a typed db",
6
+ "detail": "The `ctx.db` passed to `resolveToken` is now typed as the delivery channel's `TenantDb` instead of `unknown`, so an app can query its device entity without a guard or cast. Existing callbacks that take `unknown` still compile."
7
+ }
8
+ ]
@@ -1,12 +1,11 @@
1
- import type { TenantId } from "@cosmicdrift/kumiko-framework/engine";
2
- import type { DeliveryChannel } from "../delivery/index.ts";
1
+ import type { ChannelContext, DeliveryChannel } from "../delivery/index.ts";
3
2
  import type { PushTransport } from "./types.ts";
4
3
 
5
4
  export type PushChannelOptions = {
6
5
  readonly transport: PushTransport;
7
6
  readonly resolveToken: (
8
7
  userId: string,
9
- ctx: { db: unknown; tenantId: TenantId },
8
+ ctx: Pick<ChannelContext, "db" | "tenantId">,
10
9
  ) => Promise<string | null>;
11
10
  };
12
11
 
@@ -0,0 +1,34 @@
1
+ # Sample: Session Exchange
2
+
3
+ **I want my own login method (Apple/Google ID token, email link) without rebuilding cookies, JWTs and rate limits.**
4
+
5
+ ## What this sample shows
6
+
7
+ An anonymous write handler verifies an identity and returns `{ kind: "auth-session", session }`. The app lists it under `auth.sessionExchangeHandlers`; `POST /api/auth/session-exchange` runs it and mints the session like `/auth/login` (token, cookies). The rate limit counts per IP and method and is not reset on success, because the route cannot tell whose code was right. By default it reuses the login limiter; set `auth.sessionExchangeRateLimit` to a larger limiter, or `null` to turn it off (for example when the methods carry signed tokens).
8
+
9
+ ## What to copy into your app
10
+
11
+ ```ts illustration
12
+ auth: {
13
+ membershipQuery: "tenant:query:memberships",
14
+ loginHandler: "auth-email-password:write:login",
15
+ sessionExchangeHandlers: { code: "demo-exchange:write:code" },
16
+ },
17
+ ```
18
+
19
+ The client calls `POST /api/auth/session-exchange` with `{ method: "code", payload: { ... } }`.
20
+
21
+ ## Design rules
22
+
23
+ 1. **Only listed handlers can issue a session.** The route resolves `method` against the map (own keys only); the handler QN never comes from the client.
24
+ 2. **The handler owns verification.** The demo compares a fixed code; a real handler verifies the ID token signature and audience first, then calls `sessionForVerifiedUser(ctx, { email })` (or `{ userId }`) for the login gates: account status, membership choice, claims. A lookup by email only issues a session for a verified address (otherwise a pre-registered attacker account would be taken over by the victim), a lookup by `userId` trusts your own identity link. There is no password or lockout gate, so accept only credentials that cannot be guessed: a signed ID token or a long random one-time token. A short code (six digits by mail) needs its own attempt counter per identity in the handler; the route only knows the IP, and a per-IP bucket does not stop a distributed guess. There is no MFA gate: boot aborts when `auth-mfa` is mounted together with `sessionExchangeHandlers`.
25
+ 3. **Anything but `auth-session` is rejected.** An MFA challenge or foreign result yields 500 and no cookie.
26
+ 4. **Errors map like login.** `details.reason` goes through `loginErrorStatusMap`.
27
+ 5. **Grant SYSTEM to the one handler, hide it from agents.** `escapeHatch: { grants: ["systemIdentity"] }` on the exchange handler, not `r.systemScope()` on the feature, and `agent: { expose: false }` because the payload is a credential.
28
+
29
+ ## Tests
30
+
31
+ - **End-to-end over HTTP:** exchange returns a token that authenticates a query
32
+ - **Wrong code:** 401 via `invalid_credentials`
33
+ - **Restricted user:** no session
34
+ - **Unknown method:** 400
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@cosmicdrift/kumiko-sample-session-exchange",
3
+ "description": "auth.sessionExchangeHandlers — app-defined login methods (ID token, email code) that the framework mints into a session.",
4
+ "private": true,
5
+ "dependencies": {
6
+ "@cosmicdrift/kumiko-bundled-features": "workspace:*",
7
+ "@cosmicdrift/kumiko-framework": "workspace:*"
8
+ },
9
+ "devDependencies": {
10
+ "@cosmicdrift/kumiko-testing": "workspace:*"
11
+ }
12
+ }
@@ -0,0 +1,54 @@
1
+ // Session Exchange Sample
2
+ //
3
+ // An app-defined login method: an anonymous write handler verifies an identity
4
+ // and returns { kind: "auth-session", session }; the framework route mints the
5
+ // session (token, cookies, rate limit) exactly like /auth/login.
6
+ //
7
+ // What to copy into your own app:
8
+ //
9
+ // auth: {
10
+ // membershipQuery: "tenant:query:memberships",
11
+ // sessionExchangeHandlers: { code: "demo-exchange:write:code" },
12
+ // },
13
+ //
14
+ // Only handlers listed in sessionExchangeHandlers can cause a session to be
15
+ // issued, so a handler that merely returns a session-shaped object elsewhere
16
+ // stays harmless. The demo code check stands in for verifying an ID token;
17
+ // sessionForVerifiedUser then runs the login gates after the identity proof
18
+ // (account status, membership choice, claims).
19
+
20
+ import { sessionForVerifiedUser } from "@cosmicdrift/kumiko-bundled-features/auth-email-password";
21
+ import { defineFeature } from "@cosmicdrift/kumiko-framework/engine";
22
+ import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
23
+ import { z } from "zod";
24
+
25
+ export const DEMO_EXCHANGE_CODE = "246810";
26
+ export const DEMO_EXCHANGE_QN = "demo-exchange:write:code";
27
+ export const INVALID_CREDENTIALS_REASON = "invalid_credentials";
28
+
29
+ export const demoExchangeFeature = defineFeature("demo-exchange", (r) => {
30
+ r.requires({ features: ["user", "tenant"] });
31
+
32
+ r.writeHandler({
33
+ name: "code",
34
+ schema: z.object({ email: z.email(), code: z.string().min(1) }),
35
+ access: { roles: ["anonymous"] },
36
+ escapeHatch: {
37
+ grants: ["systemIdentity"],
38
+ reason:
39
+ "Unauthenticated exchange has no caller identity yet — sessionForVerifiedUser looks up the user and resolves the membership as SYSTEM before a session exists.",
40
+ },
41
+ // The payload carries a credential (code or ID token) that must never enter an LLM transcript.
42
+ agent: { expose: false },
43
+ handler: async (event, ctx) => {
44
+ if (event.payload.code !== DEMO_EXCHANGE_CODE) {
45
+ return writeFailure(
46
+ new UnprocessableError(INVALID_CREDENTIALS_REASON, {
47
+ i18nKey: "demo-exchange.errors.invalidCredentials",
48
+ }),
49
+ );
50
+ }
51
+ return sessionForVerifiedUser(ctx, { email: event.payload.email });
52
+ },
53
+ });
54
+ });