@plinthjs/auth 0.1.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/dist/index.js ADDED
@@ -0,0 +1,852 @@
1
+ import { createHash, createHmac, timingSafeEqual, randomBytes } from 'crypto';
2
+ import { Response, Request, HttpException } from '@plinthjs/http';
3
+ import { getSession } from '@plinthjs/session';
4
+
5
+ // src/email-verification.ts
6
+
7
+ // src/events.ts
8
+ var Attempting = class {
9
+ constructor(guard, credentials, remember = false) {
10
+ this.guard = guard;
11
+ this.credentials = credentials;
12
+ this.remember = remember;
13
+ }
14
+ guard;
15
+ credentials;
16
+ remember;
17
+ };
18
+ var Validated = class {
19
+ constructor(guard, user) {
20
+ this.guard = guard;
21
+ this.user = user;
22
+ }
23
+ guard;
24
+ user;
25
+ };
26
+ var Login = class {
27
+ constructor(guard, user, remember) {
28
+ this.guard = guard;
29
+ this.user = user;
30
+ this.remember = remember;
31
+ }
32
+ guard;
33
+ user;
34
+ remember;
35
+ };
36
+ var Authenticated = class {
37
+ constructor(guard, user) {
38
+ this.guard = guard;
39
+ this.user = user;
40
+ }
41
+ guard;
42
+ user;
43
+ };
44
+ var Failed = class {
45
+ constructor(guard, user, credentials) {
46
+ this.guard = guard;
47
+ this.user = user;
48
+ this.credentials = credentials;
49
+ }
50
+ guard;
51
+ user;
52
+ credentials;
53
+ };
54
+ var Logout = class {
55
+ constructor(guard, user) {
56
+ this.guard = guard;
57
+ this.user = user;
58
+ }
59
+ guard;
60
+ user;
61
+ };
62
+ var CurrentDeviceLogout = class {
63
+ constructor(guard, user) {
64
+ this.guard = guard;
65
+ this.user = user;
66
+ }
67
+ guard;
68
+ user;
69
+ };
70
+ var OtherDeviceLogout = class {
71
+ constructor(guard, user) {
72
+ this.guard = guard;
73
+ this.user = user;
74
+ }
75
+ guard;
76
+ user;
77
+ };
78
+ var Registered = class {
79
+ constructor(user) {
80
+ this.user = user;
81
+ }
82
+ user;
83
+ };
84
+ var Verified = class {
85
+ constructor(user) {
86
+ this.user = user;
87
+ }
88
+ user;
89
+ };
90
+ var PasswordReset = class {
91
+ constructor(user) {
92
+ this.user = user;
93
+ }
94
+ user;
95
+ };
96
+ var Lockout = class {
97
+ constructor(credentials) {
98
+ this.credentials = credentials;
99
+ }
100
+ credentials;
101
+ };
102
+
103
+ // src/email-verification.ts
104
+ var EmailVerifier = class {
105
+ secret;
106
+ expireMinutes;
107
+ now;
108
+ events;
109
+ constructor(options) {
110
+ this.secret = options.secret;
111
+ this.expireMinutes = options.expireMinutes ?? 60;
112
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
113
+ this.events = options.events;
114
+ }
115
+ /** A stable hash of the user's email — proves the link was issued for this exact address. */
116
+ hashFor(user) {
117
+ return createHash("sha256").update(user.getEmailForVerification()).digest("hex");
118
+ }
119
+ /** Build a signed, expiring verification payload for `user` (embed it in the verification URL). */
120
+ sign(user) {
121
+ const expires = this.now().getTime() + this.expireMinutes * 6e4;
122
+ return { expires, signature: this.signature(user, expires) };
123
+ }
124
+ /** Whether `payload` is a valid, unexpired signature for `user`'s current email. */
125
+ isValid(user, payload) {
126
+ if (this.now().getTime() > payload.expires) return false;
127
+ return safeEqual(this.signature(user, payload.expires), payload.signature);
128
+ }
129
+ /**
130
+ * Verify a payload and mark the user verified. Returns `false` on a bad or expired signature;
131
+ * idempotent — an already-verified user returns `true` without re-marking.
132
+ */
133
+ async verify(user, payload) {
134
+ if (!this.isValid(user, payload)) return false;
135
+ if (!user.hasVerifiedEmail()) {
136
+ await user.markEmailAsVerified();
137
+ this.events?.dispatch(new Verified(user));
138
+ }
139
+ return true;
140
+ }
141
+ /** The HMAC binding the user id, email hash, and expiry. */
142
+ signature(user, expires) {
143
+ const data = `${String(user.getAuthIdentifier())}.${this.hashFor(user)}.${String(expires)}`;
144
+ return createHmac("sha256", this.secret).update(data).digest("hex");
145
+ }
146
+ };
147
+ function safeEqual(a, b) {
148
+ const bufferA = Buffer.from(a);
149
+ const bufferB = Buffer.from(b);
150
+ if (bufferA.length !== bufferB.length) return false;
151
+ return timingSafeEqual(bufferA, bufferB);
152
+ }
153
+ var SESSION_KEY = "auth.id";
154
+ var TOKEN_KEY = "api_token";
155
+ var PASSWORD_HASH_SESSION_KEY = "auth.password_hash";
156
+ var DEFAULT_REMEMBER_DURATION = 576e3;
157
+ var SessionGuard = class {
158
+ constructor(provider, session, key = SESSION_KEY, options = {}) {
159
+ this.provider = provider;
160
+ this.session = session;
161
+ this.key = key;
162
+ this.name = options.name ?? "web";
163
+ this.request = options.request;
164
+ this.events = options.events;
165
+ }
166
+ provider;
167
+ session;
168
+ key;
169
+ cachedUser = null;
170
+ resolved = false;
171
+ lastAttempted = null;
172
+ viaRememberFlag = false;
173
+ rememberDuration = DEFAULT_REMEMBER_DURATION;
174
+ request;
175
+ name;
176
+ events;
177
+ async user() {
178
+ if (this.resolved) return this.cachedUser;
179
+ const id = this.session.get(this.key);
180
+ this.cachedUser = id === null ? null : await this.provider.retrieveById(id);
181
+ this.resolved = true;
182
+ return this.cachedUser;
183
+ }
184
+ async check() {
185
+ return await this.user() !== null;
186
+ }
187
+ async guest() {
188
+ return !await this.check();
189
+ }
190
+ async id() {
191
+ const user = await this.user();
192
+ return user === null ? null : user.getAuthIdentifier();
193
+ }
194
+ async validate(credentials) {
195
+ const user = await this.provider.retrieveByCredentials(credentials);
196
+ this.lastAttempted = user;
197
+ if (user === null) return false;
198
+ return this.hasValidCredentials(user, credentials);
199
+ }
200
+ async attempt(credentials) {
201
+ return this.attemptWhen(credentials);
202
+ }
203
+ /**
204
+ * Attempt to authenticate with additional callbacks — the Laravel `attemptWhen`. The callbacks
205
+ * run after the credentials validate, receiving the user and this guard; every one must return
206
+ * `true` (a falsy result fails the attempt without logging the user in).
207
+ */
208
+ async attemptWhen(credentials, callbacks = []) {
209
+ this.events?.dispatch(new Attempting(this.name, credentials));
210
+ const user = await this.provider.retrieveByCredentials(credentials);
211
+ this.lastAttempted = user;
212
+ if (user !== null && await this.hasValidCredentials(user, credentials) && await this.shouldLogin(callbacks, user)) {
213
+ await this.provider.rehashPasswordIfRequired?.(user, credentials);
214
+ this.login(user);
215
+ return true;
216
+ }
217
+ this.events?.dispatch(new Failed(this.name, user, credentials));
218
+ return false;
219
+ }
220
+ async once(credentials) {
221
+ this.events?.dispatch(new Attempting(this.name, credentials));
222
+ const user = await this.provider.retrieveByCredentials(credentials);
223
+ this.lastAttempted = user;
224
+ if (user !== null && await this.hasValidCredentials(user, credentials)) {
225
+ this.setUser(user);
226
+ return true;
227
+ }
228
+ return false;
229
+ }
230
+ login(user) {
231
+ this.updateSession(user);
232
+ this.events?.dispatch(new Login(this.name, user, false));
233
+ this.setUser(user);
234
+ }
235
+ async loginUsingId(id) {
236
+ const user = await this.provider.retrieveById(id);
237
+ if (user !== null) this.login(user);
238
+ return user;
239
+ }
240
+ /**
241
+ * Log the current user out, cycling the remember token so every recaller dies — the Laravel
242
+ * `logout`. The session keys are cleared synchronously; the returned promise resolves once the
243
+ * token has been cycled through the provider and the `Logout` event dispatched.
244
+ */
245
+ logout() {
246
+ return this.performLogout(true);
247
+ }
248
+ /**
249
+ * Log the current user out on this device only — the Laravel `logoutCurrentDevice`. Unlike
250
+ * {@link SessionGuard.logout} the remember token is *not* cycled, so other remembered devices
251
+ * stay logged in. Dispatches `CurrentDeviceLogout`.
252
+ */
253
+ logoutCurrentDevice() {
254
+ return this.performLogout(false);
255
+ }
256
+ /**
257
+ * Invalidate the user's sessions on every other device — the Laravel `logoutOtherDevices`.
258
+ * Validates `password` against the current user (throwing when it does not match), then:
259
+ *
260
+ * - force re-hashes the password through {@link UserProvider.rehashPasswordIfRequired} (when the
261
+ * provider supports it) and refreshes this session's stored password hash, so any session
262
+ * checked by `authenticateSession` whose stored hash is now stale is logged out — the same
263
+ * session-password-hash mechanism Laravel's `AuthenticateSession` middleware uses; and
264
+ * - cycles the remember token, killing every previously issued recaller cookie.
265
+ *
266
+ * Returns the fresh recaller value for *this* device (the Laravel `queueRecallerCookie`
267
+ * re-issue), or `null` when nobody is authenticated.
268
+ */
269
+ async logoutOtherDevices(password) {
270
+ const user = await this.user();
271
+ if (user === null) return null;
272
+ if (!await this.provider.validateCredentials(user, { password })) {
273
+ throw new Error("The given password does not match the current password.");
274
+ }
275
+ await this.provider.rehashPasswordIfRequired?.(user, { password }, true);
276
+ this.session.put(PASSWORD_HASH_SESSION_KEY, user.getAuthPassword());
277
+ const recaller = await this.remember(user);
278
+ this.events?.dispatch(new OtherDeviceLogout(this.name, user));
279
+ return recaller;
280
+ }
281
+ setUser(user) {
282
+ this.cachedUser = user;
283
+ this.resolved = true;
284
+ this.events?.dispatch(new Authenticated(this.name, user));
285
+ }
286
+ /** Set the current request (used by the HTTP Basic helpers). The `setRequest` equivalent. */
287
+ setRequest(request) {
288
+ this.request = request;
289
+ return this;
290
+ }
291
+ /** The last user a credential attempt resolved, or `null`. The `getLastAttempted` equivalent. */
292
+ getLastAttempted() {
293
+ return this.lastAttempted;
294
+ }
295
+ /** Whether the current user was authenticated via a remember-me recaller. The `viaRemember` equivalent. */
296
+ viaRemember() {
297
+ return this.viaRememberFlag;
298
+ }
299
+ /**
300
+ * Set how long (in minutes) issued recaller cookies should live — the `setRememberDuration`
301
+ * equivalent. The guard does not write cookies itself; read it back via
302
+ * {@link SessionGuard.getRememberDuration} when turning a recaller value into a cookie.
303
+ */
304
+ setRememberDuration(minutes) {
305
+ this.rememberDuration = minutes;
306
+ return this;
307
+ }
308
+ /** The "remember me" cookie lifetime in minutes. The `getRememberDuration` equivalent. */
309
+ getRememberDuration() {
310
+ return this.rememberDuration;
311
+ }
312
+ /**
313
+ * Attempt HTTP Basic authentication, logging the user in for the session — the Laravel `basic`.
314
+ * Resolves to `undefined` when already authenticated or when the `Authorization: Basic` header
315
+ * validates; otherwise resolves to a `401` challenge response (`WWW-Authenticate: Basic`).
316
+ * Requires the request (constructor option or {@link SessionGuard.setRequest}).
317
+ */
318
+ async basic(field = "email") {
319
+ if (await this.check()) return void 0;
320
+ const credentials = this.basicCredentialsFromRequest(field);
321
+ if (credentials !== null && await this.attempt(credentials)) return void 0;
322
+ return failedBasicResponse();
323
+ }
324
+ /**
325
+ * Perform a stateless HTTP Basic attempt (no session persistence) — the Laravel `onceBasic`.
326
+ * Resolves to `undefined` on success, or the `401` challenge response on failure.
327
+ */
328
+ async onceBasic(field = "email") {
329
+ const credentials = this.basicCredentialsFromRequest(field);
330
+ if (credentials !== null && await this.once(credentials)) return void 0;
331
+ return failedBasicResponse();
332
+ }
333
+ /**
334
+ * Issue a fresh remember-me token for `user`, persist it through the provider, and return the
335
+ * recaller value (`id|token`) to store in a long-lived cookie. The Laravel "remember me" persist.
336
+ */
337
+ async remember(user) {
338
+ const token = randomBytes(20).toString("hex");
339
+ await this.provider.updateRememberToken(user, token);
340
+ return recallerValue(user.getAuthIdentifier(), token);
341
+ }
342
+ /**
343
+ * Authenticate from a recaller cookie value (`id|token`), logging the user in for the session on a
344
+ * constant-time token match (the Laravel `viaRemember` path). Returns the user, or `null`.
345
+ */
346
+ async loginUsingRecaller(value) {
347
+ const recaller = parseRecaller(value);
348
+ if (recaller === null) return null;
349
+ const user = await this.provider.retrieveByToken(recaller.id, recaller.token);
350
+ if (user !== null) {
351
+ this.viaRememberFlag = true;
352
+ this.updateSession(user);
353
+ this.events?.dispatch(new Login(this.name, user, true));
354
+ this.setUser(user);
355
+ }
356
+ return user;
357
+ }
358
+ /** Persist the user's id and current password hash into the session. */
359
+ updateSession(user) {
360
+ this.session.put(this.key, user.getAuthIdentifier());
361
+ this.session.put(PASSWORD_HASH_SESSION_KEY, user.getAuthPassword());
362
+ }
363
+ /** Whether `credentials` validate against `user`, dispatching `Validated` when they do. */
364
+ async hasValidCredentials(user, credentials) {
365
+ const valid = await this.provider.validateCredentials(user, credentials);
366
+ if (valid) this.events?.dispatch(new Validated(this.name, user));
367
+ return valid;
368
+ }
369
+ /** Run the `attemptWhen` callbacks; every one must return `true` for the login to proceed. */
370
+ async shouldLogin(callbacks, user) {
371
+ const list = typeof callbacks === "function" ? [callbacks] : callbacks;
372
+ for (const callback of list) {
373
+ if (!await callback(user, this)) return false;
374
+ }
375
+ return true;
376
+ }
377
+ /** Clear the session synchronously, then finish teardown (token cycling + event) async. */
378
+ performLogout(cycleToken) {
379
+ const known = this.resolved ? this.cachedUser : null;
380
+ const id = this.session.get(this.key);
381
+ this.session.forget(this.key);
382
+ this.session.forget(PASSWORD_HASH_SESSION_KEY);
383
+ this.cachedUser = null;
384
+ this.resolved = true;
385
+ this.viaRememberFlag = false;
386
+ return this.finishLogout(known, id, cycleToken);
387
+ }
388
+ /** Resolve the user that was logged out, cycle their remember token, and dispatch the event. */
389
+ async finishLogout(known, id, cycleToken) {
390
+ const user = known ?? (id === null ? null : await this.provider.retrieveById(id));
391
+ if (user === null) return;
392
+ if (cycleToken && hasRememberToken(user)) {
393
+ await this.provider.updateRememberToken(user, randomBytes(20).toString("hex"));
394
+ }
395
+ this.events?.dispatch(
396
+ cycleToken ? new Logout(this.name, user) : new CurrentDeviceLogout(this.name, user)
397
+ );
398
+ }
399
+ /** Parse `Authorization: Basic …` from the request into `{ [field], password }`, or `null`. */
400
+ basicCredentialsFromRequest(field) {
401
+ if (this.request === void 0) return null;
402
+ const header = this.request.header("authorization");
403
+ if (!header?.toLowerCase().startsWith("basic ")) return null;
404
+ const decoded = Buffer.from(header.slice(6).trim(), "base64").toString("utf8");
405
+ const separator = decoded.indexOf(":");
406
+ if (separator === -1) return null;
407
+ return { [field]: decoded.slice(0, separator), password: decoded.slice(separator + 1) };
408
+ }
409
+ };
410
+ function failedBasicResponse() {
411
+ return Response.make("Invalid Basic credentials.", 401).withHeaders({
412
+ "WWW-Authenticate": "Basic"
413
+ });
414
+ }
415
+ function hasRememberToken(user) {
416
+ if (!("getRememberToken" in user)) return false;
417
+ const token = user.getRememberToken();
418
+ return typeof token === "string" && token.length > 0;
419
+ }
420
+ function recallerValue(id, token) {
421
+ return `${String(id)}|${token}`;
422
+ }
423
+ function parseRecaller(value) {
424
+ const separator = value.indexOf("|");
425
+ if (separator <= 0) return null;
426
+ const token = value.slice(separator + 1);
427
+ if (token.length === 0) return null;
428
+ return { id: value.slice(0, separator), token };
429
+ }
430
+ var TokenGuard = class {
431
+ constructor(provider, request, inputKey = TOKEN_KEY, options = {}) {
432
+ this.provider = provider;
433
+ this.request = request;
434
+ this.inputKey = inputKey;
435
+ this.name = options.name ?? "api";
436
+ this.events = options.events;
437
+ }
438
+ provider;
439
+ request;
440
+ inputKey;
441
+ cachedUser = null;
442
+ resolved = false;
443
+ name;
444
+ events;
445
+ async user() {
446
+ if (this.resolved) return this.cachedUser;
447
+ const token = this.tokenForRequest();
448
+ this.cachedUser = token === void 0 ? null : await this.provider.retrieveByCredentials({ [this.inputKey]: token });
449
+ this.resolved = true;
450
+ if (this.cachedUser !== null) {
451
+ this.events?.dispatch(new Authenticated(this.name, this.cachedUser));
452
+ }
453
+ return this.cachedUser;
454
+ }
455
+ async check() {
456
+ return await this.user() !== null;
457
+ }
458
+ async guest() {
459
+ return !await this.check();
460
+ }
461
+ async id() {
462
+ const user = await this.user();
463
+ return user === null ? null : user.getAuthIdentifier();
464
+ }
465
+ async validate(credentials) {
466
+ const user = await this.provider.retrieveByCredentials(credentials);
467
+ if (user === null) return false;
468
+ return this.provider.validateCredentials(user, credentials);
469
+ }
470
+ setUser(user) {
471
+ this.cachedUser = user;
472
+ this.resolved = true;
473
+ this.events?.dispatch(new Authenticated(this.name, user));
474
+ }
475
+ /** Read the API token from the bearer header, then the query string, then the input bag. */
476
+ tokenForRequest() {
477
+ const bearer = this.request.bearerToken();
478
+ if (bearer !== void 0) return bearer;
479
+ const query = this.request.query(this.inputKey);
480
+ if (typeof query === "string" && query.length > 0) return query;
481
+ const input = this.request.input(this.inputKey);
482
+ return typeof input === "string" && input.length > 0 ? input : void 0;
483
+ }
484
+ };
485
+ var RequestGuard = class {
486
+ constructor(callback, request, provider) {
487
+ this.callback = callback;
488
+ this.provider = provider;
489
+ this.request = request;
490
+ }
491
+ callback;
492
+ provider;
493
+ cachedUser = null;
494
+ resolved = false;
495
+ request;
496
+ async user() {
497
+ if (this.resolved) return this.cachedUser;
498
+ this.cachedUser = this.request === void 0 ? null : await this.callback(this.request, this.provider) ?? null;
499
+ this.resolved = true;
500
+ return this.cachedUser;
501
+ }
502
+ async check() {
503
+ return await this.user() !== null;
504
+ }
505
+ async guest() {
506
+ return !await this.check();
507
+ }
508
+ async id() {
509
+ const user = await this.user();
510
+ return user === null ? null : user.getAuthIdentifier();
511
+ }
512
+ /**
513
+ * Whether the callback resolves a user for `credentials['request']` — the Laravel
514
+ * `RequestGuard::validate`, which runs the resolver against the given request.
515
+ */
516
+ async validate(credentials) {
517
+ const request = credentials["request"];
518
+ if (!(request instanceof Request)) return false;
519
+ return (await this.callback(request, this.provider) ?? null) !== null;
520
+ }
521
+ setUser(user) {
522
+ this.cachedUser = user;
523
+ this.resolved = true;
524
+ }
525
+ /** Swap the request and reset the cached user. The `setRequest` equivalent. */
526
+ setRequest(request) {
527
+ this.request = request;
528
+ this.cachedUser = null;
529
+ this.resolved = false;
530
+ return this;
531
+ }
532
+ };
533
+
534
+ // src/manager.ts
535
+ var AuthManager = class {
536
+ constructor(defaultGuard = "web") {
537
+ this.defaultGuard = defaultGuard;
538
+ }
539
+ defaultGuard;
540
+ guards = /* @__PURE__ */ new Map();
541
+ /** Register a guard factory under `name`. The `Auth::extend()` equivalent. */
542
+ extend(name, factory) {
543
+ this.guards.set(name, factory);
544
+ return this;
545
+ }
546
+ /**
547
+ * Register a closure-driven guard under `name` — the `Auth::viaRequest()` equivalent. The
548
+ * callback receives the request (and `provider`, when given) and returns the authenticated user
549
+ * or `null`; the manager builds a {@link RequestGuard} around it on every resolve.
550
+ */
551
+ viaRequest(name, callback, provider) {
552
+ return this.extend(name, (request) => new RequestGuard(callback, request, provider));
553
+ }
554
+ /**
555
+ * Resolve a guard by name (or the default), forwarding `request` to the factory so
556
+ * request-scoped guards (e.g. {@link AuthManager.viaRequest}) can read it. Throws if the guard is
557
+ * not registered.
558
+ */
559
+ guard(name, request) {
560
+ const resolved = name ?? this.defaultGuard;
561
+ const factory = this.guards.get(resolved);
562
+ if (factory === void 0) {
563
+ throw new Error(`Auth guard [${resolved}] is not defined.`);
564
+ }
565
+ return factory(request);
566
+ }
567
+ /** Change the default guard name. The `Auth::shouldUse()` equivalent. */
568
+ setDefaultGuard(name) {
569
+ this.defaultGuard = name;
570
+ return this;
571
+ }
572
+ /** The current default guard name. */
573
+ getDefaultGuard() {
574
+ return this.defaultGuard;
575
+ }
576
+ };
577
+ var USER_ATTRIBUTE = "mason.user";
578
+ var PASSWORD_CONFIRMED_AT_SESSION_KEY = "auth.password_confirmed_at";
579
+ var DEFAULT_PASSWORD_TIMEOUT_SECONDS = 10800;
580
+ var AuthenticationError = class extends HttpException {
581
+ constructor(message = "Unauthenticated.") {
582
+ super(401, message);
583
+ this.name = "AuthenticationError";
584
+ }
585
+ };
586
+ function getUser(req) {
587
+ return req.attribute(USER_ATTRIBUTE);
588
+ }
589
+ function authenticateSession(provider) {
590
+ return async (req, next) => {
591
+ const session = requireSession(req);
592
+ const guard = new SessionGuard(provider, session);
593
+ const user = await guard.user();
594
+ if (user === null) throw new AuthenticationError();
595
+ const storedHash = session.get(PASSWORD_HASH_SESSION_KEY);
596
+ if (storedHash !== null && storedHash !== user.getAuthPassword()) {
597
+ await guard.logoutCurrentDevice();
598
+ throw new AuthenticationError();
599
+ }
600
+ if (storedHash === null) session.put(PASSWORD_HASH_SESSION_KEY, user.getAuthPassword());
601
+ return next(req.withAttribute(USER_ATTRIBUTE, user));
602
+ };
603
+ }
604
+ function authenticateToken(provider, inputKey) {
605
+ return async (req, next) => {
606
+ const guard = inputKey === void 0 ? new TokenGuard(provider, req) : new TokenGuard(provider, req, inputKey);
607
+ const user = await guard.user();
608
+ if (user === null) throw new AuthenticationError();
609
+ return next(req.withAttribute(USER_ATTRIBUTE, user));
610
+ };
611
+ }
612
+ function redirectIfAuthenticated(provider, redirectTo = "/home") {
613
+ return async (req, next) => {
614
+ const session = getSession(req);
615
+ if (session === void 0) return next(req);
616
+ const user = await new SessionGuard(provider, session).user();
617
+ return user === null ? next(req) : Response.redirectTo(redirectTo);
618
+ };
619
+ }
620
+ function requirePassword(redirectTo = "/confirm-password", passwordTimeoutSeconds = DEFAULT_PASSWORD_TIMEOUT_SECONDS, now = () => /* @__PURE__ */ new Date()) {
621
+ return async (req, next) => {
622
+ const session = requireSession(req);
623
+ const confirmedAt = session.get(PASSWORD_CONFIRMED_AT_SESSION_KEY);
624
+ const fresh = typeof confirmedAt === "number" && now().getTime() / 1e3 - confirmedAt < passwordTimeoutSeconds;
625
+ if (fresh) return next(req);
626
+ if (req.wantsJson()) {
627
+ return Response.json({ message: "Password confirmation required." }, 423);
628
+ }
629
+ return Response.redirectTo(redirectTo);
630
+ };
631
+ }
632
+ async function confirmPassword(provider, session, user, password, now = () => /* @__PURE__ */ new Date()) {
633
+ const credentials = { password };
634
+ if (!await provider.validateCredentials(user, credentials)) return false;
635
+ session.put(PASSWORD_CONFIRMED_AT_SESSION_KEY, Math.floor(now().getTime() / 1e3));
636
+ return true;
637
+ }
638
+ function requireSession(req) {
639
+ const session = getSession(req);
640
+ if (session === void 0) {
641
+ throw new HttpException(
642
+ 500,
643
+ "Session authentication requires the session middleware to run first."
644
+ );
645
+ }
646
+ return session;
647
+ }
648
+ var PasswordStatus = {
649
+ ResetLinkSent: "passwords.sent",
650
+ PasswordReset: "passwords.reset",
651
+ InvalidUser: "passwords.user",
652
+ InvalidToken: "passwords.token",
653
+ InvalidPassword: "passwords.password",
654
+ ResetThrottled: "passwords.throttled"
655
+ };
656
+ var ArrayTokenRepository = class {
657
+ store = /* @__PURE__ */ new Map();
658
+ hasher;
659
+ expireMinutes;
660
+ throttleSeconds;
661
+ now;
662
+ makeToken;
663
+ constructor(options) {
664
+ this.hasher = options.hasher;
665
+ this.expireMinutes = options.expireMinutes ?? 60;
666
+ this.throttleSeconds = options.throttleSeconds ?? 60;
667
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
668
+ this.makeToken = options.createToken ?? (() => randomBytes(20).toString("hex"));
669
+ }
670
+ async create(user) {
671
+ const token = this.makeToken();
672
+ this.store.set(user.getAuthIdentifier(), {
673
+ hashed: this.hasher.make(token),
674
+ createdAt: this.now().getTime()
675
+ });
676
+ return token;
677
+ }
678
+ async exists(user, token) {
679
+ const record = this.store.get(user.getAuthIdentifier());
680
+ if (record === void 0 || this.expired(record)) return false;
681
+ return this.hasher.check(token, record.hashed);
682
+ }
683
+ async recentlyCreatedToken(user) {
684
+ const record = this.store.get(user.getAuthIdentifier());
685
+ if (record === void 0) return false;
686
+ return (this.now().getTime() - record.createdAt) / 1e3 < this.throttleSeconds;
687
+ }
688
+ async delete(user) {
689
+ this.store.delete(user.getAuthIdentifier());
690
+ }
691
+ async deleteExpired() {
692
+ for (const [key, record] of this.store) {
693
+ if (this.expired(record)) this.store.delete(key);
694
+ }
695
+ }
696
+ expired(record) {
697
+ return (this.now().getTime() - record.createdAt) / 6e4 >= this.expireMinutes;
698
+ }
699
+ };
700
+ var PasswordBroker = class {
701
+ constructor(users, tokens, events) {
702
+ this.users = users;
703
+ this.tokens = tokens;
704
+ this.events = events;
705
+ }
706
+ users;
707
+ tokens;
708
+ events;
709
+ /**
710
+ * Send a reset link: resolve the user from `credentials`, throttle repeat requests, mint a token,
711
+ * and hand it to `send`. Returns {@link PasswordStatus.ResetLinkSent} on success.
712
+ */
713
+ async sendResetLink(credentials, send) {
714
+ const user = await this.users.retrieveByCredentials(credentials);
715
+ if (user === null) return PasswordStatus.InvalidUser;
716
+ if (await this.tokens.recentlyCreatedToken(user)) return PasswordStatus.ResetThrottled;
717
+ const token = await this.tokens.create(user);
718
+ await send(user, token);
719
+ return PasswordStatus.ResetLinkSent;
720
+ }
721
+ /**
722
+ * Reset a password: resolve the user, require a non-empty password, verify the token, then run
723
+ * `reset` to persist and delete the token. Returns {@link PasswordStatus.PasswordReset} on success.
724
+ */
725
+ async reset(credentials, reset) {
726
+ const user = await this.users.retrieveByCredentials(this.lookupOnly(credentials));
727
+ if (user === null) return PasswordStatus.InvalidUser;
728
+ if (typeof credentials.password !== "string" || credentials.password === "") {
729
+ return PasswordStatus.InvalidPassword;
730
+ }
731
+ if (!await this.tokens.exists(user, credentials.token)) return PasswordStatus.InvalidToken;
732
+ await reset(user, credentials.password);
733
+ await this.tokens.delete(user);
734
+ this.events?.dispatch(new PasswordReset(user));
735
+ return PasswordStatus.PasswordReset;
736
+ }
737
+ /** The user-lookup credentials, with `token`/`password` removed so they don't act as match fields. */
738
+ lookupOnly(credentials) {
739
+ const lookup = {};
740
+ for (const [key, value] of Object.entries(credentials)) {
741
+ if (key !== "token" && key !== "password") lookup[key] = value;
742
+ }
743
+ return lookup;
744
+ }
745
+ };
746
+ var REMEMBER_TOKEN = "remember_token";
747
+ var GenericUser = class {
748
+ constructor(attributes, identifierName = "id", passwordName = "password") {
749
+ this.attributes = attributes;
750
+ this.identifierName = identifierName;
751
+ this.passwordName = passwordName;
752
+ }
753
+ attributes;
754
+ identifierName;
755
+ passwordName;
756
+ getAuthIdentifier() {
757
+ const id = this.attributes[this.identifierName];
758
+ if (typeof id === "number" || typeof id === "string") return id;
759
+ return "";
760
+ }
761
+ getAuthIdentifierName() {
762
+ return this.identifierName;
763
+ }
764
+ getAuthPassword() {
765
+ const password = this.attributes[this.passwordName];
766
+ return typeof password === "string" ? password : "";
767
+ }
768
+ setAuthPassword(hashed) {
769
+ this.attributes[this.passwordName] = hashed;
770
+ }
771
+ getRememberToken() {
772
+ const token = this.attributes[REMEMBER_TOKEN];
773
+ return typeof token === "string" ? token : null;
774
+ }
775
+ setRememberToken(token) {
776
+ this.attributes[REMEMBER_TOKEN] = token;
777
+ }
778
+ /** Read an arbitrary attribute, used by providers to match credentials. */
779
+ getAttribute(key) {
780
+ return this.attributes[key];
781
+ }
782
+ };
783
+ var ArrayUserProvider = class {
784
+ constructor(users, hasher) {
785
+ this.users = users;
786
+ this.hasher = hasher;
787
+ }
788
+ users;
789
+ hasher;
790
+ retrieveById(identifier) {
791
+ const user = this.users.find((candidate) => candidate.getAuthIdentifier() === identifier);
792
+ return Promise.resolve(user ?? null);
793
+ }
794
+ retrieveByToken(identifier, token) {
795
+ const user = this.users.find(
796
+ (candidate) => String(candidate.getAuthIdentifier()) === String(identifier)
797
+ );
798
+ const stored = user?.getRememberToken();
799
+ if (user === void 0 || stored === null || stored === void 0 || stored.length === 0) {
800
+ return Promise.resolve(null);
801
+ }
802
+ return Promise.resolve(safeEqual2(stored, token) ? user : null);
803
+ }
804
+ updateRememberToken(user, token) {
805
+ if (isRememberable(user)) user.setRememberToken(token);
806
+ return Promise.resolve();
807
+ }
808
+ retrieveByCredentials(credentials) {
809
+ const keys = Object.keys(credentials).filter((key) => !key.includes("password"));
810
+ if (keys.length === 0) return Promise.resolve(null);
811
+ const user = this.users.find(
812
+ (candidate) => keys.every((key) => candidate.getAttribute(key) === credentials[key])
813
+ );
814
+ return Promise.resolve(user ?? null);
815
+ }
816
+ validateCredentials(user, credentials) {
817
+ const password = credentials["password"];
818
+ if (typeof password !== "string") return Promise.resolve(false);
819
+ return Promise.resolve(this.hasher.check(password, user.getAuthPassword()));
820
+ }
821
+ /**
822
+ * Re-hash and persist the user's password when its cost parameters no longer match the hasher's
823
+ * (or always, when `force` is set) — the Laravel `rehashPasswordIfRequired`. Persists through the
824
+ * {@link PasswordUpdatable} seam, mirroring how remember tokens are persisted.
825
+ */
826
+ rehashPasswordIfRequired(user, credentials, force = false) {
827
+ const password = credentials["password"];
828
+ if (typeof password !== "string") return Promise.resolve();
829
+ if (!force && !this.hasher.needsRehash(user.getAuthPassword())) return Promise.resolve();
830
+ if (isPasswordUpdatable(user)) user.setAuthPassword(this.hasher.make(password));
831
+ return Promise.resolve();
832
+ }
833
+ };
834
+ function isRememberable(user) {
835
+ return "setRememberToken" in user && typeof user.setRememberToken === "function";
836
+ }
837
+ function isPasswordUpdatable(user) {
838
+ return "setAuthPassword" in user && typeof user.setAuthPassword === "function";
839
+ }
840
+ function safeEqual2(a, b) {
841
+ const bufferA = Buffer.from(a);
842
+ const bufferB = Buffer.from(b);
843
+ if (bufferA.length !== bufferB.length) return false;
844
+ return timingSafeEqual(bufferA, bufferB);
845
+ }
846
+
847
+ // src/index.ts
848
+ var VERSION = "0.1.0";
849
+
850
+ export { ArrayTokenRepository, ArrayUserProvider, Attempting, AuthManager, Authenticated, AuthenticationError, CurrentDeviceLogout, EmailVerifier, Failed, GenericUser, Lockout, Login, Logout, OtherDeviceLogout, PASSWORD_CONFIRMED_AT_SESSION_KEY, PASSWORD_HASH_SESSION_KEY, PasswordBroker, PasswordReset, PasswordStatus, Registered, RequestGuard, SessionGuard, TokenGuard, VERSION, Validated, Verified, authenticateSession, authenticateToken, confirmPassword, getUser, redirectIfAuthenticated, requirePassword };
851
+ //# sourceMappingURL=index.js.map
852
+ //# sourceMappingURL=index.js.map