@cosmicdrift/kumiko-framework 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/agents/api/framework-ui-types.md +1 -1
- package/agents/api/renderer-web.md +2 -2
- package/agents/api/types.md +2 -0
- package/agents/examples/session-exchange.md +253 -0
- package/agents/examples.md +1 -0
- package/dist/api/api-constants.d.ts +1 -0
- package/dist/api/api-constants.js +2 -0
- package/dist/api/auth-routes-login.js +2 -5
- package/dist/api/auth-routes-mfa.js +4 -15
- package/dist/api/auth-routes-session-exchange.d.ts +2 -0
- package/dist/api/auth-routes-session-exchange.js +74 -0
- package/dist/api/auth-routes-shared.d.ts +12 -0
- package/dist/api/auth-routes-shared.js +15 -0
- package/dist/api/auth-routes-types.d.ts +2 -0
- package/dist/api/auth-routes.js +2 -0
- package/package.json +3 -3
- package/src/changes.json +6 -0
|
@@ -65,7 +65,7 @@ type ActionFormLoad = {
|
|
|
65
65
|
query: string; // Query QN that returns the record.
|
|
66
66
|
idParam?: string; // Payload key carrying the record id (default "id").
|
|
67
67
|
singleton?: boolean; // The query picks the row from the caller's tenant/session context, so the form loads without a record id and the query is called WITHOUT `idParam` (same semantics as `ProjectionDetailScreenDefinition.singleton`).
|
|
68
|
-
passPrefill?: boolean; // Sends the values
|
|
68
|
+
passPrefill?: boolean; // Sends the values the form is opened with, from a drawer (row-action params, e.g. `vehicleId`) or a navigation handoff (e.g. an assistant step's values), in the load payload next to `idParam`, so the query can pre-fill for the chosen item.
|
|
69
69
|
};
|
|
70
70
|
type ActionFormPreview = { // Preview panel above the submit button: runs a query over the current form values and shows what the submit would do.
|
|
71
71
|
query: string; // Query QN.
|
|
@@ -506,7 +506,7 @@ type DefaultAppShellProps = {
|
|
|
506
506
|
navBadges?: ReadonlyMap<string, ReactNode>; // Runtime badges per navigation item (bare nav-id → ReactNode), passed through to NavTree.
|
|
507
507
|
headerActions?: ReactNode; // Right-aligned slot in the topbar (next to the breadcrumb) — for ThemeToggle, global actions, and similar controls.
|
|
508
508
|
sidebarFooter?: ReactNode; // Footer slot at the bottom of the sidebar — profile row, help link, or plan banner.
|
|
509
|
-
focusRailNavQns?: string[]; //
|
|
509
|
+
focusRailNavQns?: string[]; // Nav QNs (any depth) the focus rail shows as tiles, in this order; unlisted top-level entries sit behind a "More" tile that opens the full sidebar.
|
|
510
510
|
fill?: boolean; // Viewport-fit shell.
|
|
511
511
|
children: ReactNode; // Screen content rendered inside SidebarInset.
|
|
512
512
|
};
|
|
@@ -1820,7 +1820,7 @@ type WorkspaceShellProps = {
|
|
|
1820
1820
|
user?: WorkspaceShellUser; // Current user.
|
|
1821
1821
|
initialWorkspaceId?: string; // Initial active workspace short id ("admin").
|
|
1822
1822
|
sidebarFooter?: ReactNode; // Footer slot at the bottom of the sidebar — profile row, help link, build information.
|
|
1823
|
-
focusRailNavQns?: string[]; //
|
|
1823
|
+
focusRailNavQns?: string[]; // Nav QNs (any depth) the focus rail shows as tiles, in this order; unlisted top-level entries sit behind a "More" tile that opens the full sidebar.
|
|
1824
1824
|
navBadges?: ReadonlyMap<string, ReactNode>; // Runtime badge slot per nav leaf (bare nav id), same as DefaultAppShell.
|
|
1825
1825
|
fill?: boolean; // Viewport-fit shell.
|
|
1826
1826
|
contentSurface?: "card" | "background"; // Surface behind the screen content.
|
package/agents/api/types.md
CHANGED
|
@@ -42,8 +42,10 @@ type AuthRoutesConfig = {
|
|
|
42
42
|
membershipQuery: string;
|
|
43
43
|
userQuery?: string;
|
|
44
44
|
loginHandler?: string;
|
|
45
|
+
sessionExchangeHandlers?: Readonly<Record<string, string>>;
|
|
45
46
|
loginErrorStatusMap?: Readonly<Record<string, number>>;
|
|
46
47
|
loginRateLimit?: LoginRateLimiter | null;
|
|
48
|
+
sessionExchangeRateLimit?: LoginRateLimiter | null;
|
|
47
49
|
mfaVerifyHandler?: string;
|
|
48
50
|
switchTenantMfaGateHandler?: string;
|
|
49
51
|
mfaVerifyErrorStatusMap?: Readonly<Record<string, number>>;
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
<!-- Generated by `bun run gen:agent-docs` from samples/recipes/session-exchange. Do not edit. -->
|
|
2
|
+
|
|
3
|
+
# session-exchange
|
|
4
|
+
|
|
5
|
+
auth.sessionExchangeHandlers — app-defined login methods (ID token, email code) that the framework mints into a session.
|
|
6
|
+
|
|
7
|
+
## README
|
|
8
|
+
|
|
9
|
+
# Sample: Session Exchange
|
|
10
|
+
|
|
11
|
+
**I want my own login method (Apple/Google ID token, email link) without rebuilding cookies, JWTs and rate limits.**
|
|
12
|
+
|
|
13
|
+
## What this sample shows
|
|
14
|
+
|
|
15
|
+
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).
|
|
16
|
+
|
|
17
|
+
## What to copy into your app
|
|
18
|
+
|
|
19
|
+
```ts illustration
|
|
20
|
+
auth: {
|
|
21
|
+
membershipQuery: "tenant:query:memberships",
|
|
22
|
+
loginHandler: "auth-email-password:write:login",
|
|
23
|
+
sessionExchangeHandlers: { code: "demo-exchange:write:code" },
|
|
24
|
+
},
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The client calls `POST /api/auth/session-exchange` with `{ method: "code", payload: { ... } }`.
|
|
28
|
+
|
|
29
|
+
## Design rules
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
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`.
|
|
33
|
+
3. **Anything but `auth-session` is rejected.** An MFA challenge or foreign result yields 500 and no cookie.
|
|
34
|
+
4. **Errors map like login.** `details.reason` goes through `loginErrorStatusMap`.
|
|
35
|
+
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.
|
|
36
|
+
|
|
37
|
+
## Tests
|
|
38
|
+
|
|
39
|
+
- **End-to-end over HTTP:** exchange returns a token that authenticates a query
|
|
40
|
+
- **Wrong code:** 401 via `invalid_credentials`
|
|
41
|
+
- **Restricted user:** no session
|
|
42
|
+
- **Unknown method:** 400
|
|
43
|
+
|
|
44
|
+
## Source files
|
|
45
|
+
|
|
46
|
+
### src/__tests__/feature.integration.test.ts
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
// Session Exchange Sample — Integration Test
|
|
50
|
+
//
|
|
51
|
+
// Real HTTP + DB: an app-defined exchange handler is listed under
|
|
52
|
+
// auth.sessionExchangeHandlers and the framework route mints the session.
|
|
53
|
+
|
|
54
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
55
|
+
import { AuthErrors, hashPassword } from "@cosmicdrift/kumiko-bundled-features/auth-email-password";
|
|
56
|
+
import {
|
|
57
|
+
configValuesTable,
|
|
58
|
+
createConfigFeature,
|
|
59
|
+
} from "@cosmicdrift/kumiko-bundled-features/config";
|
|
60
|
+
import {
|
|
61
|
+
createTenantFeature,
|
|
62
|
+
tenantEntity,
|
|
63
|
+
tenantMembershipsTable,
|
|
64
|
+
} from "@cosmicdrift/kumiko-bundled-features/tenant";
|
|
65
|
+
import { seedTenantMembership } from "@cosmicdrift/kumiko-bundled-features/tenant/seeding";
|
|
66
|
+
import {
|
|
67
|
+
createUserFeature,
|
|
68
|
+
USER_STATUS,
|
|
69
|
+
UserHandlers,
|
|
70
|
+
userEntity,
|
|
71
|
+
} from "@cosmicdrift/kumiko-bundled-features/user";
|
|
72
|
+
import { updateUserViaEventStore } from "@cosmicdrift/kumiko-bundled-features/user/testing";
|
|
73
|
+
import type { TenantId } from "@cosmicdrift/kumiko-framework/engine";
|
|
74
|
+
import { TestUsers, testTenantId } from "@cosmicdrift/kumiko-framework/seeding";
|
|
75
|
+
import {
|
|
76
|
+
setupTestStack,
|
|
77
|
+
type TestStack,
|
|
78
|
+
unsafeCreateEntityTable,
|
|
79
|
+
unsafePushTables,
|
|
80
|
+
} from "@cosmicdrift/kumiko-testing/stack";
|
|
81
|
+
import {
|
|
82
|
+
DEMO_EXCHANGE_CODE,
|
|
83
|
+
DEMO_EXCHANGE_QN,
|
|
84
|
+
demoExchangeFeature,
|
|
85
|
+
INVALID_CREDENTIALS_REASON,
|
|
86
|
+
} from "../feature";
|
|
87
|
+
|
|
88
|
+
const TENANT: TenantId = testTenantId(1);
|
|
89
|
+
const EMAIL = "exchange@example.com";
|
|
90
|
+
|
|
91
|
+
let stack: TestStack;
|
|
92
|
+
|
|
93
|
+
beforeAll(async () => {
|
|
94
|
+
stack = await setupTestStack({
|
|
95
|
+
features: [
|
|
96
|
+
createConfigFeature(),
|
|
97
|
+
createUserFeature(),
|
|
98
|
+
createTenantFeature(),
|
|
99
|
+
demoExchangeFeature,
|
|
100
|
+
],
|
|
101
|
+
authConfig: {
|
|
102
|
+
membershipQuery: "tenant:query:memberships",
|
|
103
|
+
sessionExchangeHandlers: { code: DEMO_EXCHANGE_QN },
|
|
104
|
+
loginErrorStatusMap: { [INVALID_CREDENTIALS_REASON]: 401 },
|
|
105
|
+
loginRateLimit: null,
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
await unsafeCreateEntityTable(stack.db, userEntity);
|
|
110
|
+
await unsafeCreateEntityTable(stack.db, tenantEntity);
|
|
111
|
+
await unsafePushTables(stack.db, { configValuesTable, tenantMembershipsTable });
|
|
112
|
+
|
|
113
|
+
await createMember(EMAIL, { verified: true });
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
async function createMember(email: string, opts: { verified: boolean }): Promise<string> {
|
|
117
|
+
const created = await stack.http.writeOk<{ id: string }>(
|
|
118
|
+
UserHandlers.create,
|
|
119
|
+
{
|
|
120
|
+
email,
|
|
121
|
+
passwordHash: await hashPassword("super-long-password"),
|
|
122
|
+
displayName: "Exchange",
|
|
123
|
+
},
|
|
124
|
+
TestUsers.systemAdmin,
|
|
125
|
+
);
|
|
126
|
+
await seedTenantMembership(stack.db, { userId: created.id, tenantId: TENANT, roles: ["User"] });
|
|
127
|
+
if (opts.verified) {
|
|
128
|
+
await updateUserViaEventStore(stack.db, created.id, { emailVerified: true });
|
|
129
|
+
}
|
|
130
|
+
return created.id;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
afterAll(async () => {
|
|
134
|
+
await stack.cleanup();
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
function exchange(body: unknown): Promise<Response> {
|
|
138
|
+
return stack.http.raw("POST", "/api/auth/session-exchange", body);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
describe("session-exchange sample wiring", () => {
|
|
142
|
+
test("valid code mints a token that authenticates a query", async () => {
|
|
143
|
+
const res = await exchange({
|
|
144
|
+
method: "code",
|
|
145
|
+
payload: { email: EMAIL, code: DEMO_EXCHANGE_CODE },
|
|
146
|
+
});
|
|
147
|
+
expect(res.status).toBe(200);
|
|
148
|
+
const { token } = (await res.json()) as { token: string };
|
|
149
|
+
expect(token.length).toBeGreaterThan(20);
|
|
150
|
+
|
|
151
|
+
const me = await stack.http.raw(
|
|
152
|
+
"POST",
|
|
153
|
+
"/api/query",
|
|
154
|
+
{ type: "user:query:user:me", payload: {} },
|
|
155
|
+
{ Authorization: `Bearer ${token}` },
|
|
156
|
+
);
|
|
157
|
+
expect(me.status).toBe(200);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("wrong code is 401 via invalid_credentials", async () => {
|
|
161
|
+
const res = await exchange({ method: "code", payload: { email: EMAIL, code: "000000" } });
|
|
162
|
+
expect(res.status).toBe(401);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("a restricted user gets no session", async () => {
|
|
166
|
+
const restrictedId = await createMember("restricted@example.com", { verified: true });
|
|
167
|
+
await updateUserViaEventStore(stack.db, restrictedId, { status: USER_STATUS.Restricted });
|
|
168
|
+
|
|
169
|
+
const res = await exchange({
|
|
170
|
+
method: "code",
|
|
171
|
+
payload: { email: "restricted@example.com", code: DEMO_EXCHANGE_CODE },
|
|
172
|
+
});
|
|
173
|
+
expect(res.status).toBeGreaterThanOrEqual(400);
|
|
174
|
+
expect(res.headers.getSetCookie()).toEqual([]);
|
|
175
|
+
expect(((await res.json()) as { token?: string }).token).toBeUndefined();
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
test("an unverified email gets no session", async () => {
|
|
179
|
+
await createMember("unverified@example.com", { verified: false });
|
|
180
|
+
const res = await exchange({
|
|
181
|
+
method: "code",
|
|
182
|
+
payload: { email: "unverified@example.com", code: DEMO_EXCHANGE_CODE },
|
|
183
|
+
});
|
|
184
|
+
expect(res.status).toBe(422);
|
|
185
|
+
expect(res.headers.getSetCookie()).toEqual([]);
|
|
186
|
+
expect(JSON.stringify(await res.json())).toContain(AuthErrors.emailNotVerified);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test("unknown method is 400", async () => {
|
|
190
|
+
const res = await exchange({ method: "other", payload: {} });
|
|
191
|
+
expect(res.status).toBe(400);
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### src/feature.ts
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
// Session Exchange Sample
|
|
200
|
+
//
|
|
201
|
+
// An app-defined login method: an anonymous write handler verifies an identity
|
|
202
|
+
// and returns { kind: "auth-session", session }; the framework route mints the
|
|
203
|
+
// session (token, cookies, rate limit) exactly like /auth/login.
|
|
204
|
+
//
|
|
205
|
+
// What to copy into your own app:
|
|
206
|
+
//
|
|
207
|
+
// auth: {
|
|
208
|
+
// membershipQuery: "tenant:query:memberships",
|
|
209
|
+
// sessionExchangeHandlers: { code: "demo-exchange:write:code" },
|
|
210
|
+
// },
|
|
211
|
+
//
|
|
212
|
+
// Only handlers listed in sessionExchangeHandlers can cause a session to be
|
|
213
|
+
// issued, so a handler that merely returns a session-shaped object elsewhere
|
|
214
|
+
// stays harmless. The demo code check stands in for verifying an ID token;
|
|
215
|
+
// sessionForVerifiedUser then runs the login gates after the identity proof
|
|
216
|
+
// (account status, membership choice, claims).
|
|
217
|
+
|
|
218
|
+
import { sessionForVerifiedUser } from "@cosmicdrift/kumiko-bundled-features/auth-email-password";
|
|
219
|
+
import { defineFeature } from "@cosmicdrift/kumiko-framework/engine";
|
|
220
|
+
import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
|
|
221
|
+
import { z } from "zod";
|
|
222
|
+
|
|
223
|
+
export const DEMO_EXCHANGE_CODE = "246810";
|
|
224
|
+
export const DEMO_EXCHANGE_QN = "demo-exchange:write:code";
|
|
225
|
+
export const INVALID_CREDENTIALS_REASON = "invalid_credentials";
|
|
226
|
+
|
|
227
|
+
export const demoExchangeFeature = defineFeature("demo-exchange", (r) => {
|
|
228
|
+
r.requires({ features: ["user", "tenant"] });
|
|
229
|
+
|
|
230
|
+
r.writeHandler({
|
|
231
|
+
name: "code",
|
|
232
|
+
schema: z.object({ email: z.email(), code: z.string().min(1) }),
|
|
233
|
+
access: { roles: ["anonymous"] },
|
|
234
|
+
escapeHatch: {
|
|
235
|
+
grants: ["systemIdentity"],
|
|
236
|
+
reason:
|
|
237
|
+
"Unauthenticated exchange has no caller identity yet — sessionForVerifiedUser looks up the user and resolves the membership as SYSTEM before a session exists.",
|
|
238
|
+
},
|
|
239
|
+
// The payload carries a credential (code or ID token) that must never enter an LLM transcript.
|
|
240
|
+
agent: { expose: false },
|
|
241
|
+
handler: async (event, ctx) => {
|
|
242
|
+
if (event.payload.code !== DEMO_EXCHANGE_CODE) {
|
|
243
|
+
return writeFailure(
|
|
244
|
+
new UnprocessableError(INVALID_CREDENTIALS_REASON, {
|
|
245
|
+
i18nKey: "demo-exchange.errors.invalidCredentials",
|
|
246
|
+
}),
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
return sessionForVerifiedUser(ctx, { email: event.payload.email });
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
```
|
package/agents/examples.md
CHANGED
|
@@ -75,6 +75,7 @@
|
|
|
75
75
|
| `secrets-demo` | Tenant-owned secrets with envelope encryption, DEK cache, and KEK rotation. | `examples/secrets-demo.md` |
|
|
76
76
|
| `security-baseline` | composeSecurityStack(): sessions, crypto-shredding, rate-limiting, audit — plus the NODE_ENV=production boot warning when one is missing. | `examples/security-baseline.md` |
|
|
77
77
|
| `seed-migration` | ES-Operations seed-migrations — file-based diff-and-apply für Aggregate-Updates die idempotent-Seeder nicht erfassen. | `examples/seed-migration.md` |
|
|
78
|
+
| `session-exchange` | auth.sessionExchangeHandlers — app-defined login methods (ID token, email code) that the framework mints into a session. | `examples/session-exchange.md` |
|
|
78
79
|
| `session-revocation` | createSessionCallbacks + sessionChecker — server-side session revocation via JWT jti. | `examples/session-revocation.md` |
|
|
79
80
|
| `signature` | The signature bundled feature: a request for several signers, a signing link that is delivered by the app, and a completed PDF with a signature page. | `examples/signature.md` |
|
|
80
81
|
| `state-machine` | Enforced entity state transitions. No more illegal state changes. | `examples/state-machine.md` |
|
|
@@ -11,6 +11,7 @@ export declare const Routes: {
|
|
|
11
11
|
readonly exportXlsx: "/export/xlsx";
|
|
12
12
|
readonly auth: "/auth";
|
|
13
13
|
readonly authLogin: "/auth/login";
|
|
14
|
+
readonly authSessionExchange: "/auth/session-exchange";
|
|
14
15
|
readonly authMfaVerify: "/auth/mfa/verify";
|
|
15
16
|
readonly authMfaPreauthEnableStart: "/auth/mfa/preauth-enable-start";
|
|
16
17
|
readonly authMfaPreauthConfirm: "/auth/mfa/preauth-confirm";
|
|
@@ -13,6 +13,7 @@ export const Routes = {
|
|
|
13
13
|
exportXlsx: "/export/xlsx",
|
|
14
14
|
auth: "/auth",
|
|
15
15
|
authLogin: "/auth/login",
|
|
16
|
+
authSessionExchange: "/auth/session-exchange",
|
|
16
17
|
authMfaVerify: "/auth/mfa/verify",
|
|
17
18
|
authMfaPreauthEnableStart: "/auth/mfa/preauth-enable-start",
|
|
18
19
|
authMfaPreauthConfirm: "/auth/mfa/preauth-confirm",
|
|
@@ -43,6 +44,7 @@ export const Routes = {
|
|
|
43
44
|
// The auth middleware skips these paths.
|
|
44
45
|
export const PUBLIC_API_PATHS = new Set([
|
|
45
46
|
`/api${Routes.authLogin}`,
|
|
47
|
+
`/api${Routes.authSessionExchange}`,
|
|
46
48
|
`/api${Routes.authMfaVerify}`,
|
|
47
49
|
`/api${Routes.authMfaPreauthEnableStart}`,
|
|
48
50
|
`/api${Routes.authMfaPreauthConfirm}`,
|
|
@@ -3,6 +3,7 @@ import { createAnonymousUser } from "../engine/system-user.js";
|
|
|
3
3
|
import { SYSTEM_TENANT_ID } from "../engine/types/index.js";
|
|
4
4
|
import { Routes } from "./api-constants.js";
|
|
5
5
|
import { inMemoryLoginRateLimiterFallback } from "./auth-rate-limiters.js";
|
|
6
|
+
import { handlerFailureResponse } from "./auth-routes-shared.js";
|
|
6
7
|
// Body schema for POST /auth/login. Enforced BEFORE rate-limit so that a
|
|
7
8
|
// malformed body (`email: 42`, missing password, …) returns 400 instead of
|
|
8
9
|
// crashing on `.toLowerCase()` and leaking a 500 that never increments the
|
|
@@ -47,11 +48,7 @@ export function registerLoginRoute(ctx) {
|
|
|
47
48
|
// Feature-specific auth reason codes arrive via UnprocessableError.details.reason
|
|
48
49
|
// (e.g. "invalid_credentials", "user_locked"). Fall back to the KumikoError code
|
|
49
50
|
// so unmapped cases still get a sensible status.
|
|
50
|
-
|
|
51
|
-
const reason = result.error.details?.reason ?? result.error.code;
|
|
52
|
-
// @cast-boundary engine-payload — statusMap value union narrows to the http-status union
|
|
53
|
-
const status = (statusMap[reason] ?? result.error.httpStatus);
|
|
54
|
-
return c.json({ isSuccess: false, error: result.error }, status);
|
|
51
|
+
return handlerFailureResponse(c, result.error, statusMap);
|
|
55
52
|
}
|
|
56
53
|
// @cast-boundary engine-payload — generic dispatcher.write result for
|
|
57
54
|
// login. Three possible shapes: a straight session, an MFA challenge
|
|
@@ -4,6 +4,7 @@ import { createAnonymousUser } from "../engine/system-user.js";
|
|
|
4
4
|
import { SYSTEM_TENANT_ID } from "../engine/types/index.js";
|
|
5
5
|
import { Routes } from "./api-constants.js";
|
|
6
6
|
import { inMemoryLoginRateLimiterFallback } from "./auth-rate-limiters.js";
|
|
7
|
+
import { handlerFailureResponse } from "./auth-routes-shared.js";
|
|
7
8
|
// Body schema for POST /auth/mfa/verify. challengeToken is opaque to the
|
|
8
9
|
// framework — it's minted and verified entirely by the mfaVerifyHandler
|
|
9
10
|
// (auth-mfa owns the token format, TOTP/recovery-code check, and the
|
|
@@ -70,11 +71,7 @@ export function registerMfaVerifyRoute(ctx) {
|
|
|
70
71
|
}
|
|
71
72
|
const result = await dispatcher.write(mfaVerifyQn, body, createAnonymousUser(SYSTEM_TENANT_ID));
|
|
72
73
|
if (!result.isSuccess) {
|
|
73
|
-
|
|
74
|
-
const reason = result.error.details?.reason ?? result.error.code;
|
|
75
|
-
// @cast-boundary engine-payload — statusMap value union narrows to the http-status union
|
|
76
|
-
const status = (statusMap[reason] ?? result.error.httpStatus);
|
|
77
|
-
return c.json({ isSuccess: false, error: result.error }, status);
|
|
74
|
+
return handlerFailureResponse(c, result.error, statusMap);
|
|
78
75
|
}
|
|
79
76
|
// @cast-boundary engine-payload — generic dispatcher.write result for mfa-verify handler
|
|
80
77
|
const data = result.data;
|
|
@@ -138,11 +135,7 @@ export function registerMfaPreauthEnableStartRoute(ctx) {
|
|
|
138
135
|
}
|
|
139
136
|
const result = await dispatcher.write(mfaPreauthEnableStartQn, body, createAnonymousUser(SYSTEM_TENANT_ID));
|
|
140
137
|
if (!result.isSuccess) {
|
|
141
|
-
|
|
142
|
-
const reason = result.error.details?.reason ?? result.error.code;
|
|
143
|
-
// @cast-boundary engine-payload — statusMap value union narrows to the http-status union
|
|
144
|
-
const status = (statusMap[reason] ?? result.error.httpStatus);
|
|
145
|
-
return c.json({ isSuccess: false, error: result.error }, status);
|
|
138
|
+
return handlerFailureResponse(c, result.error, statusMap);
|
|
146
139
|
}
|
|
147
140
|
// @cast-boundary engine-payload — generic dispatcher.write result for
|
|
148
141
|
// the preauth-enable-start handler
|
|
@@ -183,11 +176,7 @@ export function registerMfaPreauthConfirmRoute(ctx) {
|
|
|
183
176
|
}
|
|
184
177
|
const result = await dispatcher.write(mfaPreauthConfirmQn, body, createAnonymousUser(SYSTEM_TENANT_ID));
|
|
185
178
|
if (!result.isSuccess) {
|
|
186
|
-
|
|
187
|
-
const reason = result.error.details?.reason ?? result.error.code;
|
|
188
|
-
// @cast-boundary engine-payload — statusMap value union narrows to the http-status union
|
|
189
|
-
const status = (statusMap[reason] ?? result.error.httpStatus);
|
|
190
|
-
return c.json({ isSuccess: false, error: result.error }, status);
|
|
179
|
+
return handlerFailureResponse(c, result.error, statusMap);
|
|
191
180
|
}
|
|
192
181
|
// @cast-boundary engine-payload — generic dispatcher.write result for mfa-preauth-confirm handler
|
|
193
182
|
const data = result.data;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { createAnonymousUser } from "../engine/system-user.js";
|
|
3
|
+
import { SYSTEM_TENANT_ID } from "../engine/types/index.js";
|
|
4
|
+
import { Routes } from "./api-constants.js";
|
|
5
|
+
import { inMemoryLoginRateLimiterFallback } from "./auth-rate-limiters.js";
|
|
6
|
+
import { handlerFailureResponse } from "./auth-routes-shared.js";
|
|
7
|
+
// Parsed before the rate limit so a malformed body cannot bypass the bucket.
|
|
8
|
+
const SessionExchangeBody = z.object({
|
|
9
|
+
method: z.string().min(1),
|
|
10
|
+
payload: z.unknown(),
|
|
11
|
+
});
|
|
12
|
+
// Loose on purpose: optional session fields (claims, sid, timezone) pass through untouched.
|
|
13
|
+
const AuthSessionResult = z.object({
|
|
14
|
+
kind: z.literal("auth-session"),
|
|
15
|
+
session: z.looseObject({
|
|
16
|
+
id: z.string(),
|
|
17
|
+
tenantId: z.string(),
|
|
18
|
+
roles: z.array(z.string()),
|
|
19
|
+
}),
|
|
20
|
+
});
|
|
21
|
+
export function registerSessionExchangeRoute(ctx) {
|
|
22
|
+
const { api, dispatcher, config, getClientIp, mintSessionAndRespond, landingPathFragment } = ctx;
|
|
23
|
+
const handlers = config.sessionExchangeHandlers;
|
|
24
|
+
if (!handlers || Object.keys(handlers).length === 0)
|
|
25
|
+
return;
|
|
26
|
+
const statusMap = config.loginErrorStatusMap ?? {};
|
|
27
|
+
const loginLimiter = config.loginRateLimit === null
|
|
28
|
+
? null
|
|
29
|
+
: (config.loginRateLimit ?? inMemoryLoginRateLimiterFallback());
|
|
30
|
+
const rateLimiter = config.sessionExchangeRateLimit === undefined ? loginLimiter : config.sessionExchangeRateLimit;
|
|
31
|
+
api.post(Routes.authSessionExchange, async (c) => {
|
|
32
|
+
const raw = await c.req.json().catch(() => null);
|
|
33
|
+
const parsed = SessionExchangeBody.safeParse(raw);
|
|
34
|
+
if (!parsed.success) {
|
|
35
|
+
return c.json({ isSuccess: false, error: "invalid_body" }, 400);
|
|
36
|
+
}
|
|
37
|
+
const { method, payload } = parsed.data;
|
|
38
|
+
// hasOwn: "__proto__" / "toString" must not resolve through the prototype.
|
|
39
|
+
const qn = Object.hasOwn(handlers, method) ? handlers[method] : undefined;
|
|
40
|
+
if (qn === undefined) {
|
|
41
|
+
return c.json({ isSuccess: false, error: "unknown_method" }, 400);
|
|
42
|
+
}
|
|
43
|
+
const rateLimitKey = `${getClientIp(c)}|session-exchange:${method}`;
|
|
44
|
+
if (rateLimiter) {
|
|
45
|
+
const allowed = await rateLimiter.check(rateLimitKey);
|
|
46
|
+
if (!allowed) {
|
|
47
|
+
return c.json({ isSuccess: false, error: "rate_limited" }, 429);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const result = await dispatcher.write(qn, payload, createAnonymousUser(SYSTEM_TENANT_ID));
|
|
51
|
+
if (!result.isSuccess) {
|
|
52
|
+
return handlerFailureResponse(c, result.error, statusMap);
|
|
53
|
+
}
|
|
54
|
+
const exchanged = AuthSessionResult.safeParse(result.data);
|
|
55
|
+
if (!exchanged.success) {
|
|
56
|
+
return c.json({ isSuccess: false, error: "invalid_exchange_result" }, 500);
|
|
57
|
+
}
|
|
58
|
+
const session = exchanged.data.session;
|
|
59
|
+
const token = await mintSessionAndRespond(c, session);
|
|
60
|
+
const landingPath = landingPathFragment({
|
|
61
|
+
flow: "login",
|
|
62
|
+
roles: session.roles,
|
|
63
|
+
tenantId: session.tenantId,
|
|
64
|
+
});
|
|
65
|
+
// No rate-limit reset on success: the bucket is per IP and method, not per
|
|
66
|
+
// identity, so a reset after one's own valid code would reopen guessing for others.
|
|
67
|
+
return c.json({
|
|
68
|
+
isSuccess: true,
|
|
69
|
+
token,
|
|
70
|
+
user: { id: session.id, tenantId: session.tenantId, roles: session.roles },
|
|
71
|
+
...landingPath,
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
}
|
|
@@ -32,4 +32,16 @@ declare const RequestTokenBody: z.ZodObject<{
|
|
|
32
32
|
email: z.ZodEmail;
|
|
33
33
|
returnTo: z.ZodCatch<z.ZodOptional<z.ZodString>>;
|
|
34
34
|
}, z.core.$strip>;
|
|
35
|
+
export declare function handlerFailureResponse(c: Context, error: {
|
|
36
|
+
readonly code: string;
|
|
37
|
+
readonly httpStatus: number;
|
|
38
|
+
readonly details?: unknown;
|
|
39
|
+
}, statusMap: Readonly<Record<string, number>>): Response & import("hono").TypedResponse<{
|
|
40
|
+
isSuccess: false;
|
|
41
|
+
error: {
|
|
42
|
+
readonly code: string;
|
|
43
|
+
readonly httpStatus: number;
|
|
44
|
+
readonly details?: import("hono/utils/types").JSONValue | undefined;
|
|
45
|
+
};
|
|
46
|
+
}, 400 | 401 | 403 | 422 | 429 | 500, "json">;
|
|
35
47
|
export {};
|
|
@@ -89,3 +89,18 @@ const RequestTokenBody = z.object({
|
|
|
89
89
|
email: z.email(),
|
|
90
90
|
returnTo: returnToField,
|
|
91
91
|
});
|
|
92
|
+
// A handler failure answers with the status the route maps its reason to, else
|
|
93
|
+
// with the error's own status. Shared so the auth routes cannot drift apart.
|
|
94
|
+
export function handlerFailureResponse(c, error, statusMap) {
|
|
95
|
+
const details = error.details;
|
|
96
|
+
const reason = typeof details === "object" &&
|
|
97
|
+
details !== null &&
|
|
98
|
+
"reason" in details &&
|
|
99
|
+
typeof details.reason === "string"
|
|
100
|
+
? details.reason
|
|
101
|
+
: error.code;
|
|
102
|
+
// @cast-boundary engine-payload — statusMap value union narrows to the http-status union
|
|
103
|
+
const status = (statusMap[reason] ?? error.httpStatus);
|
|
104
|
+
// c.json (not Response.json) keeps headers middleware set via c.header before next().
|
|
105
|
+
return c.json({ isSuccess: false, error }, status);
|
|
106
|
+
}
|
|
@@ -19,8 +19,10 @@ export type AuthRoutesConfig = {
|
|
|
19
19
|
membershipQuery: string;
|
|
20
20
|
userQuery?: string;
|
|
21
21
|
loginHandler?: string;
|
|
22
|
+
sessionExchangeHandlers?: Readonly<Record<string, string>>;
|
|
22
23
|
loginErrorStatusMap?: Readonly<Record<string, number>>;
|
|
23
24
|
loginRateLimit?: LoginRateLimiter | null;
|
|
25
|
+
sessionExchangeRateLimit?: LoginRateLimiter | null;
|
|
24
26
|
mfaVerifyHandler?: string;
|
|
25
27
|
switchTenantMfaGateHandler?: string;
|
|
26
28
|
mfaVerifyErrorStatusMap?: Readonly<Record<string, number>>;
|
package/dist/api/auth-routes.js
CHANGED
|
@@ -3,6 +3,7 @@ import { registerInviteRoutes } from "./auth-routes-invite.js";
|
|
|
3
3
|
import { registerLoginRoute } from "./auth-routes-login.js";
|
|
4
4
|
import { registerMfaPreauthConfirmRoute, registerMfaPreauthEnableStartRoute, registerMfaVerifyRoute, } from "./auth-routes-mfa.js";
|
|
5
5
|
import { registerSessionRoutes } from "./auth-routes-session.js";
|
|
6
|
+
import { registerSessionExchangeRoute } from "./auth-routes-session-exchange.js";
|
|
6
7
|
import { registerSignupRoutes } from "./auth-routes-signup.js";
|
|
7
8
|
import { registerAccountUnlockRoutes, registerEmailVerificationRoutes, registerPasswordResetRoutes, } from "./auth-routes-token-flows.js";
|
|
8
9
|
export { createInMemoryLoginRateLimiter, createRedisLoginRateLimiter, inMemoryLoginRateLimiterFallback, } from "./auth-rate-limiters.js";
|
|
@@ -29,6 +30,7 @@ export function assertSessionCallbacksPaired(auth) {
|
|
|
29
30
|
export function createAuthRoutes(dispatcher, jwt, config) {
|
|
30
31
|
const ctx = createAuthRouteContext(dispatcher, jwt, config);
|
|
31
32
|
registerLoginRoute(ctx);
|
|
33
|
+
registerSessionExchangeRoute(ctx);
|
|
32
34
|
registerMfaVerifyRoute(ctx);
|
|
33
35
|
registerMfaPreauthEnableStartRoute(ctx);
|
|
34
36
|
registerMfaPreauthConfirmRoute(ctx);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cosmicdrift/kumiko-framework",
|
|
3
|
-
"version": "0.424.
|
|
3
|
+
"version": "0.424.1",
|
|
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.424.
|
|
207
|
+
"@cosmicdrift/kumiko-types": "0.424.1",
|
|
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.424.
|
|
229
|
+
"@cosmicdrift/kumiko-testing": "0.424.1",
|
|
230
230
|
"bun-types": "^1.4.4",
|
|
231
231
|
"fflate": "^0.8.3",
|
|
232
232
|
"meilisearch": "^0.62.0",
|
package/src/changes.json
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.424.1",
|
|
4
|
+
"type": "improvement",
|
|
5
|
+
"title": "custom login methods via session-exchange handlers",
|
|
6
|
+
"detail": "`auth.sessionExchangeHandlers` maps a method name to an anonymous write handler that verifies the identity itself (for example an Apple or Google ID token) and returns `{ kind: \"auth-session\", session }`. The new public route `POST /auth/session-exchange` runs the handler and mints the session like `/auth/login`, including cookies. The login rate limiter counts per IP and method and is not reset on success. Only listed handlers can issue a session. The route's rate limit (IP + method, no reset) reuses the login limiter unless `auth.sessionExchangeRateLimit` sets another one or `null`. The new `sessionForVerifiedUser` helper from auth-email-password runs the login gates (account status, membership choice, claims) after the identity proof, with a verified-email requirement for email lookups, without password or lockout gates. Boot aborts when `auth-mfa` is mounted together with `sessionExchangeHandlers`, since the exchange cannot enforce a second factor yet."
|
|
7
|
+
},
|
|
2
8
|
{
|
|
3
9
|
"version": "0.424.0",
|
|
4
10
|
"type": "fix",
|