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