@voltro/plugin-auth 0.85.0 → 0.86.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.
@@ -1,2018 +0,0 @@
1
- import { hashPassword as e, verifyPassword as t, verifyPasswordWithRehash as n } from "./password.js";
2
- import { SESSION_COOKIE_NAME as r, clearSessionCookie as i, issueSession as a, readSessionFromHeaders as o, resolveSessionSecret as s, resolveSessionSecrets as c, sessionSecretsOf as l } from "./session.js";
3
- import { a as u, i as d, l as f, n as p, o as m, r as h, s as g, t as _ } from "./strategy-XaGjSicX.js";
4
- import { hashToken as v, mintSecret as y, mintToken as b } from "./tokens.js";
5
- import { CSRF_COOKIE_NAME as ee, CSRF_HEADER_NAME as te, issueCsrfToken as x, verifyCsrf as ne } from "./csrf.js";
6
- import { generateChallenge as S, verifyAssertion as re, verifyRegistration as C } from "./webauthn.js";
7
- import { createHash as w, createHmac as T, randomBytes as E, timingSafeEqual as ie } from "node:crypto";
8
- import { Data as ae, Effect as D } from "effect";
9
- import { SESSION_HEADER_NAME as oe, buildSetCookie as O, readCookie as se } from "@voltro/protocol/session";
10
- import { registerRetention as ce, retentionTtlMsFromEnv as le, writeTenantSelection as ue } from "@voltro/database";
11
- import { IMPERSONATION_METADATA_KEY as k, definePlugin as de, rawImpersonationMark as fe, selectSubjectTenant as pe } from "@voltro/protocol";
12
- //#region src/postgresUserStore.ts
13
- var me = (e) => {
14
- let t = e;
15
- for (let e = 0; typeof t == "object" && t && e < 6; e++) {
16
- let e = t.code;
17
- if (typeof e == "string") return e;
18
- let n = t;
19
- t = n.reason ?? n.cause;
20
- }
21
- }, he = (e) => {
22
- let t = e?.columns ?? {};
23
- return {
24
- table: e?.table ?? "users",
25
- col: {
26
- id: t.id ?? "id",
27
- email: t.email ?? "email",
28
- tenantId: t.tenantId ?? "tenantId",
29
- createdAt: t.createdAt ?? "createdAt",
30
- passwordHash: t.passwordHash ?? "passwordHash",
31
- updatedAt: t.updatedAt ?? "updatedAt",
32
- mfaSecret: t.mfaSecret ?? "mfaSecret",
33
- mfaEnrolledAt: t.mfaEnrolledAt ?? "mfaEnrolledAt",
34
- emailVerifiedAt: t.emailVerifiedAt ?? "emailVerifiedAt",
35
- deactivatedAt: t.deactivatedAt ?? !1
36
- }
37
- };
38
- }, ge = (e, t = {}) => {
39
- let n = he(t.identity), { col: r } = n, i = (t) => e`${e(r[t])}`, a = [
40
- "id",
41
- "email",
42
- "passwordHash",
43
- "tenantId",
44
- "createdAt",
45
- "mfaSecret",
46
- "mfaEnrolledAt",
47
- "emailVerifiedAt",
48
- "deactivatedAt"
49
- ], o, s = () => o ??= {
50
- usersTable: e.join(".", !1)(n.table.split(".").map((t) => e`${e(t)}`)),
51
- selectList: e.csv(a.map((t) => r[t] === !1 ? e`NULL AS ${e(t)}` : e`${i(t)} AS ${e(t)}`))
52
- }, c = (e, t) => /* @__PURE__ */ Error(`postgresUserStore: ${t} needs the "${e}" column, and identity.columns.${e} is false — this table has none`), l = (t) => r.updatedAt === !1 ? e`` : e`, ${i("updatedAt")} = ${t}`, d = (e) => ({
53
- id: e.id,
54
- email: e.email,
55
- passwordHash: e.passwordHash,
56
- tenantId: e.tenantId,
57
- createdAt: e.createdAt,
58
- mfaSecret: e.mfaSecret,
59
- mfaEnrolledAt: e.mfaEnrolledAt,
60
- emailVerifiedAt: e.emailVerifiedAt,
61
- ...r.deactivatedAt === !1 ? {} : { deactivatedAt: e.deactivatedAt ?? null }
62
- }), f = (t) => D.gen(function* () {
63
- let n = yield* e`
64
- SELECT ${s().selectList} FROM ${s().usersTable}
65
- WHERE ${i("email")} = ${t.toLowerCase()}
66
- LIMIT 1
67
- `;
68
- return n[0] ? d(n[0]) : null;
69
- }).pipe(D.orElseSucceed(() => null)), m = (t) => D.gen(function* () {
70
- let n = yield* e`
71
- SELECT ${s().selectList} FROM ${s().usersTable}
72
- WHERE ${i("id")} = ${t}
73
- LIMIT 1
74
- `;
75
- return n[0] ? d(n[0]) : null;
76
- }).pipe(D.orElseSucceed(() => null)), g = (t) => D.gen(function* () {
77
- let n = t.email.toLowerCase(), a = /* @__PURE__ */ new Date(), o = [
78
- i("id"),
79
- i("email"),
80
- i("tenantId"),
81
- i("createdAt")
82
- ], c = [
83
- t.id,
84
- n,
85
- t.tenantId,
86
- a
87
- ];
88
- return r.passwordHash !== !1 && (o.push(i("passwordHash")), c.push(t.passwordHash ?? null)), r.updatedAt !== !1 && (o.push(i("updatedAt")), c.push(a)), yield* e`
89
- INSERT INTO ${s().usersTable} (${e.csv(o)})
90
- VALUES ${e.in(c)}
91
- `.pipe(D.map(() => ({
92
- ...t,
93
- email: n,
94
- createdAt: a
95
- })), D.catch((e) => me(e) === "23505" ? D.fail(new p({ email: n })) : D.die(e)));
96
- }), _ = (t) => D.gen(function* () {
97
- let n = (yield* e`
98
- SELECT ${s().selectList} FROM ${s().usersTable} WHERE ${i("id")} = ${t} LIMIT 1
99
- `)[0];
100
- return n ? d(n) : yield* D.fail(new h({ userId: t }));
101
- }).pipe(D.catchTag("SqlError", (e) => D.die(e))), v = (t, n) => D.gen(function* () {
102
- return r.passwordHash === !1 ? yield* D.die(c("passwordHash", "updatePassword")) : (yield* e`
103
- UPDATE ${s().usersTable} SET ${i("passwordHash")} = ${n}${l(/* @__PURE__ */ new Date())}
104
- WHERE ${i("id")} = ${t}
105
- `.pipe(D.catchTag("SqlError", (e) => D.die(e))), yield* _(t));
106
- }), y = (t, n) => D.gen(function* () {
107
- return r.mfaSecret === !1 ? yield* D.die(c("mfaSecret", "setMfaSecret")) : r.mfaEnrolledAt === !1 ? yield* D.die(c("mfaEnrolledAt", "setMfaSecret")) : (yield* e`
108
- UPDATE ${s().usersTable}
109
- SET ${i("mfaSecret")} = ${n}, ${i("mfaEnrolledAt")} = ${null}
110
- WHERE ${i("id")} = ${t}
111
- `.pipe(D.catchTag("SqlError", (e) => D.die(e))), yield* _(t));
112
- }), b = (t) => D.gen(function* () {
113
- return r.mfaEnrolledAt === !1 ? yield* D.die(c("mfaEnrolledAt", "markMfaEnrolled")) : (yield* e`
114
- UPDATE ${s().usersTable}
115
- SET ${i("mfaEnrolledAt")} = ${/* @__PURE__ */ new Date()}
116
- WHERE ${i("id")} = ${t}
117
- `.pipe(D.catchTag("SqlError", (e) => D.die(e))), yield* _(t));
118
- }), ee = (t) => D.gen(function* () {
119
- return r.mfaSecret === !1 ? yield* D.die(c("mfaSecret", "clearMfa")) : r.mfaEnrolledAt === !1 ? yield* D.die(c("mfaEnrolledAt", "clearMfa")) : (yield* e`
120
- UPDATE ${s().usersTable}
121
- SET ${i("mfaSecret")} = ${null}, ${i("mfaEnrolledAt")} = ${null}
122
- WHERE ${i("id")} = ${t}
123
- `.pipe(D.catchTag("SqlError", (e) => D.die(e))), yield* _(t));
124
- }), te = (t) => D.gen(function* () {
125
- return r.emailVerifiedAt === !1 ? yield* D.die(c("emailVerifiedAt", "markEmailVerified")) : (yield* e`
126
- UPDATE ${s().usersTable}
127
- SET ${i("emailVerifiedAt")} = ${/* @__PURE__ */ new Date()}${l(/* @__PURE__ */ new Date())}
128
- WHERE ${i("id")} = ${t} AND ${i("emailVerifiedAt")} IS NULL
129
- `.pipe(D.catchTag("SqlError", (e) => D.die(e))), yield* _(t));
130
- }), x = (t) => D.gen(function* () {
131
- return (yield* e`
132
- SELECT "userId", "tenantId", role, "joinedAt"
133
- FROM memberships WHERE "userId" = ${t}
134
- ORDER BY "joinedAt" ASC
135
- `).map((e) => ({ ...e }));
136
- }).pipe(D.orElseSucceed(() => [])), ne = (t) => D.gen(function* () {
137
- let n = /* @__PURE__ */ new Date();
138
- yield* e`
139
- UPDATE memberships SET role = ${t.role}
140
- WHERE "userId" = ${t.userId} AND "tenantId" = ${t.tenantId}
141
- `;
142
- let r = yield* e`
143
- SELECT "userId", "tenantId", role, "joinedAt"
144
- FROM memberships
145
- WHERE "userId" = ${t.userId} AND "tenantId" = ${t.tenantId}
146
- LIMIT 1
147
- `;
148
- return r[0] ? { ...r[0] } : (yield* e`
149
- INSERT INTO memberships (id, "userId", "tenantId", role, "joinedAt")
150
- VALUES (${u("mem")}, ${t.userId}, ${t.tenantId}, ${t.role}, ${n})
151
- `, {
152
- ...t,
153
- joinedAt: n
154
- });
155
- }).pipe(D.catch(() => D.succeed({
156
- ...t,
157
- joinedAt: /* @__PURE__ */ new Date()
158
- }))), S = (t, n) => D.gen(function* () {
159
- return (yield* e`
160
- SELECT role FROM memberships
161
- WHERE "userId" = ${t} AND "tenantId" = ${n} LIMIT 1
162
- `)[0]?.role ?? null;
163
- }).pipe(D.orElseSucceed(() => null)), re = (t) => D.gen(function* () {
164
- return (yield* e`
165
- SELECT id, "userId", "tenantId", "expiresAt", "ipAddress", "userAgent", "createdAt", "lastSeenAt"
166
- FROM sessions WHERE "userId" = ${t}
167
- ORDER BY "createdAt" DESC
168
- `).map((e) => ({ ...e }));
169
- }).pipe(D.orElseSucceed(() => [])), C = (t) => D.gen(function* () {
170
- let n = /* @__PURE__ */ new Date();
171
- return yield* e`
172
- INSERT INTO sessions (id, "userId", "tenantId", "expiresAt", "ipAddress", "userAgent", "createdAt", "lastSeenAt")
173
- VALUES (
174
- ${t.id}, ${t.userId}, ${t.tenantId}, ${t.expiresAt},
175
- ${t.ipAddress ?? null}, ${t.userAgent ?? null}, ${n}, ${n}
176
- )
177
- `, {
178
- ...t,
179
- createdAt: n,
180
- lastSeenAt: n
181
- };
182
- }).pipe(D.catch(() => D.succeed({
183
- ...t,
184
- createdAt: /* @__PURE__ */ new Date(),
185
- lastSeenAt: /* @__PURE__ */ new Date()
186
- }))), w = (t) => D.gen(function* () {
187
- let n = yield* e`
188
- SELECT id, "userId", "tenantId", "expiresAt", "ipAddress", "userAgent", "createdAt", "lastSeenAt"
189
- FROM sessions WHERE id = ${t} LIMIT 1
190
- `;
191
- return n[0] ? { ...n[0] } : null;
192
- }).pipe(D.orElseSucceed(() => null)), T = (t, n) => D.gen(function* () {
193
- yield* e`
194
- UPDATE sessions SET "expiresAt" = ${n}, "lastSeenAt" = ${/* @__PURE__ */ new Date()}
195
- WHERE id = ${t}
196
- `;
197
- }).pipe(D.asVoid, D.orElseSucceed(() => void 0)), E = (t, n) => D.gen(function* () {
198
- return (yield* e`
199
- DELETE FROM sessions WHERE id = ${n} AND "userId" = ${t}
200
- RETURNING id
201
- `).length > 0;
202
- }).pipe(D.orElseSucceed(() => !1)), ie = (t, n) => D.gen(function* () {
203
- return (yield* e`
204
- DELETE FROM sessions WHERE "userId" = ${t} AND id <> ${n}
205
- RETURNING id
206
- `).length;
207
- }).pipe(D.orElseSucceed(() => 0)), ae = (t) => D.gen(function* () {
208
- return (yield* e`
209
- DELETE FROM sessions WHERE "userId" = ${t}
210
- RETURNING id
211
- `).length;
212
- }).pipe(D.orElseSucceed(() => 0)), oe = (t) => D.gen(function* () {
213
- let n = /* @__PURE__ */ new Date();
214
- return yield* e`
215
- INSERT INTO "authTokens" (id, "tokenHash", "userId", purpose, "expiresAt", "consumedAt", "createdAt")
216
- VALUES (${t.id}, ${t.tokenHash}, ${t.userId}, ${t.purpose}, ${t.expiresAt}, ${null}, ${n})
217
- `, {
218
- ...t,
219
- consumedAt: null,
220
- createdAt: n
221
- };
222
- }).pipe(D.catch(() => D.succeed({
223
- ...t,
224
- consumedAt: null,
225
- createdAt: /* @__PURE__ */ new Date()
226
- }))), O = (t, n) => D.gen(function* () {
227
- let r = yield* e`
228
- UPDATE "authTokens"
229
- SET "consumedAt" = ${/* @__PURE__ */ new Date()}
230
- WHERE "tokenHash" = ${t}
231
- AND purpose = ${n}
232
- AND "consumedAt" IS NULL
233
- AND "expiresAt" > ${/* @__PURE__ */ new Date()}
234
- RETURNING id, "tokenHash", "userId", purpose, "expiresAt", "consumedAt", "createdAt"
235
- `;
236
- return r[0] ? { ...r[0] } : null;
237
- }).pipe(D.orElseSucceed(() => null)), se = (t, n) => D.gen(function* () {
238
- let r = yield* e`
239
- SELECT id, "tokenHash", "userId", purpose, "expiresAt", "consumedAt", "createdAt"
240
- FROM "authTokens"
241
- WHERE "userId" = ${t} AND purpose = ${n}
242
- ORDER BY "createdAt" DESC
243
- LIMIT 1
244
- `;
245
- return r[0] ? { ...r[0] } : null;
246
- }).pipe(D.orElseSucceed(() => null)), ce = (t) => D.gen(function* () {
247
- let n = /* @__PURE__ */ new Date(), r = t.email.toLowerCase();
248
- return yield* e`
249
- INSERT INTO invitations (
250
- id, "tokenHash", email, "tenantId", role, "invitedByUserId",
251
- "expiresAt", "acceptedAt", "acceptedByUserId", "revokedAt", "revokedByUserId", "createdAt"
252
- ) VALUES (
253
- ${t.id}, ${t.tokenHash}, ${r}, ${t.tenantId},
254
- ${t.role}, ${t.invitedByUserId}, ${t.expiresAt},
255
- ${null}, ${null}, ${null}, ${null}, ${n}
256
- )
257
- `, {
258
- ...t,
259
- email: r,
260
- acceptedAt: null,
261
- acceptedByUserId: null,
262
- revokedAt: null,
263
- revokedByUserId: null,
264
- createdAt: n
265
- };
266
- }).pipe(D.catch((e) => D.die(e))), le = (t) => D.gen(function* () {
267
- let n = yield* e`
268
- SELECT id, "tokenHash", email, "tenantId", role, "invitedByUserId", "expiresAt",
269
- "acceptedAt", "acceptedByUserId", "revokedAt", "revokedByUserId", "createdAt"
270
- FROM invitations WHERE "tokenHash" = ${t} LIMIT 1
271
- `;
272
- return n[0] ? { ...n[0] } : null;
273
- }).pipe(D.orElseSucceed(() => null)), ue = (t, n, r) => D.gen(function* () {
274
- let i = yield* e`
275
- UPDATE invitations
276
- SET "acceptedAt" = ${r}, "acceptedByUserId" = ${n}
277
- WHERE "tokenHash" = ${t}
278
- AND "acceptedAt" IS NULL
279
- AND "revokedAt" IS NULL
280
- AND "expiresAt" > ${r}
281
- RETURNING id, "tokenHash", email, "tenantId", role, "invitedByUserId", "expiresAt",
282
- "acceptedAt", "acceptedByUserId", "revokedAt", "revokedByUserId", "createdAt"
283
- `;
284
- return i[0] ? { ...i[0] } : null;
285
- }).pipe(D.catch((e) => D.die(e))), k = (t, n, r, i) => D.gen(function* () {
286
- return (yield* e`
287
- UPDATE invitations
288
- SET "revokedAt" = ${i}, "revokedByUserId" = ${r}
289
- WHERE id = ${t}
290
- AND "tenantId" = ${n}
291
- AND "acceptedAt" IS NULL
292
- AND "revokedAt" IS NULL
293
- RETURNING id
294
- `).length > 0;
295
- }).pipe(D.catch((e) => D.die(e))), de = (t) => D.gen(function* () {
296
- return (yield* e`
297
- SELECT id, "tokenHash", email, "tenantId", role, "invitedByUserId", "expiresAt",
298
- "acceptedAt", "acceptedByUserId", "revokedAt", "revokedByUserId", "createdAt"
299
- FROM invitations WHERE "tenantId" = ${t}
300
- ORDER BY "createdAt" DESC
301
- `).map((e) => ({ ...e }));
302
- }).pipe(D.orElseSucceed(() => [])), fe = (t, n) => D.gen(function* () {
303
- return (yield* e`
304
- SELECT COUNT(*)::int AS n FROM invitations
305
- WHERE "tenantId" = ${t}
306
- AND "acceptedAt" IS NULL AND "revokedAt" IS NULL AND "expiresAt" > ${n}
307
- `)[0]?.n ?? 0;
308
- }).pipe(D.catch((e) => D.die(e))), pe = (t, n, r, i) => D.gen(function* () {
309
- return (yield* e`
310
- UPDATE invitations
311
- SET "revokedAt" = ${i}, "revokedByUserId" = ${r}
312
- WHERE "tenantId" = ${t}
313
- AND email = ${n.toLowerCase()}
314
- AND "acceptedAt" IS NULL
315
- AND "revokedAt" IS NULL
316
- RETURNING id
317
- `).length;
318
- }).pipe(D.catch((e) => D.die(e))), ge = (t) => D.gen(function* () {
319
- let n = /* @__PURE__ */ new Date();
320
- return yield* e`
321
- INSERT INTO "impersonationGrants" (
322
- id, "sessionId", "actorUserId", "actorSessionId", "targetUserId", "tenantId",
323
- reason, "startedAt", "expiresAt", "endedAt", "endedReason", "ipAddress", "userAgent"
324
- ) VALUES (
325
- ${t.id}, ${t.sessionId}, ${t.actorUserId}, ${t.actorSessionId},
326
- ${t.targetUserId}, ${t.tenantId}, ${t.reason ?? null}, ${n},
327
- ${t.expiresAt}, ${null}, ${null}, ${t.ipAddress ?? null}, ${t.userAgent ?? null}
328
- )
329
- `, {
330
- ...t,
331
- startedAt: n,
332
- endedAt: null,
333
- endedReason: null
334
- };
335
- }).pipe(D.catch((e) => D.die(e))), _e = (t) => D.gen(function* () {
336
- let n = yield* e`
337
- SELECT id, "sessionId", "actorUserId", "actorSessionId", "targetUserId", "tenantId",
338
- reason, "startedAt", "expiresAt", "endedAt", "endedReason", "ipAddress", "userAgent"
339
- FROM "impersonationGrants" WHERE "sessionId" = ${t} LIMIT 1
340
- `;
341
- return n[0] ? { ...n[0] } : null;
342
- }).pipe(D.orElseSucceed(() => null)), ve = (t, n, r) => D.gen(function* () {
343
- return (yield* e`
344
- UPDATE "impersonationGrants"
345
- SET "endedAt" = ${r}, "endedReason" = ${n}
346
- WHERE "sessionId" = ${t} AND "endedAt" IS NULL
347
- RETURNING id
348
- `).length > 0;
349
- }).pipe(D.catch((e) => D.die(e))), ye = (t) => D.gen(function* () {
350
- return (yield* e`
351
- SELECT id, "credentialId", "userId", "publicKey", counter, transports, "createdAt", "lastUsedAt"
352
- FROM passkeys WHERE "userId" = ${t}
353
- `).map((e) => ({ ...e }));
354
- }).pipe(D.orElseSucceed(() => [])), be = (t) => D.gen(function* () {
355
- let n = yield* e`
356
- SELECT id, "credentialId", "userId", "publicKey", counter, transports, "createdAt", "lastUsedAt"
357
- FROM passkeys WHERE "credentialId" = ${t} LIMIT 1
358
- `;
359
- return n[0] ? { ...n[0] } : null;
360
- }).pipe(D.orElseSucceed(() => null)), A = (t) => D.gen(function* () {
361
- let n = /* @__PURE__ */ new Date();
362
- return yield* e`
363
- INSERT INTO passkeys (id, "credentialId", "userId", "publicKey", counter, transports, "createdAt", "lastUsedAt")
364
- VALUES (
365
- ${t.id}, ${t.credentialId}, ${t.userId}, ${t.publicKey},
366
- ${t.counter}, ${t.transports ?? null}, ${n}, ${null}
367
- )
368
- `, {
369
- ...t,
370
- createdAt: n,
371
- lastUsedAt: null
372
- };
373
- }).pipe(D.catch(() => D.succeed({
374
- ...t,
375
- createdAt: /* @__PURE__ */ new Date(),
376
- lastUsedAt: null
377
- }))), j = (t, n) => D.gen(function* () {
378
- return (yield* e`
379
- UPDATE passkeys
380
- SET counter = ${n}, "lastUsedAt" = ${/* @__PURE__ */ new Date()}
381
- WHERE "credentialId" = ${t}
382
- AND counter < ${n}
383
- RETURNING id
384
- `).length > 0;
385
- }).pipe(D.orElseSucceed(() => !1)), xe = (t, n) => D.gen(function* () {
386
- let r = /* @__PURE__ */ new Date();
387
- yield* e`DELETE FROM "recoveryCodes" WHERE "userId" = ${t}`;
388
- for (let i of n) yield* e`
389
- INSERT INTO "recoveryCodes" (id, "userId", "codeHash", "consumedAt", "createdAt")
390
- VALUES (${u("rc")}, ${t}, ${i}, ${null}, ${r})
391
- `;
392
- }).pipe(D.asVoid, D.orElseSucceed(() => void 0)), Se = (t, n) => D.gen(function* () {
393
- return (yield* e`
394
- UPDATE "recoveryCodes"
395
- SET "consumedAt" = ${/* @__PURE__ */ new Date()}
396
- WHERE "userId" = ${t}
397
- AND "codeHash" = ${n}
398
- AND "consumedAt" IS NULL
399
- RETURNING id
400
- `).length > 0;
401
- }).pipe(D.orElseSucceed(() => !1)), Ce = (t) => D.gen(function* () {
402
- return (yield* e`
403
- SELECT COUNT(*)::int AS n FROM "recoveryCodes"
404
- WHERE "userId" = ${t} AND "consumedAt" IS NULL
405
- `)[0]?.n ?? 0;
406
- }).pipe(D.orElseSucceed(() => 0)), M = (e, t) => D.catch((n) => D.logWarning(`[auth] lockout ${e} failed — brute-force protection is not counting`).pipe(D.annotateLogs("cause", String(n)), D.as(t)));
407
- return {
408
- findByEmail: f,
409
- findById: m,
410
- insert: g,
411
- updatePassword: v,
412
- setMfaSecret: y,
413
- markMfaEnrolled: b,
414
- clearMfa: ee,
415
- markEmailVerified: te,
416
- listMemberships: x,
417
- addMembership: ne,
418
- membershipRole: S,
419
- listSessions: re,
420
- insertSession: C,
421
- findSession: w,
422
- touchSession: T,
423
- revokeSession: E,
424
- revokeAllOtherSessions: ie,
425
- revokeAllSessions: ae,
426
- insertToken: oe,
427
- consumeToken: O,
428
- latestToken: se,
429
- insertInvitation: ce,
430
- findInvitationByHash: le,
431
- acceptInvitation: ue,
432
- revokeInvitation: k,
433
- listInvitations: de,
434
- countPendingInvitations: fe,
435
- supersedePendingInvitations: pe,
436
- insertImpersonationGrant: ge,
437
- findImpersonationGrantBySession: _e,
438
- endImpersonationGrant: ve,
439
- replaceRecoveryCodes: xe,
440
- consumeRecoveryCode: Se,
441
- countRecoveryCodes: Ce,
442
- listPasskeys: ye,
443
- findPasskey: be,
444
- insertPasskey: A,
445
- advancePasskeyCounter: j,
446
- isLockedOut: (t, n) => D.gen(function* () {
447
- let r = (yield* e`
448
- SELECT "lockedUntil" FROM "loginAttempts"
449
- WHERE email = ${t.toLowerCase()} LIMIT 1
450
- `)[0]?.lockedUntil ?? null;
451
- return r != null && n < r.getTime() ? {
452
- locked: !0,
453
- retryAfterSeconds: Math.ceil((r.getTime() - n) / 1e3)
454
- } : {
455
- locked: !1,
456
- retryAfterSeconds: 0
457
- };
458
- }).pipe(M("read", {
459
- locked: !1,
460
- retryAfterSeconds: 0
461
- })),
462
- recordLoginFailure: (t, n, r) => D.gen(function* () {
463
- let i = t.toLowerCase(), a = (yield* e`
464
- SELECT "failedCount", "windowStartedAt", "lockedUntil"
465
- FROM "loginAttempts" WHERE email = ${i} LIMIT 1
466
- `)[0], o = a?.windowStartedAt?.getTime() ?? null, s = a?.lockedUntil?.getTime() ?? null, c = o == null || n - o >= r.windowMs, l = !a || c || s != null && n >= s, d = l ? 1 : a.failedCount + 1, f = l ? new Date(n) : new Date(o), p = d >= r.maxAttempts ? new Date(n + r.lockMs) : null, m = new Date(n);
467
- yield* e`
468
- INSERT INTO "loginAttempts" (id, email, "failedCount", "windowStartedAt", "lockedUntil", "createdAt", "updatedAt")
469
- VALUES (${u("la")}, ${i}, ${d}, ${f}, ${p}, ${m}, ${m})
470
- ON CONFLICT (email) DO UPDATE SET
471
- "failedCount" = ${d},
472
- "windowStartedAt" = ${f},
473
- "lockedUntil" = ${p},
474
- "updatedAt" = ${m}
475
- `;
476
- }).pipe(D.asVoid, M("record", void 0)),
477
- clearLoginFailures: (t) => D.gen(function* () {
478
- yield* e`DELETE FROM "loginAttempts" WHERE email = ${t.toLowerCase()}`;
479
- }).pipe(D.asVoid, M("clear", void 0))
480
- };
481
- }, _e = (e = {}) => ({ sql: t }) => t === void 0 ? d() : t.onDialectOrElse({
482
- pg: () => ge(t, e),
483
- orElse: () => {
484
- throw Error("appUserStore(): the app database is not postgres, and @voltro/plugin-auth ships a SQL user store for postgres only. Pass your own `UserStore` to authRoutesPlugin({ store }).");
485
- }
486
- }), ve = (e) => new Proxy({}, { get: (t, n) => {
487
- if (typeof n == "string" && n !== "then") return (...t) => {
488
- let r = e();
489
- if (r === void 0) throw Error(`authRoutesPlugin: user store method '${n}' was called before the framework bound the app database. A resolver-backed store is available once boot has finished.`);
490
- let i = r[n];
491
- if (typeof i != "function") throw Error(`authRoutesPlugin: the resolved user store has no method '${n}'.`);
492
- return i.apply(r, [...t]);
493
- };
494
- } }), ye = { ok: !0 }, be = (e, t) => D.gen(function* () {
495
- for (let n of e) {
496
- let e = yield* n(t);
497
- if (!e.ok) return e;
498
- }
499
- return ye;
500
- }), A = 30, j = 6, xe = 20, Se = "sha1", Ce = 1, M = class extends ae.TaggedError("TotpVerifyError") {}, we = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", Te = (e) => {
501
- let t = 0, n = 0, r = "";
502
- for (let i of e) for (n = n << 8 | i, t += 8; t >= 5;) r += we[n >>> t - 5 & 31], t -= 5;
503
- return t > 0 && (r += we[n << 5 - t & 31]), r;
504
- }, Ee = (e) => {
505
- let t = e.toUpperCase().replace(/[\s=]+/g, "");
506
- if (!/^[A-Z2-7]+$/.test(t)) return null;
507
- let n = new Uint8Array(Math.floor(t.length * 5 / 8)), r = 0, i = 0, a = 0;
508
- for (let e of t) {
509
- let t = we.indexOf(e);
510
- if (t === -1) return null;
511
- i = i << 5 | t, r += 5, r >= 8 && (n[a++] = i >>> r - 8 & 255, r -= 8);
512
- }
513
- return n.subarray(0, a);
514
- }, De = (e) => {
515
- let t = Buffer.alloc(8);
516
- return t.writeBigUInt64BE(BigInt(e), 0), t;
517
- }, Oe = (e, t) => {
518
- let n = T(Se, Buffer.from(e));
519
- n.update(De(t));
520
- let r = n.digest(), i = r[r.length - 1] & 15, a = (r[i] & 127) << 24 | (r[i + 1] & 255) << 16 | (r[i + 2] & 255) << 8 | r[i + 3] & 255;
521
- return String(a % 10 ** j).padStart(j, "0");
522
- }, ke = () => Te(E(xe)), Ae = (e) => `otpauth://totp/${encodeURIComponent(`${e.issuer}:${e.accountName}`)}?${new URLSearchParams({
523
- secret: e.secret,
524
- issuer: e.issuer,
525
- algorithm: "SHA1",
526
- digits: String(j),
527
- period: String(A)
528
- }).toString()}`, je = (e, t = Date.now()) => {
529
- let n = Ee(e);
530
- return n ? Oe(n, Math.floor(t / 1e3 / A)) : "000000";
531
- }, N = (e, t, n = Date.now()) => D.gen(function* () {
532
- let r = Ee(e);
533
- if (!r) return yield* D.fail(new M({ reason: "malformedSecret" }));
534
- let i = t.replace(/\s+/g, "");
535
- if (!/^[0-9]{6}$/.test(i)) return yield* D.fail(new M({ reason: "invalidCode" }));
536
- let a = Math.floor(n / 1e3 / A), o = Buffer.from(i);
537
- for (let e = -1; e <= Ce; e++) {
538
- let t = Oe(r, a + e), n = Buffer.from(t);
539
- if (n.length === o.length && ie(n, o)) return !0;
540
- }
541
- return yield* D.fail(new M({ reason: "invalidCode" }));
542
- }), Me = (e = 10) => {
543
- let t = [];
544
- for (let n = 0; n < e; n++) {
545
- let e = Te(E(16)).slice(0, 25).match(/.{1,5}/g) ?? [];
546
- t.push(e.join("-"));
547
- }
548
- return t;
549
- }, P = (e, t, n = { store: void 0 }) => {
550
- if (e === void 0) return D.succeed(null);
551
- let r = e(t, n);
552
- return D.isEffect(r) ? r : D.promise(() => r);
553
- }, Ne = 60, Pe = "email_not_verified", Fe = "emailVerified", Ie = (e) => e?.policy ?? "off", F = (e) => Ie(e) !== "off", I = (e, t) => {
554
- if (e.emailVerifiedAt != null) return !0;
555
- let n = t?.exemptAccountsCreatedBefore;
556
- return n !== void 0 && e.createdAt.getTime() < n.getTime();
557
- }, Le = (e) => {
558
- if (e.type !== "user") return null;
559
- let t = e.metadata?.[Fe];
560
- return typeof t == "boolean" ? t : null;
561
- }, Re = (e) => {
562
- let t = Ie(e) === "strict";
563
- return (n) => D.succeed(!t || I(n, e) ? { ok: !0 } : {
564
- ok: !1,
565
- code: Pe,
566
- message: "This account's email address has not been confirmed yet. Request a new confirmation link and follow it, then sign in again."
567
- });
568
- }, L = (e, t) => ({
569
- status: e,
570
- body: JSON.stringify(t),
571
- contentType: "application/json; charset=utf-8"
572
- }), ze = (e, t, n) => `${e}${t}${t.includes("?") ? "&" : "?"}token=${encodeURIComponent(n)}`, Be = (e, t, n) => D.gen(function* () {
573
- let r = n.emailVerification, i = (n.now ?? Date.now)(), a = (r?.resendCooldownSeconds ?? 60) * 1e3;
574
- if (a > 0) {
575
- let n = yield* t.latestToken(e.id, "email-verify");
576
- if (n && i - n.createdAt.getTime() < a) return !1;
577
- }
578
- let o = b("email-verify", r?.ttlSeconds ?? 86400);
579
- if (yield* t.insertToken({
580
- id: u("tok"),
581
- tokenHash: o.tokenHash,
582
- userId: e.id,
583
- purpose: "email-verify",
584
- expiresAt: o.expiresAt
585
- }).pipe(D.ignore), !n.sendEmail) return !1;
586
- let s = ze(n.appBaseUrl ?? "", r?.callbackPath ?? "/auth/verify-email/callback", o.token);
587
- return yield* D.tryPromise(() => n.sendEmail({
588
- to: e.email,
589
- kind: "email-verify",
590
- actionUrl: s,
591
- subject: "Confirm your email address",
592
- text: `Confirm your email address: ${s}`,
593
- html: `<p><a href="${s}">Confirm your email address</a> — this link expires in 24 hours.</p>`
594
- })).pipe(D.ignore), !0;
595
- }), Ve = (e, t, n) => D.gen(function* () {
596
- if (!e.email && !e.userId) return L(400, { error: "email or userId required" });
597
- let r = e.userId ? yield* t.findById(e.userId) : yield* t.findByEmail(e.email);
598
- return r && !I(r, n.emailVerification) && (yield* Be(r, t, n)), L(202, { ok: !0 });
599
- }), He = (e, t) => D.gen(function* () {
600
- if (!e.token) return L(400, { error: "token required" });
601
- let n = yield* t.consumeToken(v(e.token), "email-verify");
602
- if (!n) return L(401, { error: "invalid or expired token" });
603
- let r = yield* t.findById(n.userId);
604
- return r ? (yield* t.markEmailVerified(r.id).pipe(D.ignore), L(200, {
605
- ok: !0,
606
- verified: !0
607
- })) : L(401, { error: "invalid or expired token" });
608
- }), Ue = 5, We = 900, Ge = 900, Ke = (e) => ({
609
- maxAttempts: e.lockout?.maxAttempts ?? Ue,
610
- windowMs: (e.lockout?.windowSeconds ?? We) * 1e3,
611
- lockMs: (e.lockout?.lockSeconds ?? Ge) * 1e3
612
- }), R = (e) => e.secrets ?? (e.secret === void 0 ? c() : l(e.secret)), z = (e) => e.secret ?? s(), B = (e, t, n = {}) => ({
613
- status: e,
614
- body: JSON.stringify(t),
615
- contentType: "application/json; charset=utf-8",
616
- ...n
617
- }), V = (e, t = {}) => ({
618
- status: 302,
619
- body: "",
620
- contentType: "text/plain",
621
- location: e,
622
- ...t
623
- }), qe = 604800, Je = (e, t) => e.type === "user" ? {
624
- ...e,
625
- metadata: {
626
- ...e.metadata ?? {},
627
- sessionId: t
628
- }
629
- } : e, H = (e, t, n, r = {}) => D.gen(function* () {
630
- r.clearLoginFailures !== !1 && (yield* t.clearLoginFailures(e.email)), n.ensureActor && (yield* n.ensureActor(e));
631
- let i = yield* t.listMemberships(e.id), o = r.sessionId ?? u("sess"), s = r.ttlSeconds ?? qe;
632
- r.sessionRow !== "existing" && (yield* t.insertSession({
633
- id: o,
634
- userId: e.id,
635
- tenantId: e.tenantId,
636
- expiresAt: new Date(Date.now() + s * 1e3),
637
- ipAddress: r.ipAddress ?? null,
638
- userAgent: r.userAgent ?? null
639
- }).pipe(D.ignore));
640
- let c = { ...r.metadata };
641
- F(n.emailVerification) && (c[Fe] = I(e, n.emailVerification));
642
- let l = Je(g(e, {
643
- memberships: i,
644
- ...Object.keys(c).length > 0 ? { metadata: c } : {}
645
- }), o), d = a(l, R(n), {
646
- ttlSeconds: s,
647
- ...n.cookieDomain ? { domain: n.cookieDomain } : {},
648
- secure: n.cookieSecure ?? !0
649
- });
650
- return {
651
- setCookie: d.setCookie,
652
- value: d.value,
653
- expiresAt: Math.floor(Date.now() / 1e3) + s,
654
- subject: l
655
- };
656
- }), U = (e, t) => D.gen(function* () {
657
- let n = t.subjectGuards ?? [];
658
- if (n.length === 0) return null;
659
- let r = yield* be(n, e);
660
- return r.ok ? null : B(403, {
661
- error: r.code,
662
- message: r.message
663
- });
664
- }), Ye = (r, i, a) => D.gen(function* () {
665
- if (!r.email || !r.password) return B(400, { error: "email and password required" });
666
- let o = yield* i.findByEmail(r.email), s = (a.now ?? Date.now)(), c = yield* i.isLockedOut(r.email, s);
667
- if (c.locked) return B(429, {
668
- error: "account_locked",
669
- retryAfterSeconds: c.retryAfterSeconds
670
- });
671
- let l = o?.passwordHash, d = typeof l == "string" && l.length > 0 ? yield* n(r.password, l) : yield* D.gen(function* () {
672
- let n = yield* e("decoy-not-a-real-password").pipe(D.orElseSucceed(() => ""));
673
- return yield* t(r.password, n), { valid: !1 };
674
- });
675
- if (!o || !d.valid) return yield* i.recordLoginFailure(r.email, s, Ke(a)), B(401, { error: "invalid credentials" });
676
- let f = yield* U(o, a);
677
- if (f) return f;
678
- if (d.rehash && (yield* i.updatePassword(o.id, d.rehash).pipe(D.ignore)), o.mfaEnrolledAt) {
679
- let e = b("mfa-pending", 300);
680
- return yield* i.insertToken({
681
- id: u("tok"),
682
- tokenHash: e.tokenHash,
683
- userId: o.id,
684
- purpose: "mfa-pending",
685
- expiresAt: e.expiresAt
686
- }).pipe(D.ignore), B(200, {
687
- ok: !0,
688
- mfaRequired: !0,
689
- pendingToken: e.token,
690
- expiresInSeconds: 300
691
- });
692
- }
693
- let { setCookie: p, subject: m } = yield* H(o, i, a, {
694
- ipAddress: r.ipAddress ?? null,
695
- userAgent: r.userAgent ?? null
696
- });
697
- return r.redirectAfter ? V(a.successRedirect ?? "/", { setCookie: p }) : B(200, {
698
- ok: !0,
699
- subject: m
700
- }, { setCookie: p });
701
- }), Xe = (e, t, n) => D.gen(function* () {
702
- if (!e.pendingToken) return B(400, { error: "pending token required" });
703
- if (!e.code && !e.recoveryCode) return B(400, { error: "code or recoveryCode required" });
704
- let r = yield* t.consumeToken(v(e.pendingToken), "mfa-pending");
705
- if (!r) return B(401, { error: "invalid or expired challenge" });
706
- let i = yield* t.findById(r.userId);
707
- if (!i || !i.mfaEnrolledAt || !i.mfaSecret) return B(401, { error: "mfa not enrolled" });
708
- let a = (n.now ?? Date.now)(), o = yield* t.isLockedOut(i.email, a);
709
- if (o.locked) return B(429, {
710
- error: "account_locked",
711
- retryAfterSeconds: o.retryAfterSeconds
712
- });
713
- let s = yield* U(i, n);
714
- if (s) return s;
715
- if (!(e.recoveryCode ? yield* t.consumeRecoveryCode(i.id, v(e.recoveryCode.trim())) : yield* N(i.mfaSecret, e.code ?? "").pipe(D.map(() => !0), D.catchTag("TotpVerifyError", () => D.succeed(!1))))) return yield* t.recordLoginFailure(i.email, a, Ke(n)), B(401, { error: "invalid_code" });
716
- let { setCookie: c, subject: l } = yield* H(i, t, n, {
717
- ipAddress: e.ipAddress ?? null,
718
- userAgent: e.userAgent ?? null
719
- });
720
- return e.redirectAfter ? V(n.successRedirect ?? "/", { setCookie: c }) : B(200, {
721
- ok: !0,
722
- subject: l
723
- }, { setCookie: c });
724
- }), Ze = (t, n, r) => D.gen(function* () {
725
- if (!t.email || !t.password) return B(400, { error: "email and password required" });
726
- if (t.password.length < 8) return B(400, { error: "password must be at least 8 characters" });
727
- if (yield* n.findByEmail(t.email)) return B(409, { error: "email already registered" });
728
- let i = t.tenantId ?? r.defaultTenantId, a = yield* P(r.admit, {
729
- email: t.email,
730
- tenantId: i,
731
- via: "sign-up"
732
- });
733
- if (a) return B(403, {
734
- error: "not_admitted",
735
- reason: a.reason,
736
- message: a.message
737
- });
738
- let o = yield* e(t.password), s = yield* n.insert({
739
- id: u("user"),
740
- email: t.email,
741
- passwordHash: o,
742
- tenantId: i
743
- });
744
- yield* n.addMembership({
745
- userId: s.id,
746
- tenantId: i,
747
- role: "owner"
748
- }).pipe(D.ignore), F(r.emailVerification) && (r.emailVerification?.sendOnSignUp ?? !0) && (yield* Be(s, n, r).pipe(D.ignore));
749
- let { setCookie: c, subject: l } = yield* H(s, n, r);
750
- return t.redirectAfter ? V(r.successRedirect ?? "/", { setCookie: c }) : B(200, {
751
- ok: !0,
752
- subject: l
753
- }, { setCookie: c });
754
- }).pipe(D.catch((e) => D.succeed(B(500, {
755
- error: "signup_failed",
756
- cause: String(e)
757
- })))), Qe = (e) => ({
758
- status: 302,
759
- body: "",
760
- location: e.successRedirect ?? "/",
761
- setCookie: i({
762
- ...e.cookieDomain ? { domain: e.cookieDomain } : {},
763
- secure: e.cookieSecure ?? !0
764
- })
765
- }), $e = (e, t) => D.gen(function* () {
766
- let n = yield* t.findById(e.userId);
767
- if (!n) return B(404, { error: "user_not_found" });
768
- let r = ke();
769
- return yield* t.setMfaSecret(n.id, r).pipe(D.catch(() => D.succeed(n))), B(200, {
770
- ok: !0,
771
- secret: r,
772
- otpauthUrl: Ae({
773
- issuer: e.issuer,
774
- accountName: e.accountName,
775
- secret: r
776
- })
777
- });
778
- }), et = (e, t) => D.gen(function* () {
779
- let n = yield* t.findById(e.userId);
780
- if (!n) return B(404, { error: "user_not_found" });
781
- if (!n.mfaSecret) return B(400, { error: "no_enrollment_in_progress" });
782
- if (n.mfaEnrolledAt) return B(409, { error: "already_enrolled" });
783
- if (!(yield* N(n.mfaSecret, e.code).pipe(D.map(() => !0), D.catchTag("TotpVerifyError", () => D.succeed(!1))))) return B(401, { error: "invalid_code" });
784
- yield* t.markMfaEnrolled(n.id).pipe(D.catch(() => D.succeed(n)));
785
- let r = Me();
786
- return yield* t.replaceRecoveryCodes(n.id, r.map((e) => v(e))).pipe(D.ignore), B(200, {
787
- ok: !0,
788
- enrolled: !0,
789
- recoveryCodes: r
790
- });
791
- }), tt = (e, t) => D.gen(function* () {
792
- let n = yield* t.findById(e.userId);
793
- if (!n) return B(404, { error: "user_not_found" });
794
- if (!n.mfaEnrolledAt) return B(400, { error: "mfa_not_enrolled" });
795
- let r = Me();
796
- return yield* t.replaceRecoveryCodes(n.id, r.map((e) => v(e))).pipe(D.ignore), B(200, {
797
- ok: !0,
798
- recoveryCodes: r
799
- });
800
- }), nt = (e, t) => D.gen(function* () {
801
- let n = yield* t.findById(e.userId);
802
- return n ? (yield* t.clearMfa(n.id).pipe(D.catch(() => D.succeed(n))), yield* t.replaceRecoveryCodes(n.id, []).pipe(D.ignore), B(200, {
803
- ok: !0,
804
- enrolled: !1
805
- })) : B(404, { error: "user_not_found" });
806
- }), rt = (e) => {
807
- let t = x(z(e)), n = O(ee, t, {
808
- httpOnly: !1,
809
- sameSite: "lax",
810
- secure: e.cookieSecure ?? !0,
811
- ...e.cookieDomain ? { domain: e.cookieDomain } : {},
812
- path: "/"
813
- });
814
- return B(200, { csrfToken: t }, { setCookie: n });
815
- }, it = (e, t, n) => `${e}${t}${t.includes("?") ? "&" : "?"}token=${encodeURIComponent(n)}`, at = (e, t, n) => D.gen(function* () {
816
- if (!e.email) return B(400, { error: "email required" });
817
- let r = yield* t.findByEmail(e.email);
818
- if (r) {
819
- let i = b("magic-link");
820
- yield* t.insertToken({
821
- id: u("tok"),
822
- tokenHash: i.tokenHash,
823
- userId: r.id,
824
- purpose: "magic-link",
825
- expiresAt: i.expiresAt
826
- }).pipe(D.ignore);
827
- let a = it(n.appBaseUrl ?? "", e.callbackPath ?? "/auth/magic-link/callback", i.token);
828
- n.sendEmail && (yield* D.tryPromise(() => n.sendEmail({
829
- to: r.email,
830
- kind: "magic-link",
831
- actionUrl: a,
832
- subject: "Your sign-in link",
833
- text: `Sign in: ${a}`,
834
- html: `<p><a href="${a}">Sign in</a> — this link expires shortly.</p>`
835
- })).pipe(D.ignore));
836
- }
837
- return B(202, { ok: !0 });
838
- }), ot = (e, t, n) => D.gen(function* () {
839
- if (!e.token) return B(400, { error: "token required" });
840
- let r = yield* t.consumeToken(v(e.token), "magic-link");
841
- if (!r) return B(401, { error: "invalid or expired token" });
842
- let i = yield* t.findById(r.userId);
843
- if (!i) return B(401, { error: "invalid or expired token" });
844
- let a = yield* t.markEmailVerified(i.id).pipe(D.orElseSucceed(() => i)), o = yield* U(a, n);
845
- if (o) return o;
846
- let { setCookie: s, subject: c } = yield* H(a, t, n);
847
- return e.redirectAfter ? V(n.successRedirect ?? "/", { setCookie: s }) : B(200, {
848
- ok: !0,
849
- subject: c
850
- }, { setCookie: s });
851
- }), st = (e, t, n) => D.gen(function* () {
852
- if (!e.email) return B(400, { error: "email required" });
853
- let r = yield* t.findByEmail(e.email);
854
- if (r) {
855
- let i = b("password-reset");
856
- yield* t.insertToken({
857
- id: u("tok"),
858
- tokenHash: i.tokenHash,
859
- userId: r.id,
860
- purpose: "password-reset",
861
- expiresAt: i.expiresAt
862
- }).pipe(D.ignore);
863
- let a = it(n.appBaseUrl ?? "", e.callbackPath ?? "/auth/password-reset/callback", i.token);
864
- n.sendEmail && (yield* D.tryPromise(() => n.sendEmail({
865
- to: r.email,
866
- kind: "password-reset",
867
- actionUrl: a,
868
- subject: "Reset your password",
869
- text: `Reset your password: ${a}`,
870
- html: `<p><a href="${a}">Reset your password</a> — this link expires shortly.</p>`
871
- })).pipe(D.ignore));
872
- }
873
- return B(202, { ok: !0 });
874
- }), ct = (t, n) => D.gen(function* () {
875
- if (!t.token || !t.newPassword) return B(400, { error: "token and newPassword required" });
876
- if (t.newPassword.length < 8) return B(400, { error: "password must be at least 8 characters" });
877
- let r = yield* n.consumeToken(v(t.token), "password-reset");
878
- if (!r) return B(401, { error: "invalid or expired token" });
879
- let i = yield* e(t.newPassword).pipe(D.orElseSucceed(() => ""));
880
- return i ? (yield* n.updatePassword(r.userId, i).pipe(D.ignore), yield* n.markEmailVerified(r.userId).pipe(D.ignore), yield* n.revokeAllSessions(r.userId).pipe(D.ignore), B(200, { ok: !0 })) : B(500, { error: "hash_failed" });
881
- }), lt = (e, t) => D.gen(function* () {
882
- return B(200, { sessions: (yield* t.listSessions(e.userId)).map((e) => ({
883
- id: e.id,
884
- tenantId: e.tenantId,
885
- ipAddress: e.ipAddress ?? null,
886
- userAgent: e.userAgent ?? null,
887
- createdAt: e.createdAt.toISOString(),
888
- lastSeenAt: e.lastSeenAt.toISOString(),
889
- expiresAt: e.expiresAt.toISOString()
890
- })) });
891
- }), ut = (e, t) => D.gen(function* () {
892
- return (yield* t.revokeSession(e.userId, e.sessionId)) ? B(200, {
893
- ok: !0,
894
- revoked: 1
895
- }) : B(404, { error: "session_not_found" });
896
- }), dt = (e, t) => D.gen(function* () {
897
- return B(200, {
898
- ok: !0,
899
- revoked: yield* t.revokeAllOtherSessions(e.userId, e.keepSessionId)
900
- });
901
- }), ft = (e, t, n, i, o) => D.gen(function* () {
902
- let s = yield* t.findById(e.userId);
903
- if (!s) return B(404, { error: "user_not_found" });
904
- let c = yield* t.listMemberships(s.id), l = c.find((t) => t.tenantId === e.targetTenantId)?.role ?? null;
905
- if (l === null) return B(403, { error: "not a member of the target tenant" });
906
- let u = e.metadata === void 0 ? void 0 : Object.fromEntries(Object.entries(e.metadata).filter(([e]) => e !== "memberships")), d = pe(g(s, { ...u === void 0 ? {} : { metadata: u } }), e.targetTenantId, c);
907
- o !== void 0 && d.type === "user" && (yield* D.promise(() => ue(o, {
908
- type: d.type,
909
- id: d.id
910
- }, e.targetTenantId)));
911
- let f = e.sessionId ? Je(d, e.sessionId) : d, p = a(f, R(n), {
912
- ttlSeconds: qe,
913
- ...n.cookieDomain ? { domain: n.cookieDomain } : {},
914
- secure: n.cookieSecure ?? !0
915
- });
916
- return e.clientId !== void 0 && i && i(e.clientId, { cookies: { [r]: p.value } }), B(200, {
917
- ok: !0,
918
- tenantId: e.targetTenantId,
919
- role: l,
920
- subject: f
921
- }, { setCookie: p.setCookie });
922
- }), pt = (e, t) => D.gen(function* () {
923
- return B(200, { memberships: (yield* t.listMemberships(e.userId)).map((e) => ({
924
- tenantId: e.tenantId,
925
- role: e.role,
926
- joinedAt: e.joinedAt.toISOString()
927
- })) });
928
- }), W = (e, t, n = {}) => ({
929
- status: e,
930
- body: JSON.stringify(t),
931
- contentType: "application/json; charset=utf-8",
932
- ...n
933
- }), mt = 604800, ht = () => {
934
- let e = /* @__PURE__ */ new Map();
935
- return {
936
- put: (t, n, r) => D.sync(() => {
937
- e.set(t, {
938
- challenge: n,
939
- expiresAt: Date.now() + r * 1e3
940
- });
941
- }),
942
- take: (t) => D.sync(() => {
943
- let n = e.get(t);
944
- return e.delete(t), !n || n.expiresAt < Date.now() ? null : n.challenge;
945
- })
946
- };
947
- }, gt = (e) => ({
948
- put: (t, n, r) => D.gen(function* () {
949
- let i = /* @__PURE__ */ new Date(), a = new Date(i.getTime() + r * 1e3);
950
- (yield* e`
951
- UPDATE "passkeyChallenges"
952
- SET challenge = ${n}, "expiresAt" = ${a}, "createdAt" = ${i}
953
- WHERE key = ${t}
954
- RETURNING key
955
- `).length === 0 && (yield* e`
956
- INSERT INTO "passkeyChallenges" (id, key, challenge, "expiresAt", "createdAt")
957
- VALUES (${u("pkc")}, ${t}, ${n}, ${a}, ${i})
958
- `);
959
- }).pipe(D.asVoid, D.orElseSucceed(() => void 0)),
960
- take: (t) => D.gen(function* () {
961
- let n = (yield* e`
962
- DELETE FROM "passkeyChallenges" WHERE key = ${t}
963
- RETURNING challenge, "expiresAt"
964
- `)[0];
965
- return n && n.expiresAt.getTime() > Date.now() ? n.challenge : null;
966
- }).pipe(D.orElseSucceed(() => null))
967
- }), G = 300, _t = (e, t, n, r) => D.gen(function* () {
968
- if (!(yield* t.findById(e.userId))) return W(404, { error: "user_not_found" });
969
- let i = S();
970
- yield* n.put(`${e.userId}:register`, i, G);
971
- let a = yield* t.listPasskeys(e.userId);
972
- return W(200, {
973
- challenge: i,
974
- rp: {
975
- id: r.rpId,
976
- name: r.rpName
977
- },
978
- user: {
979
- id: e.userId,
980
- name: e.userName,
981
- displayName: e.userName
982
- },
983
- pubKeyCredParams: [{
984
- type: "public-key",
985
- alg: -7
986
- }, {
987
- type: "public-key",
988
- alg: -257
989
- }],
990
- excludeCredentials: a.map((e) => ({
991
- type: "public-key",
992
- id: e.credentialId
993
- })),
994
- authenticatorSelection: {
995
- userVerification: "preferred",
996
- residentKey: "preferred"
997
- },
998
- timeout: G * 1e3
999
- });
1000
- }), vt = (e, t, n, r) => D.gen(function* () {
1001
- if (!(yield* t.findById(e.userId))) return W(404, { error: "user_not_found" });
1002
- let i = yield* n.take(`${e.userId}:register`);
1003
- if (!i) return W(400, { error: "no_pending_challenge" });
1004
- let a = C({
1005
- clientDataJSON: e.clientDataJSON,
1006
- authenticatorData: e.authenticatorData,
1007
- expectedChallenge: i,
1008
- expectedOrigin: r.origin,
1009
- rpId: r.rpId
1010
- });
1011
- return a.ok ? (yield* t.insertPasskey({
1012
- id: u("pk"),
1013
- credentialId: a.result.credentialId,
1014
- userId: e.userId,
1015
- publicKey: a.result.publicKey,
1016
- counter: a.result.counter,
1017
- transports: e.transports ?? null
1018
- }).pipe(D.ignore), W(200, {
1019
- ok: !0,
1020
- credentialId: a.result.credentialId
1021
- })) : W(400, { error: a.error });
1022
- }), yt = (e, t, n, r) => D.gen(function* () {
1023
- let i = S(), a = e.userId ? `${e.userId}:assert` : "*:assert";
1024
- yield* n.put(a, i, G);
1025
- let o = e.userId ? (yield* t.listPasskeys(e.userId)).map((e) => ({
1026
- type: "public-key",
1027
- id: e.credentialId
1028
- })) : [];
1029
- return W(200, {
1030
- challenge: i,
1031
- rpId: r.rpId,
1032
- allowCredentials: o,
1033
- userVerification: "preferred",
1034
- timeout: G * 1e3
1035
- });
1036
- }), bt = (e, t, n, r, i) => D.gen(function* () {
1037
- let o = yield* t.findPasskey(e.credentialId);
1038
- if (!o) return W(401, { error: "unknown_credential" });
1039
- let s = e.userId ? `${e.userId}:assert` : "*:assert", c = yield* n.take(s);
1040
- if (!c) return W(400, { error: "no_pending_challenge" });
1041
- let l = re({
1042
- clientDataJSON: e.clientDataJSON,
1043
- authenticatorData: e.authenticatorData,
1044
- signature: e.signature,
1045
- expectedChallenge: c,
1046
- expectedOrigin: r.origin,
1047
- rpId: r.rpId,
1048
- storedPublicKey: o.publicKey,
1049
- storedCounter: o.counter
1050
- });
1051
- if (!l.ok) return W(401, { error: l.error });
1052
- if (!(yield* t.advancePasskeyCounter(e.credentialId, l.result.newCounter)) && l.result.newCounter !== 0) return W(401, { error: "counter_regressed" });
1053
- let d = yield* t.findById(o.userId);
1054
- if (!d) return W(401, { error: "unknown_credential" });
1055
- let f = yield* U(d, i);
1056
- if (f) return f;
1057
- let p = yield* t.listMemberships(d.id), m = u("sess");
1058
- yield* t.insertSession({
1059
- id: m,
1060
- userId: d.id,
1061
- tenantId: d.tenantId,
1062
- expiresAt: new Date(Date.now() + mt * 1e3),
1063
- ipAddress: null,
1064
- userAgent: null
1065
- }).pipe(D.ignore);
1066
- let h = g(d, { memberships: p }), _ = h.type === "user" ? {
1067
- ...h,
1068
- metadata: {
1069
- ...h.metadata ?? {},
1070
- sessionId: m
1071
- }
1072
- } : h, v = a(_, R(i), {
1073
- ttlSeconds: mt,
1074
- ...i.cookieDomain ? { domain: i.cookieDomain } : {},
1075
- secure: i.cookieSecure ?? !0
1076
- });
1077
- return W(200, {
1078
- ok: !0,
1079
- subject: _
1080
- }, { setCookie: v.setCookie });
1081
- }), xt = 604800, St = 500, Ct = [
1082
- "owner",
1083
- "admin",
1084
- "member",
1085
- "viewer"
1086
- ], wt = ["owner", "admin"], Tt = (e, t) => t.indexOf(e), Et = (e, t = Ct) => {
1087
- let n = Tt(e.inviterRole, t);
1088
- if (n < 0) return !1;
1089
- let r = Tt(e.requestedRole, t);
1090
- return r < 0 ? n === 0 : r >= n;
1091
- }, Dt = (e) => {
1092
- let t = e?.roleRank ?? Ct;
1093
- return e?.canGrantRole ?? ((e) => Et(e, t));
1094
- }, K = (e, t, n = {}) => ({
1095
- status: e,
1096
- body: JSON.stringify(t),
1097
- contentType: "application/json; charset=utf-8",
1098
- ...n
1099
- }), Ot = (e, t, n) => `${e}${t}${t.includes("?") ? "&" : "?"}token=${encodeURIComponent(n)}`, kt = (e) => ({
1100
- id: e.id,
1101
- email: e.email,
1102
- tenantId: e.tenantId,
1103
- role: e.role,
1104
- invitedByUserId: e.invitedByUserId,
1105
- expiresAt: e.expiresAt.toISOString(),
1106
- acceptedAt: e.acceptedAt?.toISOString() ?? null,
1107
- revokedAt: e.revokedAt?.toISOString() ?? null,
1108
- createdAt: e.createdAt.toISOString()
1109
- }), At = (e, t, n, r) => D.gen(function* () {
1110
- let i = yield* n.membershipRole(e, t);
1111
- return i === null || !(r?.inviterRoles ?? wt).includes(i) ? K(403, { error: "not_permitted" }) : { role: i };
1112
- }), jt = (e) => "status" in e, Mt = (e, t, n) => D.gen(function* () {
1113
- let r = e.email.trim().toLowerCase();
1114
- if (!r || !r.includes("@")) return K(400, { error: "a valid email is required" });
1115
- if (!e.tenantId) return K(400, { error: "tenantId required" });
1116
- if (!e.role) return K(400, { error: "role required" });
1117
- let i = n.invitations, a = yield* At(e.inviterUserId, e.tenantId, t, i);
1118
- if (jt(a)) return a;
1119
- if (!Dt(i)({
1120
- inviterRole: a.role,
1121
- requestedRole: e.role,
1122
- tenantId: e.tenantId
1123
- })) return K(403, {
1124
- error: "role_not_grantable",
1125
- message: `A '${a.role}' may not invite a '${e.role}'.`
1126
- });
1127
- let o = new Date((n.now ?? Date.now)());
1128
- if ((yield* t.countPendingInvitations(e.tenantId, o)) >= (i?.maxPending ?? 500)) return K(429, { error: "too_many_pending_invitations" });
1129
- yield* t.supersedePendingInvitations(e.tenantId, r, e.inviterUserId, o).pipe(D.ignore);
1130
- let s = i?.ttlSeconds ?? 604800, c = y(s), l = yield* t.insertInvitation({
1131
- id: u("inv"),
1132
- tokenHash: c.tokenHash,
1133
- email: r,
1134
- tenantId: e.tenantId,
1135
- role: e.role,
1136
- invitedByUserId: e.inviterUserId,
1137
- expiresAt: new Date(o.getTime() + s * 1e3)
1138
- });
1139
- if (n.sendEmail) {
1140
- let t = Ot(n.appBaseUrl ?? "", i?.callbackPath ?? "/auth/invitations/accept", c.token);
1141
- yield* D.tryPromise(() => n.sendEmail({
1142
- to: r,
1143
- kind: "invitation",
1144
- actionUrl: t,
1145
- subject: "You have been invited",
1146
- text: `You have been invited to join as ${e.role}: ${t}`,
1147
- html: `<p>You have been invited to join as <strong>${e.role}</strong>. <a href="${t}">Accept the invitation</a> — this link expires.</p>`
1148
- })).pipe(D.ignore);
1149
- }
1150
- return K(201, {
1151
- ok: !0,
1152
- invitation: kt(l)
1153
- });
1154
- }), Nt = (e, t, n) => D.gen(function* () {
1155
- let r = yield* At(e.callerUserId, e.tenantId, t, n.invitations);
1156
- return jt(r) ? r : K(200, { invitations: (yield* t.listInvitations(e.tenantId)).map(kt) });
1157
- }), Pt = (e, t, n) => D.gen(function* () {
1158
- if (!e.invitationId) return K(400, { error: "invitationId required" });
1159
- let r = yield* At(e.callerUserId, e.tenantId, t, n.invitations);
1160
- if (jt(r)) return r;
1161
- let i = new Date((n.now ?? Date.now)());
1162
- return (yield* t.revokeInvitation(e.invitationId, e.tenantId, e.callerUserId, i)) ? K(200, {
1163
- ok: !0,
1164
- revoked: 1
1165
- }) : K(404, { error: "invitation_not_found" });
1166
- }), Ft = (e, t, n = {}) => D.gen(function* () {
1167
- if (!e.token) return K(400, { error: "token required" });
1168
- let r = yield* t.findInvitationByHash(v(e.token));
1169
- if (!r) return K(404, { error: "invalid_invitation" });
1170
- let i = new Date((n.now ?? Date.now)());
1171
- return K(200, {
1172
- ok: !0,
1173
- state: r.acceptedAt === null ? r.revokedAt === null ? r.expiresAt.getTime() <= i.getTime() ? "expired" : "pending" : "revoked" : "accepted",
1174
- email: r.email,
1175
- tenantId: r.tenantId,
1176
- role: r.role,
1177
- expiresAt: r.expiresAt.toISOString()
1178
- });
1179
- }), It = (e, t, n = {}) => D.gen(function* () {
1180
- if (!e.token) return K(400, { error: "token required" });
1181
- let r = v(e.token), i = new Date((n.now ?? Date.now)()), a = yield* t.findInvitationByHash(r);
1182
- if (!a) return K(401, { error: "invalid_or_expired_invitation" });
1183
- if (!e.userId) return K(401, {
1184
- error: "authentication_required",
1185
- email: a.email
1186
- });
1187
- let o = yield* t.findById(e.userId);
1188
- if (!o) return K(401, {
1189
- error: "authentication_required",
1190
- email: a.email
1191
- });
1192
- if (o.email.toLowerCase() !== a.email.toLowerCase()) return K(403, {
1193
- error: "invitation_email_mismatch",
1194
- message: "This invitation was issued to a different email address. Sign in as that address to accept it."
1195
- });
1196
- let s = yield* P(n.admit, {
1197
- email: a.email,
1198
- tenantId: a.tenantId,
1199
- via: "invitation"
1200
- });
1201
- if (s) return K(403, {
1202
- error: "not_admitted",
1203
- reason: s.reason,
1204
- message: s.message
1205
- });
1206
- let c = yield* t.acceptInvitation(r, o.id, i);
1207
- if (!c) return K(401, { error: "invalid_or_expired_invitation" });
1208
- let l = yield* t.addMembership({
1209
- userId: o.id,
1210
- tenantId: c.tenantId,
1211
- role: c.role
1212
- });
1213
- return yield* t.markEmailVerified(o.id).pipe(D.ignore), K(200, {
1214
- ok: !0,
1215
- membership: {
1216
- tenantId: l.tenantId,
1217
- role: l.role,
1218
- joinedAt: l.joinedAt.toISOString()
1219
- }
1220
- });
1221
- }), Lt = (e, t, n) => D.gen(function* () {
1222
- if (!e.token || !e.password) return K(400, { error: "token and password required" });
1223
- if (e.password.length < (n.minPasswordLength ?? 8)) return K(400, { error: "password must be at least 8 characters" });
1224
- let r = v(e.token), i = new Date((n.now ?? Date.now)()), a = yield* t.findInvitationByHash(r);
1225
- if (!a) return K(401, { error: "invalid_or_expired_invitation" });
1226
- if (yield* t.findByEmail(a.email)) return K(409, {
1227
- error: "account_exists",
1228
- message: "An account already exists for this address. Sign in, then accept the invitation."
1229
- });
1230
- let o = yield* n.hashPassword(e.password).pipe(D.orElseSucceed(() => ""));
1231
- if (!o) return K(500, { error: "hash_failed" });
1232
- let s = yield* P(n.admit, {
1233
- email: a.email,
1234
- tenantId: a.tenantId,
1235
- via: "invitation"
1236
- });
1237
- if (s) return K(403, {
1238
- error: "not_admitted",
1239
- reason: s.reason,
1240
- message: s.message
1241
- });
1242
- let c = u("user"), l = yield* t.acceptInvitation(r, c, i);
1243
- if (!l) return K(401, { error: "invalid_or_expired_invitation" });
1244
- let d = yield* t.insert({
1245
- id: c,
1246
- email: l.email,
1247
- passwordHash: o,
1248
- tenantId: l.tenantId
1249
- }).pipe(D.orElseSucceed(() => null));
1250
- return d ? (yield* t.addMembership({
1251
- userId: d.id,
1252
- tenantId: l.tenantId,
1253
- role: l.role
1254
- }), yield* t.markEmailVerified(d.id).pipe(D.ignore), K(201, {
1255
- ok: !0,
1256
- userId: d.id,
1257
- tenantId: l.tenantId,
1258
- role: l.role
1259
- })) : K(409, { error: "account_exists" });
1260
- }), Rt = 900, zt = [
1261
- "/mfa/enroll/start",
1262
- "/mfa/enroll/verify",
1263
- "/mfa/unenroll",
1264
- "/mfa/recovery-codes/regenerate",
1265
- "/passkey/register/options",
1266
- "/passkey/register/verify",
1267
- "/sessions/revoke-others",
1268
- "/switch-tenant",
1269
- "/impersonate/start"
1270
- ], Bt = (e) => {
1271
- if (typeof e != "object" || !e) return null;
1272
- let t = e;
1273
- return typeof t.actorUserId != "string" || t.actorUserId.length === 0 || typeof t.grantId != "string" || typeof t.expiresAt != "string" || typeof t.actorSessionId != "string" || typeof t.startedAt != "string" ? null : {
1274
- actorUserId: t.actorUserId,
1275
- actorSessionId: t.actorSessionId,
1276
- grantId: t.grantId,
1277
- startedAt: t.startedAt,
1278
- expiresAt: t.expiresAt,
1279
- ...typeof t.reason == "string" ? { reason: t.reason } : {}
1280
- };
1281
- }, Vt = (e) => e.type === "user" ? Bt(fe(e)) : null, Ht = (e) => Vt(e) !== null, Ut = () => (e) => {
1282
- if (e.type !== "user" || e.metadata === void 0) return e;
1283
- let t = Bt(e.metadata[k]), { metadata: n, ...r } = e;
1284
- return {
1285
- ...r,
1286
- metadata: t === null ? { __redacted: "all" } : {
1287
- __redacted: "all-except-impersonation",
1288
- [k]: t
1289
- }
1290
- };
1291
- }, q = (e, t, n = {}) => ({
1292
- status: e,
1293
- body: JSON.stringify(t),
1294
- contentType: "application/json; charset=utf-8",
1295
- ...n
1296
- }), Wt = (e, t) => D.suspend(() => {
1297
- let n = e.audit(t);
1298
- return n === void 0 ? D.void : D.isEffect(n) ? n : D.tryPromise({
1299
- try: () => Promise.resolve(n),
1300
- catch: (e) => e
1301
- });
1302
- }).pipe(D.catchCause(() => D.void)), Gt = (e, t, n) => D.gen(function* () {
1303
- let r = n.impersonation, i = (n.now ?? Date.now)(), a = new Date(i), o = e.actorSubject, s = (t, n, i = {}) => Wt(r, {
1304
- kind: "refused",
1305
- at: a,
1306
- actorUserId: i.actorUser?.id ?? (o.type === "user" ? o.id : null),
1307
- actorEmail: i.actorUser?.email ?? null,
1308
- targetUserId: i.target?.id ?? null,
1309
- targetEmail: i.target?.email ?? null,
1310
- tenantId: o.tenantId ?? null,
1311
- reason: e.reason ?? null,
1312
- refusal: n,
1313
- ipAddress: e.ipAddress ?? null,
1314
- userAgent: e.userAgent ?? null
1315
- }).pipe(D.as(q(t, {
1316
- error: n,
1317
- ...i.message === void 0 ? {} : { message: i.message }
1318
- })));
1319
- if (o.type !== "user") return yield* s(401, "unauthenticated");
1320
- if (Ht(o)) return yield* s(403, "nested_impersonation", { message: "An impersonated session may not start another impersonation. Stop the current one first." });
1321
- if (!e.actorSessionId) return yield* s(400, "no_actor_session");
1322
- let c = yield* t.findById(o.id);
1323
- if (!c) return yield* s(401, "unauthenticated");
1324
- if (!e.targetUserId && !e.targetEmail) return yield* s(400, "target_required", { actorUser: c });
1325
- let l = e.targetUserId ? yield* t.findById(e.targetUserId) : yield* t.findByEmail(e.targetEmail);
1326
- if (!l) return yield* s(404, "target_not_found", { actorUser: c });
1327
- if (l.id === c.id) return yield* s(400, "self_impersonation", {
1328
- actorUser: c,
1329
- target: l
1330
- });
1331
- let d = e.reason?.trim() ?? "";
1332
- if ((r.requireReason ?? !0) && d.length === 0) return yield* s(400, "reason_required", {
1333
- actorUser: c,
1334
- target: l,
1335
- message: "A reason is required to impersonate a user."
1336
- });
1337
- if (!(yield* r.authority({
1338
- actor: o,
1339
- actorUser: c,
1340
- target: l
1341
- }).pipe(D.catchCause(() => D.succeed(!1))))) return yield* s(403, "not_permitted", {
1342
- actorUser: c,
1343
- target: l
1344
- });
1345
- if (yield* r.authority({
1346
- actor: g(l),
1347
- actorUser: l,
1348
- target: c
1349
- }).pipe(D.catchCause(() => D.succeed(!0)))) return yield* s(403, "target_may_impersonate", {
1350
- actorUser: c,
1351
- target: l,
1352
- message: "This user may themselves impersonate others and cannot be impersonated."
1353
- });
1354
- let f = r.maxDurationSeconds ?? 900, p = Math.max(1, Math.min(e.durationSeconds ?? f, f)), m = new Date(i + p * 1e3), h = u("sess"), _ = yield* t.insertImpersonationGrant({
1355
- id: u("imp"),
1356
- sessionId: h,
1357
- actorUserId: c.id,
1358
- actorSessionId: e.actorSessionId,
1359
- targetUserId: l.id,
1360
- tenantId: l.tenantId,
1361
- reason: d.length > 0 ? d : null,
1362
- expiresAt: m,
1363
- ipAddress: e.ipAddress ?? null,
1364
- userAgent: e.userAgent ?? null
1365
- }), v = {
1366
- actorUserId: c.id,
1367
- actorSessionId: e.actorSessionId,
1368
- grantId: _.id,
1369
- startedAt: _.startedAt.toISOString(),
1370
- expiresAt: m.toISOString(),
1371
- ...d.length > 0 ? { reason: d } : {}
1372
- }, y = yield* n.issuer.issue(l, {
1373
- sessionId: h,
1374
- ttlSeconds: p,
1375
- metadata: { [k]: v },
1376
- ipAddress: e.ipAddress ?? null,
1377
- userAgent: e.userAgent ?? null
1378
- });
1379
- return yield* Wt(r, {
1380
- kind: "started",
1381
- at: a,
1382
- actorUserId: c.id,
1383
- actorEmail: c.email,
1384
- targetUserId: l.id,
1385
- targetEmail: l.email,
1386
- tenantId: l.tenantId,
1387
- sessionId: h,
1388
- grantId: _.id,
1389
- reason: d.length > 0 ? d : null,
1390
- expiresAt: m,
1391
- ipAddress: e.ipAddress ?? null,
1392
- userAgent: e.userAgent ?? null
1393
- }), q(200, {
1394
- ok: !0,
1395
- impersonation: v,
1396
- subject: y.subject
1397
- }, { setCookie: y.setCookie });
1398
- }), Kt = (e, t, n) => D.gen(function* () {
1399
- let r = n.impersonation, i = (n.now ?? Date.now)(), a = new Date(i), o = Vt(e.subject);
1400
- if (!o || !e.sessionId) return q(400, { error: "not_impersonating" });
1401
- let s = yield* t.findImpersonationGrantBySession(e.sessionId);
1402
- yield* t.endImpersonationGrant(e.sessionId, "stopped", a).pipe(D.ignore), e.subject.type === "user" && (yield* t.revokeSession(e.subject.id, e.sessionId).pipe(D.ignore)), n.invalidateSession?.(e.sessionId);
1403
- let c = yield* t.findById(o.actorUserId), l = yield* t.findSession(o.actorSessionId), u = l ? Math.floor((l.expiresAt.getTime() - i) / 1e3) : 0;
1404
- if (yield* Wt(r, {
1405
- kind: "stopped",
1406
- at: a,
1407
- actorUserId: o.actorUserId,
1408
- actorEmail: c?.email ?? null,
1409
- targetUserId: e.subject.type === "user" ? e.subject.id : null,
1410
- targetEmail: null,
1411
- tenantId: s?.tenantId ?? e.subject.tenantId ?? null,
1412
- sessionId: e.sessionId,
1413
- ...s ? { grantId: s.id } : {},
1414
- reason: s?.reason ?? null
1415
- }), !c || !l || u <= 0) return q(200, {
1416
- ok: !0,
1417
- restored: !1
1418
- }, { setCookie: n.issuer.clear() });
1419
- let d = yield* n.issuer.reissue(c, {
1420
- sessionId: o.actorSessionId,
1421
- ttlSeconds: u
1422
- });
1423
- return q(200, {
1424
- ok: !0,
1425
- restored: !0,
1426
- subject: d.subject
1427
- }, { setCookie: d.setCookie });
1428
- }), qt = "voltro:native", Jt = 600, Yt = "/login", J = (e) => e.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""), Xt = (e) => Buffer.from(e.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - e.length % 4) % 4), "base64"), Zt = (e) => J(w("sha256").update(e, "ascii").digest()), Qt = (e, t) => {
1429
- let n = J(Buffer.from(JSON.stringify(e), "utf8"));
1430
- return `${n}.${J(T("sha256", t).update(n).digest())}`;
1431
- }, $t = (e, t, n = Date.now) => {
1432
- if (!e) return null;
1433
- let r = e.indexOf(".");
1434
- if (r <= 0 || r === e.length - 1) return null;
1435
- let i = e.slice(0, r), a = Xt(e.slice(r + 1)), o = T("sha256", t).update(i).digest();
1436
- if (a.length !== o.length || !ie(a, o)) return null;
1437
- try {
1438
- let e = JSON.parse(Xt(i).toString("utf8"));
1439
- return typeof e.exp != "number" || e.exp * 1e3 < n() ? null : e;
1440
- } catch {
1441
- return null;
1442
- }
1443
- }, en = (e, t) => t.includes(e), tn = (e, t) => {
1444
- let n = new URLSearchParams(t).toString();
1445
- return `${e}${e.includes("?") ? "&" : "?"}${n}`;
1446
- }, Y = (e, t) => ({
1447
- status: e,
1448
- body: JSON.stringify(t),
1449
- contentType: "application/json; charset=utf-8"
1450
- }), X = (e, t) => ({
1451
- status: 302,
1452
- body: "",
1453
- location: e,
1454
- ...t === void 0 ? {} : { setCookie: t }
1455
- }), nn = (e) => {
1456
- if (!e) return null;
1457
- let { ch: t, r: n, s: r, exp: i } = e;
1458
- return typeof t != "string" || typeof n != "string" || typeof r != "string" || typeof i != "number" ? null : {
1459
- ch: t,
1460
- r: n,
1461
- s: r,
1462
- exp: i
1463
- };
1464
- }, rn = (e, t, n) => O(e.native.pendingCookieName ?? "voltro:native", t, {
1465
- maxAgeSeconds: n,
1466
- httpOnly: !0,
1467
- sameSite: "lax",
1468
- secure: e.config.cookieSecure ?? !0,
1469
- path: `${e.prefix}/native`
1470
- }), an = (e) => `${e.native.loginPath ?? Yt}?next=${encodeURIComponent(`${e.prefix}/native/complete`)}`, on = (e, t, n, r) => D.gen(function* () {
1471
- let i = e.get("redirect_uri") ?? "", a = e.get("code_challenge") ?? "", o = e.get("code_challenge_method") ?? "S256", s = e.get("state") ?? "";
1472
- if (!en(i, r.native.redirectUris)) return Y(400, { error: "redirect_uri_not_allowed" });
1473
- if (o !== "S256" || a.length < 43 || a.length > 128) return X(tn(i, {
1474
- error: "invalid_request",
1475
- state: s
1476
- }));
1477
- if (s.length === 0) return X(tn(i, { error: "invalid_request" }));
1478
- let c = r.now ?? Date.now, l = r.native.pendingTtlSeconds ?? Jt, u = {
1479
- ch: a,
1480
- r: i,
1481
- s,
1482
- exp: Math.floor(c() / 1e3) + l
1483
- }, d = rn(r, Qt({ ...u }, z(r.config)), l);
1484
- return t && t.subject.type === "user" && t.sessionId ? {
1485
- ...yield* sn(u, {
1486
- userId: t.subject.id,
1487
- sessionId: t.sessionId
1488
- }, n, r),
1489
- setCookie: rn(r, "", 0)
1490
- } : X(an(r), d);
1491
- }), sn = (e, t, n, r) => D.gen(function* () {
1492
- let i = b("native-code", 300);
1493
- yield* n.insertToken({
1494
- id: `tok_${J(E(12))}`,
1495
- tokenHash: i.tokenHash,
1496
- userId: t.userId,
1497
- purpose: "native-code",
1498
- expiresAt: i.expiresAt
1499
- });
1500
- let a = Qt({
1501
- sid: t.sessionId,
1502
- uid: t.userId,
1503
- ch: e.ch,
1504
- exp: Math.floor(i.expiresAt.getTime() / 1e3)
1505
- }, z(r.config));
1506
- return X(tn(e.r, {
1507
- code: `${i.token}.${a}`,
1508
- state: e.s
1509
- }));
1510
- }), cn = (e, t, n, r) => D.gen(function* () {
1511
- let i = nn($t(se(e, r.native.pendingCookieName ?? "voltro:native"), z(r.config), r.now));
1512
- return i ? !t || t.subject.type !== "user" || !t.sessionId ? X(an(r)) : {
1513
- ...yield* sn(i, {
1514
- userId: t.subject.id,
1515
- sessionId: t.sessionId
1516
- }, n, r),
1517
- setCookie: rn(r, "", 0)
1518
- } : Y(400, { error: "no_pending_native_login" });
1519
- }), ln = (e, t, n) => D.gen(function* () {
1520
- let r = e.code.indexOf(".");
1521
- if (r <= 0) return Y(400, { error: "invalid_code" });
1522
- let i = e.code.slice(0, r), a = $t(e.code.slice(r + 1), z(n.config), n.now), o = a?.sid, s = a?.uid, c = a?.ch;
1523
- if (typeof o != "string" || typeof s != "string" || typeof c != "string") return Y(400, { error: "invalid_code" });
1524
- let l = yield* t.consumeToken(v(i), "native-code");
1525
- if (!l || l.userId !== s || e.codeVerifier.length < 43 || Zt(e.codeVerifier) !== c) return Y(400, { error: "invalid_code" });
1526
- let u = yield* t.findById(s);
1527
- if (!u) return Y(400, { error: "invalid_code" });
1528
- let d = yield* H(u, t, n.config, {
1529
- sessionId: o,
1530
- sessionRow: "existing",
1531
- clearLoginFailures: !1
1532
- });
1533
- return Y(200, {
1534
- ok: !0,
1535
- session: d.value,
1536
- expiresAt: d.expiresAt,
1537
- subject: d.subject
1538
- });
1539
- }), un = (e) => {
1540
- for (let t of e) if (dn(t)) return t.auth.sessionStrategy;
1541
- return null;
1542
- }, dn = (e) => typeof e.auth == "object" && e.auth !== null && typeof e.auth.sessionStrategy == "object", fn = "/auth", pn = (e) => {
1543
- let t = Buffer.from(e.rawBody).toString("utf8");
1544
- if (!t) return {};
1545
- if ((e.headers["content-type"] ?? "").includes("application/x-www-form-urlencoded")) {
1546
- let e = new URLSearchParams(t), n = {};
1547
- for (let [t, r] of e) n[t] = r;
1548
- return n;
1549
- }
1550
- try {
1551
- let e = JSON.parse(t);
1552
- return typeof e == "object" && e ? e : {};
1553
- } catch {
1554
- return {};
1555
- }
1556
- }, mn = (e) => ({
1557
- status: e.status,
1558
- ...e.body === void 0 ? {} : { body: e.body },
1559
- ...e.contentType === void 0 ? {} : { contentType: e.contentType },
1560
- headers: {
1561
- ...e.setCookie === void 0 ? {} : { "set-cookie": e.setCookie },
1562
- ...e.location === void 0 ? {} : { location: e.location }
1563
- }
1564
- }), hn = "actors", Z = (e, t) => ({
1565
- status: e,
1566
- body: JSON.stringify(t),
1567
- contentType: "application/json; charset=utf-8"
1568
- }), Q = (e) => typeof e == "string" ? e : void 0, $ = (e, t) => typeof t == "string" && t.length > 0 ? { [e]: t } : {}, gn = (t) => {
1569
- let n = t.prefix ?? fn, r = { current: typeof t.store == "function" ? void 0 : t.store }, s = typeof t.store == "function" ? ve(() => r.current) : t.store, c = t.challengeStore ?? ht(), l = { current: void 0 }, u = t.admit === void 0 ? void 0 : (e, n) => t.admit(e, { store: n.store ?? l.current }), d = {
1570
- ...t.secret === void 0 ? {} : { secret: t.secret },
1571
- ...t.secrets === void 0 ? {} : { secrets: t.secrets },
1572
- defaultTenantId: t.defaultTenantId,
1573
- ...t.cookieDomain === void 0 ? {} : { cookieDomain: t.cookieDomain },
1574
- ...t.cookieSecure === void 0 ? {} : { cookieSecure: t.cookieSecure },
1575
- ...t.successRedirect === void 0 ? {} : { successRedirect: t.successRedirect },
1576
- ...t.signUpTenants === void 0 ? {} : { signUpTenants: t.signUpTenants },
1577
- ...t.sendEmail === void 0 ? {} : { sendEmail: t.sendEmail },
1578
- ...t.appBaseUrl === void 0 ? {} : { appBaseUrl: t.appBaseUrl },
1579
- subjectGuards: [...t.subjectGuards ?? [], ...F(t.emailVerification) ? [Re(t.emailVerification)] : []],
1580
- ...t.lockout === void 0 ? {} : { lockout: t.lockout },
1581
- ...t.now === void 0 ? {} : { now: t.now },
1582
- ...u === void 0 ? {} : { admit: u },
1583
- ensureActor: t.ensureActor ?? ((e) => {
1584
- let t = l.current;
1585
- return t === void 0 ? D.void : D.promise(() => t.insertIgnore(hn, {
1586
- id: e.id,
1587
- kind: "user",
1588
- displayName: null
1589
- }, { conflictColumns: ["id"] }));
1590
- }),
1591
- ...t.emailVerification === void 0 ? {} : { emailVerification: t.emailVerification }
1592
- }, p = {
1593
- ...t.appBaseUrl === void 0 ? {} : { appBaseUrl: t.appBaseUrl },
1594
- ...t.sendEmail === void 0 ? {} : { sendEmail: t.sendEmail },
1595
- ...t.invitations === void 0 ? {} : { invitations: t.invitations },
1596
- ...t.now === void 0 ? {} : { now: t.now },
1597
- ...u === void 0 ? {} : { admit: u }
1598
- };
1599
- t.invitations !== void 0 && ce({
1600
- source: "plugin",
1601
- table: "invitations",
1602
- timeColumn: "createdAt",
1603
- ttlMs: le(process.env.VOLTRO_INVITATIONS_TTL_HOURS, 2160),
1604
- envVar: "VOLTRO_INVITATIONS_TTL_HOURS"
1605
- }), t.impersonation !== void 0 && ce({
1606
- source: "plugin",
1607
- table: "impersonationGrants",
1608
- timeColumn: "startedAt",
1609
- ttlMs: le(process.env.VOLTRO_IMPERSONATION_GRANTS_TTL_HOURS, 8760),
1610
- envVar: "VOLTRO_IMPERSONATION_GRANTS_TTL_HOURS"
1611
- });
1612
- let h = f(s, t.sessionRevocation ?? {}), g = async (e) => {
1613
- let t = R(d), n = o(e.headers, t);
1614
- if (!n) return null;
1615
- let r = e.headers[oe] ? "header" : "cookie", i = m(n.subject);
1616
- if (i && !await D.runPromise(h.isLive(i))) return null;
1617
- if (n.renew || n.kid !== t.current.kid) {
1618
- let e = Math.max(n.exp - n.iat, 60), o = a(n.subject, t, {
1619
- ttlSeconds: e,
1620
- ...d.cookieDomain ? { domain: d.cookieDomain } : {},
1621
- secure: d.cookieSecure ?? !0
1622
- });
1623
- return i && await D.runPromise(s.touchSession(i, new Date(Date.now() + e * 1e3))), {
1624
- subject: n.subject,
1625
- sessionId: i,
1626
- renewSetCookie: o.setCookie,
1627
- renewValue: o.value,
1628
- via: r,
1629
- expiresAt: Math.floor(Date.now() / 1e3) + e
1630
- };
1631
- }
1632
- return {
1633
- subject: n.subject,
1634
- sessionId: i,
1635
- via: r,
1636
- expiresAt: n.exp
1637
- };
1638
- }, v = (e, t) => {
1639
- if (!t) return e;
1640
- let n = e.headers ?? {};
1641
- return n["set-cookie"] ? e : {
1642
- ...e,
1643
- headers: {
1644
- ...n,
1645
- "set-cookie": t
1646
- }
1647
- };
1648
- }, y = (e) => {
1649
- let n = e.headers[te], r = se(e.headers.cookie, ee);
1650
- return ne(n, r, z(t));
1651
- }, b = (e, t) => e.path === `${n}${t}`, x = (e) => D.runPromise(e).then(mn), S = {
1652
- issue: (e, t) => H(e, s, d, {
1653
- sessionId: t.sessionId,
1654
- ttlSeconds: t.ttlSeconds,
1655
- metadata: t.metadata,
1656
- ipAddress: t.ipAddress ?? null,
1657
- userAgent: t.userAgent ?? null,
1658
- clearLoginFailures: !1
1659
- }),
1660
- reissue: (e, t) => H(e, s, d, {
1661
- sessionId: t.sessionId,
1662
- ttlSeconds: t.ttlSeconds,
1663
- sessionRow: "existing",
1664
- clearLoginFailures: !1
1665
- }),
1666
- clear: () => i({
1667
- ...d.cookieDomain ? { domain: d.cookieDomain } : {},
1668
- secure: d.cookieSecure ?? !0
1669
- })
1670
- }, re = {
1671
- method: "*",
1672
- path: n,
1673
- handle: async (r) => {
1674
- let i = r.method === "GET" ? {} : pn(r);
1675
- if (t.native !== void 0) {
1676
- let e = {
1677
- prefix: n,
1678
- config: d,
1679
- native: t.native,
1680
- ...t.now === void 0 ? {} : { now: t.now }
1681
- };
1682
- if (r.method === "GET" && b(r, "/native/authorize")) {
1683
- let t = await g(r);
1684
- return x(on(new URLSearchParams(r.query), t, s, e));
1685
- }
1686
- if (r.method === "GET" && b(r, "/native/complete")) {
1687
- let t = await g(r);
1688
- return x(cn(r.headers.cookie, t, s, e));
1689
- }
1690
- if (r.method === "POST" && b(r, "/native/exchange")) return x(ln({
1691
- code: Q(i.code) ?? "",
1692
- codeVerifier: Q(i.codeVerifier) ?? ""
1693
- }, s, e));
1694
- } else if (r.path.startsWith(`${n}/native/`)) return Z(501, { error: "native_login_not_configured" });
1695
- if (r.method === "GET" && b(r, "/csrf")) return mn(rt(d));
1696
- if (r.method === "POST" && b(r, "/sign-in")) return x(Ye({
1697
- email: Q(i.email) ?? "",
1698
- password: Q(i.password) ?? "",
1699
- ...i.redirectAfter === void 0 ? {} : { redirectAfter: !!i.redirectAfter },
1700
- ...r.remoteAddr ? { ipAddress: r.remoteAddr } : {},
1701
- ...r.headers["user-agent"] ? { userAgent: r.headers["user-agent"] } : {}
1702
- }, s, d));
1703
- if (r.method === "POST" && b(r, "/sign-up")) {
1704
- let e = Q(i.tenantId);
1705
- return e !== void 0 && e !== d.defaultTenantId && !(d.signUpTenants ?? []).includes(e) ? {
1706
- status: 400,
1707
- headers: { "content-type": "application/json" },
1708
- body: JSON.stringify({ error: "tenant_not_open" })
1709
- } : x(Ze({
1710
- email: Q(i.email) ?? "",
1711
- password: Q(i.password) ?? "",
1712
- ...$("tenantId", e),
1713
- ...i.redirectAfter === void 0 ? {} : { redirectAfter: !!i.redirectAfter }
1714
- }, s, d));
1715
- }
1716
- if (r.method === "POST" && b(r, "/sign-out")) {
1717
- let e = await g(r);
1718
- return e && e.subject.type === "user" && e.sessionId && (await D.runPromise(s.revokeSession(e.subject.id, e.sessionId)), h.invalidate(e.sessionId)), mn(Qe(d));
1719
- }
1720
- if (r.method === "POST" && b(r, "/magic-link")) return x(at({
1721
- email: Q(i.email) ?? "",
1722
- ...$("callbackPath", i.callbackPath)
1723
- }, s, d));
1724
- if (r.method === "POST" && b(r, "/magic-link/callback")) return x(ot({
1725
- token: Q(i.token) ?? "",
1726
- ...i.redirectAfter === void 0 ? {} : { redirectAfter: !!i.redirectAfter }
1727
- }, s, d));
1728
- if (r.method === "POST" && b(r, "/password-reset")) return x(st({
1729
- email: Q(i.email) ?? "",
1730
- ...$("callbackPath", i.callbackPath)
1731
- }, s, d));
1732
- if (r.method === "POST" && b(r, "/password-reset/confirm")) return x(ct({
1733
- token: Q(i.token) ?? "",
1734
- newPassword: Q(i.newPassword) ?? ""
1735
- }, s));
1736
- if (r.method === "POST" && b(r, "/verify-email")) {
1737
- let e = Q(i.email);
1738
- if (e) return x(Ve({ email: e }, s, d));
1739
- let t = await g(r);
1740
- return !t || t.subject.type !== "user" ? Z(400, { error: "email required" }) : x(Ve({ userId: t.subject.id }, s, d));
1741
- }
1742
- if (r.method === "POST" && b(r, "/verify-email/callback")) return x(He({ token: Q(i.token) ?? "" }, s));
1743
- if (t.invitations && r.method === "POST" && b(r, "/invitations/preview")) return x(Ft({ token: Q(i.token) ?? "" }, s, p));
1744
- if (t.invitations && r.method === "POST" && b(r, "/invitations/sign-up")) return x(Lt({
1745
- token: Q(i.token) ?? "",
1746
- password: Q(i.password) ?? ""
1747
- }, s, {
1748
- ...p,
1749
- hashPassword: e
1750
- }));
1751
- if (r.method === "POST" && b(r, "/mfa/verify")) return x(Xe({
1752
- pendingToken: Q(i.pendingToken) ?? "",
1753
- ...$("code", i.code),
1754
- ...$("recoveryCode", i.recoveryCode),
1755
- ...i.redirectAfter === void 0 ? {} : { redirectAfter: !!i.redirectAfter },
1756
- ...r.remoteAddr ? { ipAddress: r.remoteAddr } : {},
1757
- ...r.headers["user-agent"] ? { userAgent: r.headers["user-agent"] } : {}
1758
- }, s, d));
1759
- if (t.passkey && r.method === "POST" && b(r, "/passkey/assert/options")) return x(yt({ ...$("userId", i.userId) }, s, c, t.passkey));
1760
- if (t.passkey && r.method === "POST" && b(r, "/passkey/assert/verify")) return x(bt({
1761
- credentialId: Q(i.credentialId) ?? "",
1762
- clientDataJSON: Q(i.clientDataJSON) ?? "",
1763
- authenticatorData: Q(i.authenticatorData) ?? "",
1764
- signature: Q(i.signature) ?? "",
1765
- ...$("userId", i.userId)
1766
- }, s, c, t.passkey, d));
1767
- let a = await g(r), o = a?.subject ?? null, u = () => !o || o.type !== "user" ? Z(401, { error: "unauthenticated" }) : { userId: o.id }, f = () => y(r) ? null : Z(403, { error: "csrf" }), m = (e) => x(e).then((e) => v(e, a?.renewSetCookie));
1768
- if (o && Ht(o)) {
1769
- let e = r.path.startsWith(n) ? r.path.slice(n.length) : "";
1770
- if (zt.includes(e)) return Z(403, {
1771
- error: "forbidden_while_impersonating",
1772
- message: "This action changes account credentials or session scope and is refused while impersonating. Stop the impersonation first."
1773
- });
1774
- }
1775
- if (r.method === "GET" && b(r, "/session")) {
1776
- let e = u();
1777
- return "status" in e ? e : v(Z(200, {
1778
- ok: !0,
1779
- subject: o,
1780
- renewed: a?.renewSetCookie !== void 0,
1781
- expiresAt: a?.expiresAt,
1782
- ...a?.via === "header" && a.renewValue !== void 0 ? { session: a.renewValue } : {}
1783
- }), a?.renewSetCookie);
1784
- }
1785
- if (r.method === "GET" && b(r, "/sessions")) {
1786
- let e = u();
1787
- return "status" in e ? e : m(lt({ userId: e.userId }, s));
1788
- }
1789
- if (r.method === "GET" && b(r, "/memberships")) {
1790
- let e = u();
1791
- return "status" in e ? e : m(pt({ userId: e.userId }, s));
1792
- }
1793
- if (r.method === "POST" && b(r, "/sessions/revoke")) {
1794
- let e = u();
1795
- if ("status" in e) return e;
1796
- let t = f();
1797
- if (t) return t;
1798
- let n = Q(i.sessionId) ?? "";
1799
- return m(ut({
1800
- userId: e.userId,
1801
- sessionId: n
1802
- }, s)).then((e) => (n && h.invalidate(n), e));
1803
- }
1804
- if (r.method === "POST" && b(r, "/sessions/revoke-others")) {
1805
- let e = u();
1806
- return "status" in e ? e : f() || m(dt({
1807
- userId: e.userId,
1808
- keepSessionId: a?.sessionId ?? "__none__"
1809
- }, s));
1810
- }
1811
- if (t.invitations && r.method === "POST" && b(r, "/invitations")) {
1812
- let e = u();
1813
- return "status" in e ? e : f() || m(Mt({
1814
- inviterUserId: e.userId,
1815
- tenantId: Q(i.tenantId) ?? o?.tenantId ?? "",
1816
- email: Q(i.email) ?? "",
1817
- role: Q(i.role) ?? ""
1818
- }, s, p));
1819
- }
1820
- if (t.invitations && r.method === "GET" && r.path === `${n}/invitations`) {
1821
- let e = u();
1822
- return "status" in e ? e : m(Nt({
1823
- callerUserId: e.userId,
1824
- tenantId: o?.tenantId ?? ""
1825
- }, s, p));
1826
- }
1827
- if (t.invitations && r.method === "POST" && b(r, "/invitations/revoke")) {
1828
- let e = u();
1829
- return "status" in e ? e : f() || m(Pt({
1830
- callerUserId: e.userId,
1831
- tenantId: Q(i.tenantId) ?? o?.tenantId ?? "",
1832
- invitationId: Q(i.invitationId) ?? ""
1833
- }, s, p));
1834
- }
1835
- if (t.invitations && r.method === "POST" && b(r, "/invitations/accept")) {
1836
- let e = u();
1837
- if (!("status" in e)) {
1838
- let e = f();
1839
- if (e) return e;
1840
- }
1841
- return m(It({
1842
- token: Q(i.token) ?? "",
1843
- ..."status" in e ? {} : { userId: e.userId }
1844
- }, s, p));
1845
- }
1846
- if (t.impersonation && r.method === "POST" && b(r, "/impersonate/start")) {
1847
- let e = u();
1848
- return "status" in e ? e : f() || x(Gt({
1849
- actorSubject: o,
1850
- actorSessionId: a?.sessionId ?? "",
1851
- ...$("targetUserId", i.userId),
1852
- ...$("targetEmail", i.email),
1853
- ...$("reason", i.reason),
1854
- ...typeof i.durationSeconds == "number" ? { durationSeconds: i.durationSeconds } : {},
1855
- ipAddress: r.remoteAddr ?? null,
1856
- userAgent: r.headers["user-agent"] ?? null
1857
- }, s, {
1858
- impersonation: t.impersonation,
1859
- issuer: S,
1860
- ...t.now === void 0 ? {} : { now: t.now },
1861
- invalidateSession: (e) => h.invalidate(e)
1862
- }));
1863
- }
1864
- if (t.impersonation && r.method === "POST" && b(r, "/impersonate/stop")) {
1865
- let e = u();
1866
- return "status" in e ? e : f() || x(Kt({
1867
- subject: o,
1868
- sessionId: a?.sessionId ?? ""
1869
- }, s, {
1870
- impersonation: t.impersonation,
1871
- issuer: S,
1872
- ...t.now === void 0 ? {} : { now: t.now },
1873
- invalidateSession: (e) => h.invalidate(e)
1874
- }));
1875
- }
1876
- if (r.method === "POST" && b(r, "/switch-tenant")) {
1877
- let e = u();
1878
- return "status" in e ? e : f() || x(ft({
1879
- userId: e.userId,
1880
- targetTenantId: Q(i.targetTenantId) ?? "",
1881
- ...typeof i.clientId == "number" ? { clientId: i.clientId } : {},
1882
- ...a?.sessionId ? { sessionId: a.sessionId } : {},
1883
- ...o?.type === "user" && o.metadata ? { metadata: o.metadata } : {}
1884
- }, s, d, t.rebind, l.current));
1885
- }
1886
- if (t.mfa && r.method === "POST" && b(r, "/mfa/enroll/start")) {
1887
- let e = u();
1888
- if ("status" in e) return e;
1889
- let n = f();
1890
- if (n) return n;
1891
- let r = await D.runPromise(s.findById(e.userId));
1892
- return m($e({
1893
- userId: e.userId,
1894
- issuer: t.mfa.issuer,
1895
- accountName: r?.email ?? e.userId
1896
- }, s));
1897
- }
1898
- if (t.mfa && r.method === "POST" && b(r, "/mfa/enroll/verify")) {
1899
- let e = u();
1900
- return "status" in e ? e : f() || m(et({
1901
- userId: e.userId,
1902
- code: Q(i.code) ?? ""
1903
- }, s));
1904
- }
1905
- if (t.mfa && r.method === "POST" && b(r, "/mfa/unenroll")) {
1906
- let e = u();
1907
- return "status" in e ? e : f() || m(nt({ userId: e.userId }, s));
1908
- }
1909
- if (t.mfa && r.method === "POST" && b(r, "/mfa/recovery-codes/regenerate")) {
1910
- let e = u();
1911
- return "status" in e ? e : f() || m(tt({ userId: e.userId }, s));
1912
- }
1913
- if (t.passkey && r.method === "POST" && b(r, "/passkey/register/options")) {
1914
- let e = u();
1915
- return "status" in e ? e : f() || m(_t({
1916
- userId: e.userId,
1917
- userName: Q(i.userName) ?? e.userId
1918
- }, s, c, t.passkey));
1919
- }
1920
- if (t.passkey && r.method === "POST" && b(r, "/passkey/register/verify")) {
1921
- let e = u();
1922
- return "status" in e ? e : f() || m(vt({
1923
- userId: e.userId,
1924
- credentialId: Q(i.credentialId) ?? "",
1925
- clientDataJSON: Q(i.clientDataJSON) ?? "",
1926
- authenticatorData: Q(i.authenticatorData) ?? "",
1927
- ...$("transports", i.transports)
1928
- }, s, c, t.passkey));
1929
- }
1930
- return !t.passkey && r.path.startsWith(`${n}/passkey/`) ? Z(501, { error: "passkey_not_configured" }) : Z(404, { error: "not_found" });
1931
- }
1932
- }, C = de({
1933
- name: t.name ? `@voltro/plugin-auth#${t.name}` : "@voltro/plugin-auth",
1934
- description: "Auth routes — mounts the full auth surface (password, magic-link, password-reset, CSRF, session probe/list/revoke, memberships, switch-tenant, passkey ceremonies) under /auth on the framework listener, with keyed secret rotation + request-time revocation.",
1935
- permissions: [],
1936
- declaredEnv: vn,
1937
- privacy: _n,
1938
- httpRoutes: [re],
1939
- bindDataStore: (e, n) => {
1940
- l.current = e, typeof t.store == "function" && (r.current = t.store(n?.sql === void 0 ? {} : { sql: n.sql }));
1941
- },
1942
- onActivate: (e) => D.sync(() => {
1943
- e.logger.info("auth routes active", {
1944
- prefix: n,
1945
- passkey: t.passkey ? t.passkey.rpId : "disabled",
1946
- email: t.sendEmail ? "wired" : "unwired",
1947
- revocationWindowMs: h.ttlMs,
1948
- emailVerification: t.emailVerification?.policy ?? "off",
1949
- invitations: t.invitations ? "enabled" : "disabled",
1950
- impersonation: t.impersonation ? `enabled(max ${t.impersonation.maxDurationSeconds ?? 900}s)` : "disabled"
1951
- });
1952
- }),
1953
- onDeactivate: () => D.void
1954
- }), w = t.secrets ?? t.secret;
1955
- return {
1956
- ...C,
1957
- auth: { sessionStrategy: _({
1958
- ...w === void 0 ? {} : { secret: w },
1959
- store: s,
1960
- revocation: h
1961
- }) }
1962
- };
1963
- }, _n = { collects: [{
1964
- category: "identifiers",
1965
- linked: !0,
1966
- tracking: !1,
1967
- purposes: ["app-functionality"]
1968
- }, {
1969
- category: "email",
1970
- linked: !0,
1971
- tracking: !1,
1972
- purposes: ["app-functionality"]
1973
- }] }, vn = [
1974
- {
1975
- name: "VOLTRO_SESSION_SECRET_PREVIOUS",
1976
- required: !1,
1977
- secret: !0,
1978
- description: "The session secret being rotated AWAY from. While set, cookies signed with it still verify (and get re-issued under the current secret on the next authenticated /auth response). Set the new secret as VOLTRO_SESSION_SECRET, move the old one here for one session lifetime, then drop it.",
1979
- example: "the-previous-signing-secret"
1980
- },
1981
- {
1982
- name: "VOLTRO_SESSION_KID",
1983
- required: !1,
1984
- secret: !1,
1985
- description: "Non-secret key-id label stamped into cookies signed with the current secret (default 'k0').",
1986
- example: "2026-07"
1987
- },
1988
- {
1989
- name: "VOLTRO_SESSION_KID_PREVIOUS",
1990
- required: !1,
1991
- secret: !1,
1992
- description: "Non-secret key-id label for the previous secret (default 'k-previous').",
1993
- example: "2026-01"
1994
- },
1995
- {
1996
- name: "VOLTRO_INVITATIONS_TTL_HOURS",
1997
- required: !1,
1998
- secret: !1,
1999
- description: "How long an `invitations` row is kept before the retention sweep DELETES it. Default 2160 (90 days). Only armed when `invitations` is configured. Every invitation is dead long before this — the lifetime that decides redeemability is `invitations.ttlSeconds` (7 days by default) — so this bounds the history, not the grant.",
2000
- example: "2160"
2001
- },
2002
- {
2003
- name: "VOLTRO_IMPERSONATION_GRANTS_TTL_HOURS",
2004
- required: !1,
2005
- secret: !1,
2006
- description: "How long an `impersonationGrants` row is kept before the retention sweep DELETES it. Default 8760 (365 days), matching the audit log — this table answers \"who was acting as whom, when\", which is compliance evidence rather than operational state. Only armed when `impersonation` is configured. Raise it to your audit-retention obligation; lowering it shortens how far back an impersonation can be traced.",
2007
- example: "8760"
2008
- },
2009
- {
2010
- name: "VOLTRO_AUTH_SCOPE_CACHE_TTL_MS",
2011
- required: !1,
2012
- secret: !1,
2013
- description: "How long a resolved authority (auth.resolveScopes) stays cached, in milliseconds. Default 30000 — the same window as the session-revocation check, so the two per-request store reads expire together. This is the staleness window for a role change: remove a permission and every live session observes it within this long. Set it to 0 to resolve on every request (staleness zero, one store read per request). An explicit ttlMs in code wins over this variable.",
2014
- example: "30000"
2015
- }
2016
- ];
2017
- //#endregion
2018
- export { H as $, _t as A, $e as B, Mt as C, gt as D, Pt as E, rt as F, ct as G, tt as H, pt as I, ut as J, st as K, lt as L, ht as M, R as N, yt as O, U as P, ft as Q, ot as R, Lt as S, Ft as T, nt as U, et as V, Xe as W, Qe as X, Ye as Y, Ze as Z, Ct as _, _e as _t, cn as a, He as at, Et as b, an as c, Be as ct, Gt as d, Me as dt, Pe as et, Kt as f, je as ft, wt as g, be as gt, Ht as h, N as ht, on as i, Re as it, vt as j, bt as k, Rt as l, I as lt, Vt as m, Ae as mt, un as n, Ne as nt, ln as o, Ve as ot, Ut as p, ke as pt, dt as q, qt as r, F as rt, en as s, Le as st, gn as t, Fe as tt, zt as u, M as ut, St as v, ge as vt, Nt as w, It as x, xt as y, at as z };