@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.
package/README.md CHANGED
@@ -20,6 +20,16 @@ Installation, guides, the full API reference, and examples all live in the
20
20
  **[Voltro documentation](https://docs.voltro.dev/docs/intro/getting-started)** — the single source of truth. This README is
21
21
  deliberately short so there is nothing here to drift out of date.
22
22
 
23
+ ## Registered device sessions
24
+
25
+ `rotateRegisteredSession` replaces a credential atomically and retains inactive
26
+ aliases so revoking an earlier cookie's row also ends its successor. Registry
27
+ writes own transactions; use `{ transaction: 'existing' }` inside a mutation or
28
+ an explicit transaction. Apply the declared `sessions` schema before restarting
29
+ upgraded auth replicas. See the bilingual
30
+ [session guide](https://docs.voltro.dev/docs/authentication/sessions) for authority
31
+ checks, device families and revocation cache limits.
32
+
23
33
  ## License
24
34
 
25
35
  Proprietary. © 2026 Voltro UG. Your use is governed by the
@@ -1,11 +1,11 @@
1
1
  # Third-Party Notices — @voltro/plugin-auth
2
2
 
3
- This package depends on the open-source software listed below. Each is the
3
+ This package uses the open-source software listed below. Each is the
4
4
  property of its respective copyright holders and is used under the terms of
5
5
  its license. This file is provided for attribution; it grants no rights in
6
6
  @voltro/plugin-auth itself, which is proprietary (see LICENSE).
7
7
 
8
- Generated from the resolved runtime dependency closure (5 packages).
8
+ Generated from the resolved runtime dependency closure (4 packages).
9
9
 
10
10
  ---
11
11
 
@@ -37,34 +37,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37
37
  SOFTWARE.
38
38
  ```
39
39
 
40
- ## layerr@3.0.0
41
-
42
- License: MIT
43
-
44
- ```
45
- MIT License
46
-
47
- Copyright (c) 2020 Perry Mitchell
48
-
49
- Permission is hereby granted, free of charge, to any person obtaining a copy
50
- of this software and associated documentation files (the "Software"), to deal
51
- in the Software without restriction, including without limitation the rights
52
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
53
- copies of the Software, and to permit persons to whom the Software is
54
- furnished to do so, subject to the following conditions:
55
-
56
- The above copyright notice and this permission notice shall be included in all
57
- copies or substantial portions of the Software.
58
-
59
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
60
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
61
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
62
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
63
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
64
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
65
- SOFTWARE.
66
- ```
67
-
68
40
  ## typeid-js@1.2.0
69
41
 
70
42
  License: Apache-2.0
@@ -273,14 +245,14 @@ Apache License
273
245
  limitations under the License.
274
246
  ```
275
247
 
276
- ## ulidx@2.4.1
248
+ ## ulid@3.0.2
277
249
 
278
250
  License: MIT
279
251
 
280
252
  ```
281
- MIT License
253
+ The MIT License (MIT)
282
254
 
283
- Copyright (c) 2021 Perry Mitchell
255
+ Copyright (c) 2017 Alizain Feerasta
284
256
 
285
257
  Permission is hereby granted, free of charge, to any person obtaining a copy
286
258
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,9 @@
1
+ import { Effect as e } from "effect";
2
+ //#region src/admission.ts
3
+ var t = (t, n, r = { store: void 0 }) => {
4
+ if (t === void 0) return e.succeed(null);
5
+ let i = t(n, r);
6
+ return e.isEffect(i) ? i : e.promise(() => i);
7
+ };
8
+ //#endregion
9
+ export { t as decideAdmission };
@@ -0,0 +1,19 @@
1
+ import { memoryUserStore as e } from "./userStore.js";
2
+ import { postgresUserStore as t } from "./postgresUserStore.js";
3
+ //#region src/appUserStore.ts
4
+ var n = (n = {}) => ({ sql: r }) => r === void 0 ? e() : r.onDialectOrElse({
5
+ pg: () => t(r, n),
6
+ orElse: () => {
7
+ 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 }).");
8
+ }
9
+ }), r = (e) => new Proxy({}, { get: (t, n) => {
10
+ if (typeof n == "string" && n !== "then") return (...t) => {
11
+ let r = e();
12
+ 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.`);
13
+ let i = r[n];
14
+ if (typeof i != "function") throw Error(`authRoutesPlugin: the resolved user store has no method '${n}'.`);
15
+ return i.apply(r, [...t]);
16
+ };
17
+ } });
18
+ //#endregion
19
+ export { n as appUserStore, r as deferredUserStore };
@@ -0,0 +1,62 @@
1
+ import { newAuthId as e } from "./userStore.js";
2
+ import { hashToken as t, mintToken as n } from "./tokens.js";
3
+ import { Effect as r } from "effect";
4
+ //#region src/emailVerification.ts
5
+ var i = 60, a = "email_not_verified", o = "emailVerified", s = (e) => e?.policy ?? "off", c = (e) => s(e) !== "off", l = (e, t) => {
6
+ if (e.emailVerifiedAt != null) return !0;
7
+ let n = t?.exemptAccountsCreatedBefore;
8
+ return n !== void 0 && e.createdAt.getTime() < n.getTime();
9
+ }, u = (e) => {
10
+ if (e.type !== "user") return null;
11
+ let t = e.metadata?.[o];
12
+ return typeof t == "boolean" ? t : null;
13
+ }, d = (e) => {
14
+ let t = s(e) === "strict";
15
+ return (n) => r.succeed(!t || l(n, e) ? { ok: !0 } : {
16
+ ok: !1,
17
+ code: a,
18
+ message: "This account's email address has not been confirmed yet. Request a new confirmation link and follow it, then sign in again."
19
+ });
20
+ }, f = (e, t) => ({
21
+ status: e,
22
+ body: JSON.stringify(t),
23
+ contentType: "application/json; charset=utf-8"
24
+ }), p = (e, t, n) => `${e}${t}${t.includes("?") ? "&" : "?"}token=${encodeURIComponent(n)}`, m = (t, i, a) => r.gen(function* () {
25
+ let o = a.emailVerification, s = (a.now ?? Date.now)(), c = (o?.resendCooldownSeconds ?? 60) * 1e3;
26
+ if (c > 0) {
27
+ let e = yield* i.latestToken(t.id, "email-verify");
28
+ if (e && s - e.createdAt.getTime() < c) return !1;
29
+ }
30
+ let l = n("email-verify", o?.ttlSeconds ?? 86400);
31
+ if (yield* i.insertToken({
32
+ id: e("tok"),
33
+ tokenHash: l.tokenHash,
34
+ userId: t.id,
35
+ purpose: "email-verify",
36
+ expiresAt: l.expiresAt
37
+ }).pipe(r.ignore), !a.sendEmail) return !1;
38
+ let u = p(a.appBaseUrl ?? "", o?.callbackPath ?? "/auth/verify-email/callback", l.token);
39
+ return yield* r.tryPromise(() => a.sendEmail({
40
+ to: t.email,
41
+ kind: "email-verify",
42
+ actionUrl: u,
43
+ subject: "Confirm your email address",
44
+ text: `Confirm your email address: ${u}`,
45
+ html: `<p><a href="${u}">Confirm your email address</a> — this link expires in 24 hours.</p>`
46
+ })).pipe(r.ignore), !0;
47
+ }), h = (e, t, n) => r.gen(function* () {
48
+ if (!e.email && !e.userId) return f(400, { error: "email or userId required" });
49
+ let r = e.userId ? yield* t.findById(e.userId) : yield* t.findByEmail(e.email);
50
+ return r && !l(r, n.emailVerification) && (yield* m(r, t, n)), f(202, { ok: !0 });
51
+ }), g = (e, n) => r.gen(function* () {
52
+ if (!e.token) return f(400, { error: "token required" });
53
+ let i = yield* n.consumeToken(t(e.token), "email-verify");
54
+ if (!i) return f(401, { error: "invalid or expired token" });
55
+ let a = yield* n.findById(i.userId);
56
+ return a ? (yield* n.markEmailVerified(a.id).pipe(r.ignore), f(200, {
57
+ ok: !0,
58
+ verified: !0
59
+ })) : f(401, { error: "invalid or expired token" });
60
+ });
61
+ //#endregion
62
+ export { a as EMAIL_NOT_VERIFIED_CODE, o as EMAIL_VERIFIED_METADATA_KEY, i as EMAIL_VERIFY_RESEND_COOLDOWN_S, c as emailVerificationActive, d as emailVerificationGuard, g as handleEmailVerifyConfirm, h as handleEmailVerifyRequest, u as isEmailVerified, m as sendEmailVerification, l as userEmailVerified };
@@ -0,0 +1,337 @@
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, resolveSessionSecret as o, resolveSessionSecrets as s, sessionSecretsOf as c } from "./session.js";
3
+ import { newAuthId as l, subjectFromUser as u } from "./userStore.js";
4
+ import { runSubjectGuards as d } from "./subjectGuard.js";
5
+ import { generateRecoveryCodes as f, generateTotpSecret as p, otpauthUrl as m, verifyTotpCode as h } from "./totp.js";
6
+ import { MFA_PENDING_TTL_S as g, hashToken as _, mintToken as v } from "./tokens.js";
7
+ import { CSRF_COOKIE_NAME as y, issueCsrfToken as b } from "./csrf.js";
8
+ import { decideAdmission as x } from "./admission.js";
9
+ import { EMAIL_VERIFIED_METADATA_KEY as S, emailVerificationActive as C, sendEmailVerification as w, userEmailVerified as T } from "./emailVerification.js";
10
+ import { Effect as E } from "effect";
11
+ import { buildSetCookie as D } from "@voltro/protocol/session";
12
+ import { writeTenantSelection as O } from "@voltro/database";
13
+ import { selectSubjectTenant as k } from "@voltro/protocol";
14
+ //#region src/handlers.ts
15
+ var A = 5, j = 900, M = 900, N = (e) => ({
16
+ maxAttempts: e.lockout?.maxAttempts ?? A,
17
+ windowMs: (e.lockout?.windowSeconds ?? j) * 1e3,
18
+ lockMs: (e.lockout?.lockSeconds ?? M) * 1e3
19
+ }), P = (e) => e.secrets ?? (e.secret === void 0 ? s() : c(e.secret)), F = (e) => e.secret ?? o(), I = (e, t, n = {}) => ({
20
+ status: e,
21
+ body: JSON.stringify(t),
22
+ contentType: "application/json; charset=utf-8",
23
+ ...n
24
+ }), L = (e, t = {}) => ({
25
+ status: 302,
26
+ body: "",
27
+ contentType: "text/plain",
28
+ location: e,
29
+ ...t
30
+ }), R = 604800, z = (e, t) => e.type === "user" ? {
31
+ ...e,
32
+ metadata: {
33
+ ...e.metadata ?? {},
34
+ sessionId: t
35
+ }
36
+ } : e, B = (e, t, n, r = {}) => E.gen(function* () {
37
+ r.clearLoginFailures !== !1 && (yield* t.clearLoginFailures(e.email)), n.ensureActor && (yield* n.ensureActor(e));
38
+ let i = yield* t.listMemberships(e.id), o = r.sessionId ?? l("sess"), s = r.ttlSeconds ?? R;
39
+ r.sessionRow !== "existing" && (yield* t.insertSession({
40
+ id: o,
41
+ userId: e.id,
42
+ tenantId: e.tenantId,
43
+ expiresAt: new Date(Date.now() + s * 1e3),
44
+ ipAddress: r.ipAddress ?? null,
45
+ userAgent: r.userAgent ?? null
46
+ }).pipe(E.ignore));
47
+ let c = { ...r.metadata };
48
+ C(n.emailVerification) && (c[S] = T(e, n.emailVerification));
49
+ let d = z(u(e, {
50
+ memberships: i,
51
+ ...Object.keys(c).length > 0 ? { metadata: c } : {}
52
+ }), o), f = a(d, P(n), {
53
+ ttlSeconds: s,
54
+ ...n.cookieDomain ? { domain: n.cookieDomain } : {},
55
+ secure: n.cookieSecure ?? !0
56
+ });
57
+ return {
58
+ setCookie: f.setCookie,
59
+ value: f.value,
60
+ expiresAt: Math.floor(Date.now() / 1e3) + s,
61
+ subject: d
62
+ };
63
+ }), V = (e, t) => E.gen(function* () {
64
+ let n = t.subjectGuards ?? [];
65
+ if (n.length === 0) return null;
66
+ let r = yield* d(n, e);
67
+ return r.ok ? null : I(403, {
68
+ error: r.code,
69
+ message: r.message
70
+ });
71
+ }), H = (r, i, a) => E.gen(function* () {
72
+ if (!r.email || !r.password) return I(400, { error: "email and password required" });
73
+ let o = yield* i.findByEmail(r.email), s = (a.now ?? Date.now)(), c = yield* i.isLockedOut(r.email, s);
74
+ if (c.locked) return I(429, {
75
+ error: "account_locked",
76
+ retryAfterSeconds: c.retryAfterSeconds
77
+ });
78
+ let u = o?.passwordHash, d = typeof u == "string" && u.length > 0 ? yield* n(r.password, u) : yield* E.gen(function* () {
79
+ let n = yield* e("decoy-not-a-real-password").pipe(E.orElseSucceed(() => ""));
80
+ return yield* t(r.password, n), { valid: !1 };
81
+ });
82
+ if (!o || !d.valid) return yield* i.recordLoginFailure(r.email, s, N(a)), I(401, { error: "invalid credentials" });
83
+ let f = yield* V(o, a);
84
+ if (f) return f;
85
+ if (d.rehash && (yield* i.updatePassword(o.id, d.rehash).pipe(E.ignore)), o.mfaEnrolledAt) {
86
+ let e = v("mfa-pending", 300);
87
+ return yield* i.insertToken({
88
+ id: l("tok"),
89
+ tokenHash: e.tokenHash,
90
+ userId: o.id,
91
+ purpose: "mfa-pending",
92
+ expiresAt: e.expiresAt
93
+ }).pipe(E.ignore), I(200, {
94
+ ok: !0,
95
+ mfaRequired: !0,
96
+ pendingToken: e.token,
97
+ expiresInSeconds: 300
98
+ });
99
+ }
100
+ let { setCookie: p, subject: m } = yield* B(o, i, a, {
101
+ ipAddress: r.ipAddress ?? null,
102
+ userAgent: r.userAgent ?? null
103
+ });
104
+ return r.redirectAfter ? L(a.successRedirect ?? "/", { setCookie: p }) : I(200, {
105
+ ok: !0,
106
+ subject: m
107
+ }, { setCookie: p });
108
+ }), U = (e, t, n) => E.gen(function* () {
109
+ if (!e.pendingToken) return I(400, { error: "pending token required" });
110
+ if (!e.code && !e.recoveryCode) return I(400, { error: "code or recoveryCode required" });
111
+ let r = yield* t.consumeToken(_(e.pendingToken), "mfa-pending");
112
+ if (!r) return I(401, { error: "invalid or expired challenge" });
113
+ let i = yield* t.findById(r.userId);
114
+ if (!i || !i.mfaEnrolledAt || !i.mfaSecret) return I(401, { error: "mfa not enrolled" });
115
+ let a = (n.now ?? Date.now)(), o = yield* t.isLockedOut(i.email, a);
116
+ if (o.locked) return I(429, {
117
+ error: "account_locked",
118
+ retryAfterSeconds: o.retryAfterSeconds
119
+ });
120
+ let s = yield* V(i, n);
121
+ if (s) return s;
122
+ if (!(e.recoveryCode ? yield* t.consumeRecoveryCode(i.id, _(e.recoveryCode.trim())) : yield* h(i.mfaSecret, e.code ?? "").pipe(E.map(() => !0), E.catchTag("TotpVerifyError", () => E.succeed(!1))))) return yield* t.recordLoginFailure(i.email, a, N(n)), I(401, { error: "invalid_code" });
123
+ let { setCookie: c, subject: l } = yield* B(i, t, n, {
124
+ ipAddress: e.ipAddress ?? null,
125
+ userAgent: e.userAgent ?? null
126
+ });
127
+ return e.redirectAfter ? L(n.successRedirect ?? "/", { setCookie: c }) : I(200, {
128
+ ok: !0,
129
+ subject: l
130
+ }, { setCookie: c });
131
+ }), W = (t, n, r) => E.gen(function* () {
132
+ if (!t.email || !t.password) return I(400, { error: "email and password required" });
133
+ if (t.password.length < 8) return I(400, { error: "password must be at least 8 characters" });
134
+ if (yield* n.findByEmail(t.email)) return I(409, { error: "email already registered" });
135
+ let i = t.tenantId ?? r.defaultTenantId, a = yield* x(r.admit, {
136
+ email: t.email,
137
+ tenantId: i,
138
+ via: "sign-up"
139
+ });
140
+ if (a) return I(403, {
141
+ error: "not_admitted",
142
+ reason: a.reason,
143
+ message: a.message
144
+ });
145
+ let o = yield* e(t.password), s = yield* n.insert({
146
+ id: l("user"),
147
+ email: t.email,
148
+ passwordHash: o,
149
+ tenantId: i
150
+ });
151
+ yield* n.addMembership({
152
+ userId: s.id,
153
+ tenantId: i,
154
+ role: "owner"
155
+ }).pipe(E.ignore), C(r.emailVerification) && (r.emailVerification?.sendOnSignUp ?? !0) && (yield* w(s, n, r).pipe(E.ignore));
156
+ let { setCookie: c, subject: u } = yield* B(s, n, r);
157
+ return t.redirectAfter ? L(r.successRedirect ?? "/", { setCookie: c }) : I(200, {
158
+ ok: !0,
159
+ subject: u
160
+ }, { setCookie: c });
161
+ }).pipe(E.catch((e) => E.succeed(I(500, {
162
+ error: "signup_failed",
163
+ cause: String(e)
164
+ })))), G = (e) => ({
165
+ status: 302,
166
+ body: "",
167
+ location: e.successRedirect ?? "/",
168
+ setCookie: i({
169
+ ...e.cookieDomain ? { domain: e.cookieDomain } : {},
170
+ secure: e.cookieSecure ?? !0
171
+ })
172
+ }), K = (e, t) => E.gen(function* () {
173
+ let n = yield* t.findById(e.userId);
174
+ if (!n) return I(404, { error: "user_not_found" });
175
+ let r = p();
176
+ return yield* t.setMfaSecret(n.id, r).pipe(E.catch(() => E.succeed(n))), I(200, {
177
+ ok: !0,
178
+ secret: r,
179
+ otpauthUrl: m({
180
+ issuer: e.issuer,
181
+ accountName: e.accountName,
182
+ secret: r
183
+ })
184
+ });
185
+ }), q = (e, t) => E.gen(function* () {
186
+ let n = yield* t.findById(e.userId);
187
+ if (!n) return I(404, { error: "user_not_found" });
188
+ if (!n.mfaSecret) return I(400, { error: "no_enrollment_in_progress" });
189
+ if (n.mfaEnrolledAt) return I(409, { error: "already_enrolled" });
190
+ if (!(yield* h(n.mfaSecret, e.code).pipe(E.map(() => !0), E.catchTag("TotpVerifyError", () => E.succeed(!1))))) return I(401, { error: "invalid_code" });
191
+ yield* t.markMfaEnrolled(n.id).pipe(E.catch(() => E.succeed(n)));
192
+ let r = f();
193
+ return yield* t.replaceRecoveryCodes(n.id, r.map((e) => _(e))).pipe(E.ignore), I(200, {
194
+ ok: !0,
195
+ enrolled: !0,
196
+ recoveryCodes: r
197
+ });
198
+ }), J = (e, t) => E.gen(function* () {
199
+ let n = yield* t.findById(e.userId);
200
+ if (!n) return I(404, { error: "user_not_found" });
201
+ if (!n.mfaEnrolledAt) return I(400, { error: "mfa_not_enrolled" });
202
+ let r = f();
203
+ return yield* t.replaceRecoveryCodes(n.id, r.map((e) => _(e))).pipe(E.ignore), I(200, {
204
+ ok: !0,
205
+ recoveryCodes: r
206
+ });
207
+ }), Y = (e, t) => E.gen(function* () {
208
+ let n = yield* t.findById(e.userId);
209
+ return n ? (yield* t.clearMfa(n.id).pipe(E.catch(() => E.succeed(n))), yield* t.replaceRecoveryCodes(n.id, []).pipe(E.ignore), I(200, {
210
+ ok: !0,
211
+ enrolled: !1
212
+ })) : I(404, { error: "user_not_found" });
213
+ }), X = (e) => {
214
+ let t = b(F(e)), n = D(y, t, {
215
+ httpOnly: !1,
216
+ sameSite: "lax",
217
+ secure: e.cookieSecure ?? !0,
218
+ ...e.cookieDomain ? { domain: e.cookieDomain } : {},
219
+ path: "/"
220
+ });
221
+ return I(200, { csrfToken: t }, { setCookie: n });
222
+ }, Z = (e, t, n) => `${e}${t}${t.includes("?") ? "&" : "?"}token=${encodeURIComponent(n)}`, Q = (e, t, n) => E.gen(function* () {
223
+ if (!e.email) return I(400, { error: "email required" });
224
+ let r = yield* t.findByEmail(e.email);
225
+ if (r) {
226
+ let i = v("magic-link");
227
+ yield* t.insertToken({
228
+ id: l("tok"),
229
+ tokenHash: i.tokenHash,
230
+ userId: r.id,
231
+ purpose: "magic-link",
232
+ expiresAt: i.expiresAt
233
+ }).pipe(E.ignore);
234
+ let a = Z(n.appBaseUrl ?? "", e.callbackPath ?? "/auth/magic-link/callback", i.token);
235
+ n.sendEmail && (yield* E.tryPromise(() => n.sendEmail({
236
+ to: r.email,
237
+ kind: "magic-link",
238
+ actionUrl: a,
239
+ subject: "Your sign-in link",
240
+ text: `Sign in: ${a}`,
241
+ html: `<p><a href="${a}">Sign in</a> — this link expires shortly.</p>`
242
+ })).pipe(E.ignore));
243
+ }
244
+ return I(202, { ok: !0 });
245
+ }), $ = (e, t, n) => E.gen(function* () {
246
+ if (!e.token) return I(400, { error: "token required" });
247
+ let r = yield* t.consumeToken(_(e.token), "magic-link");
248
+ if (!r) return I(401, { error: "invalid or expired token" });
249
+ let i = yield* t.findById(r.userId);
250
+ if (!i) return I(401, { error: "invalid or expired token" });
251
+ let a = yield* t.markEmailVerified(i.id).pipe(E.orElseSucceed(() => i)), o = yield* V(a, n);
252
+ if (o) return o;
253
+ let { setCookie: s, subject: c } = yield* B(a, t, n);
254
+ return e.redirectAfter ? L(n.successRedirect ?? "/", { setCookie: s }) : I(200, {
255
+ ok: !0,
256
+ subject: c
257
+ }, { setCookie: s });
258
+ }), ee = (e, t, n) => E.gen(function* () {
259
+ if (!e.email) return I(400, { error: "email required" });
260
+ let r = yield* t.findByEmail(e.email);
261
+ if (r) {
262
+ let i = v("password-reset");
263
+ yield* t.insertToken({
264
+ id: l("tok"),
265
+ tokenHash: i.tokenHash,
266
+ userId: r.id,
267
+ purpose: "password-reset",
268
+ expiresAt: i.expiresAt
269
+ }).pipe(E.ignore);
270
+ let a = Z(n.appBaseUrl ?? "", e.callbackPath ?? "/auth/password-reset/callback", i.token);
271
+ n.sendEmail && (yield* E.tryPromise(() => n.sendEmail({
272
+ to: r.email,
273
+ kind: "password-reset",
274
+ actionUrl: a,
275
+ subject: "Reset your password",
276
+ text: `Reset your password: ${a}`,
277
+ html: `<p><a href="${a}">Reset your password</a> — this link expires shortly.</p>`
278
+ })).pipe(E.ignore));
279
+ }
280
+ return I(202, { ok: !0 });
281
+ }), te = (t, n) => E.gen(function* () {
282
+ if (!t.token || !t.newPassword) return I(400, { error: "token and newPassword required" });
283
+ if (t.newPassword.length < 8) return I(400, { error: "password must be at least 8 characters" });
284
+ let r = yield* n.consumeToken(_(t.token), "password-reset");
285
+ if (!r) return I(401, { error: "invalid or expired token" });
286
+ let i = yield* e(t.newPassword).pipe(E.orElseSucceed(() => ""));
287
+ return i ? (yield* n.updatePassword(r.userId, i).pipe(E.ignore), yield* n.markEmailVerified(r.userId).pipe(E.ignore), yield* n.revokeAllSessions(r.userId).pipe(E.ignore), I(200, { ok: !0 })) : I(500, { error: "hash_failed" });
288
+ }), ne = (e, t) => E.gen(function* () {
289
+ return I(200, { sessions: (yield* t.listSessions(e.userId)).map((e) => ({
290
+ id: e.id,
291
+ tenantId: e.tenantId,
292
+ ipAddress: e.ipAddress ?? null,
293
+ userAgent: e.userAgent ?? null,
294
+ createdAt: e.createdAt.toISOString(),
295
+ lastSeenAt: e.lastSeenAt.toISOString(),
296
+ expiresAt: e.expiresAt.toISOString()
297
+ })) });
298
+ }), re = (e, t) => E.gen(function* () {
299
+ return (yield* t.revokeSession(e.userId, e.sessionId)) ? I(200, {
300
+ ok: !0,
301
+ revoked: 1
302
+ }) : I(404, { error: "session_not_found" });
303
+ }), ie = (e, t) => E.gen(function* () {
304
+ return I(200, {
305
+ ok: !0,
306
+ revoked: yield* t.revokeAllOtherSessions(e.userId, e.keepSessionId)
307
+ });
308
+ }), ae = (e, t, n, i, o) => E.gen(function* () {
309
+ let s = yield* t.findById(e.userId);
310
+ if (!s) return I(404, { error: "user_not_found" });
311
+ let c = yield* t.listMemberships(s.id), l = c.find((t) => t.tenantId === e.targetTenantId)?.role ?? null;
312
+ if (l === null) return I(403, { error: "not a member of the target tenant" });
313
+ let d = e.metadata === void 0 ? void 0 : Object.fromEntries(Object.entries(e.metadata).filter(([e]) => e !== "memberships")), f = k(u(s, { ...d === void 0 ? {} : { metadata: d } }), e.targetTenantId, c);
314
+ o !== void 0 && f.type === "user" && (yield* E.promise(() => O(o, {
315
+ type: f.type,
316
+ id: f.id
317
+ }, e.targetTenantId)));
318
+ let p = e.sessionId ? z(f, e.sessionId) : f, m = a(p, P(n), {
319
+ ttlSeconds: R,
320
+ ...n.cookieDomain ? { domain: n.cookieDomain } : {},
321
+ secure: n.cookieSecure ?? !0
322
+ });
323
+ return e.clientId !== void 0 && i && i(e.clientId, { cookies: { [r]: m.value } }), I(200, {
324
+ ok: !0,
325
+ tenantId: e.targetTenantId,
326
+ role: l,
327
+ subject: p
328
+ }, { setCookie: m.setCookie });
329
+ }), oe = (e, t) => E.gen(function* () {
330
+ return I(200, { memberships: (yield* t.listMemberships(e.userId)).map((e) => ({
331
+ tenantId: e.tenantId,
332
+ role: e.role,
333
+ joinedAt: e.joinedAt.toISOString()
334
+ })) });
335
+ });
336
+ //#endregion
337
+ export { g as MFA_PENDING_TTL_S, P as configSessionSecrets, F as configSigningKey, V as guardSubject, X as handleCsrf, oe as handleListMemberships, ne as handleListSessions, $ as handleMagicLinkConsume, Q as handleMagicLinkRequest, K as handleMfaEnrollStart, q as handleMfaEnrollVerify, J as handleMfaRegenerateRecoveryCodes, Y as handleMfaUnenroll, U as handleMfaVerify, te as handlePasswordResetConfirm, ee as handlePasswordResetRequest, ie as handleRevokeAllOtherSessions, re as handleRevokeSession, H as handleSignIn, G as handleSignOut, W as handleSignUp, ae as handleSwitchTenant, B as issueUserSession };