@plinthjs/auth 0.1.0 → 0.1.2

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 The Mason contributors
3
+ Copyright (c) 2026 The Plinth contributors
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # @plinthjs/auth
2
2
 
3
- Mason's authentication layer, the `Illuminate\Auth` equivalent. The `Authenticatable` /
3
+ Plinth's authentication layer. The `Authenticatable` /
4
4
  `UserProvider` / `Guard` contracts, an in-memory `ArrayUserProvider` over `GenericUser`s (passwords
5
5
  verified through `@plinthjs/encryption`), a stateful `SessionGuard` (with `attemptWhen`, HTTP Basic,
6
6
  remember-me and the logout variants), a stateless `TokenGuard`, an `AuthManager` for named guards,
7
- password resets, signed email verification, the Laravel auth event classes, and HTTP middleware.
7
+ password resets, signed email verification, the auth event classes, and HTTP middleware.
8
8
 
9
9
  ## Install
10
10
 
@@ -110,6 +110,6 @@ status === PasswordStatus.PasswordReset
110
110
  implementing `MustVerifyEmail`; `verify(user, payload)` checks it and marks the email verified.
111
111
 
112
112
  Guards, the broker and the verifier dispatch `Attempting`, `Login`, `Failed`, `Logout`,
113
- `PasswordReset`, `Verified` and the other Laravel event classes through any object with a
113
+ `PasswordReset`, `Verified` and the other standard event classes through any object with a
114
114
  `dispatch(event)` method (the `AuthEvents` seam), passed as the `events` option, or as the third
115
115
  argument of the `PasswordBroker` constructor.
package/dist/index.cjs CHANGED
@@ -114,7 +114,7 @@ var EmailVerifier = class {
114
114
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
115
115
  this.events = options.events;
116
116
  }
117
- /** A stable hash of the user's email — proves the link was issued for this exact address. */
117
+ /** A stable hash of the user's email - proves the link was issued for this exact address. */
118
118
  hashFor(user) {
119
119
  return crypto.createHash("sha256").update(user.getEmailForVerification()).digest("hex");
120
120
  }
@@ -130,7 +130,7 @@ var EmailVerifier = class {
130
130
  }
131
131
  /**
132
132
  * Verify a payload and mark the user verified. Returns `false` on a bad or expired signature;
133
- * idempotent — an already-verified user returns `true` without re-marking.
133
+ * idempotent - an already-verified user returns `true` without re-marking.
134
134
  */
135
135
  async verify(user, payload) {
136
136
  if (!this.isValid(user, payload)) return false;
@@ -203,7 +203,7 @@ var SessionGuard = class {
203
203
  return this.attemptWhen(credentials);
204
204
  }
205
205
  /**
206
- * Attempt to authenticate with additional callbacks — the Laravel `attemptWhen`. The callbacks
206
+ * Attempt to authenticate with additional callbacks - the `attemptWhen`. The callbacks
207
207
  * run after the credentials validate, receiving the user and this guard; every one must return
208
208
  * `true` (a falsy result fails the attempt without logging the user in).
209
209
  */
@@ -240,7 +240,7 @@ var SessionGuard = class {
240
240
  return user;
241
241
  }
242
242
  /**
243
- * Log the current user out, cycling the remember token so every recaller dies — the Laravel
243
+ * Log the current user out, cycling the remember token so every recaller dies - the conventional
244
244
  * `logout`. The session keys are cleared synchronously; the returned promise resolves once the
245
245
  * token has been cycled through the provider and the `Logout` event dispatched.
246
246
  */
@@ -248,7 +248,7 @@ var SessionGuard = class {
248
248
  return this.performLogout(true);
249
249
  }
250
250
  /**
251
- * Log the current user out on this device only — the Laravel `logoutCurrentDevice`. Unlike
251
+ * Log the current user out on this device only - the `logoutCurrentDevice`. Unlike
252
252
  * {@link SessionGuard.logout} the remember token is *not* cycled, so other remembered devices
253
253
  * stay logged in. Dispatches `CurrentDeviceLogout`.
254
254
  */
@@ -256,17 +256,16 @@ var SessionGuard = class {
256
256
  return this.performLogout(false);
257
257
  }
258
258
  /**
259
- * Invalidate the user's sessions on every other device — the Laravel `logoutOtherDevices`.
259
+ * Invalidate the user's sessions on every other device - the `logoutOtherDevices`.
260
260
  * Validates `password` against the current user (throwing when it does not match), then:
261
261
  *
262
262
  * - force re-hashes the password through {@link UserProvider.rehashPasswordIfRequired} (when the
263
263
  * provider supports it) and refreshes this session's stored password hash, so any session
264
- * checked by `authenticateSession` whose stored hash is now stale is logged out — the same
265
- * session-password-hash mechanism Laravel's `AuthenticateSession` middleware uses; and
264
+ * checked by `authenticateSession` whose stored hash is now stale is logged out - the same
265
+ * session-password-hash mechanism the conventional `AuthenticateSession` middleware uses; and
266
266
  * - cycles the remember token, killing every previously issued recaller cookie.
267
267
  *
268
- * Returns the fresh recaller value for *this* device (the Laravel `queueRecallerCookie`
269
- * re-issue), or `null` when nobody is authenticated.
268
+ * Returns the fresh recaller value for *this* device, or `null` when nobody is authenticated.
270
269
  */
271
270
  async logoutOtherDevices(password) {
272
271
  const user = await this.user();
@@ -299,7 +298,7 @@ var SessionGuard = class {
299
298
  return this.viaRememberFlag;
300
299
  }
301
300
  /**
302
- * Set how long (in minutes) issued recaller cookies should live — the `setRememberDuration`
301
+ * Set how long (in minutes) issued recaller cookies should live - the `setRememberDuration`
303
302
  * equivalent. The guard does not write cookies itself; read it back via
304
303
  * {@link SessionGuard.getRememberDuration} when turning a recaller value into a cookie.
305
304
  */
@@ -312,7 +311,7 @@ var SessionGuard = class {
312
311
  return this.rememberDuration;
313
312
  }
314
313
  /**
315
- * Attempt HTTP Basic authentication, logging the user in for the session — the Laravel `basic`.
314
+ * Attempt HTTP Basic authentication, logging the user in for the session - the `basic`.
316
315
  * Resolves to `undefined` when already authenticated or when the `Authorization: Basic` header
317
316
  * validates; otherwise resolves to a `401` challenge response (`WWW-Authenticate: Basic`).
318
317
  * Requires the request (constructor option or {@link SessionGuard.setRequest}).
@@ -324,7 +323,7 @@ var SessionGuard = class {
324
323
  return failedBasicResponse();
325
324
  }
326
325
  /**
327
- * Perform a stateless HTTP Basic attempt (no session persistence) — the Laravel `onceBasic`.
326
+ * Perform a stateless HTTP Basic attempt (no session persistence) - the `onceBasic`.
328
327
  * Resolves to `undefined` on success, or the `401` challenge response on failure.
329
328
  */
330
329
  async onceBasic(field = "email") {
@@ -334,7 +333,7 @@ var SessionGuard = class {
334
333
  }
335
334
  /**
336
335
  * Issue a fresh remember-me token for `user`, persist it through the provider, and return the
337
- * recaller value (`id|token`) to store in a long-lived cookie. The Laravel "remember me" persist.
336
+ * recaller value (`id|token`) to store in a long-lived cookie.
338
337
  */
339
338
  async remember(user) {
340
339
  const token = crypto.randomBytes(20).toString("hex");
@@ -343,7 +342,7 @@ var SessionGuard = class {
343
342
  }
344
343
  /**
345
344
  * Authenticate from a recaller cookie value (`id|token`), logging the user in for the session on a
346
- * constant-time token match (the Laravel `viaRemember` path). Returns the user, or `null`.
345
+ * constant-time token match. Returns the user, or `null`.
347
346
  */
348
347
  async loginUsingRecaller(value) {
349
348
  const recaller = parseRecaller(value);
@@ -512,7 +511,7 @@ var RequestGuard = class {
512
511
  return user === null ? null : user.getAuthIdentifier();
513
512
  }
514
513
  /**
515
- * Whether the callback resolves a user for `credentials['request']` — the Laravel
514
+ * Whether the callback resolves a user for `credentials['request']` - the conventional
516
515
  * `RequestGuard::validate`, which runs the resolver against the given request.
517
516
  */
518
517
  async validate(credentials) {
@@ -546,7 +545,7 @@ var AuthManager = class {
546
545
  return this;
547
546
  }
548
547
  /**
549
- * Register a closure-driven guard under `name` — the `Auth::viaRequest()` equivalent. The
548
+ * Register a closure-driven guard under `name` - the `Auth::viaRequest()` equivalent. The
550
549
  * callback receives the request (and `provider`, when given) and returns the authenticated user
551
550
  * or `null`; the manager builds a {@link RequestGuard} around it on every resolve.
552
551
  */
@@ -576,7 +575,7 @@ var AuthManager = class {
576
575
  return this.defaultGuard;
577
576
  }
578
577
  };
579
- var USER_ATTRIBUTE = "mason.user";
578
+ var USER_ATTRIBUTE = "plinth.user";
580
579
  var PASSWORD_CONFIRMED_AT_SESSION_KEY = "auth.password_confirmed_at";
581
580
  var DEFAULT_PASSWORD_TIMEOUT_SECONDS = 10800;
582
581
  var AuthenticationError = class extends http.HttpException {
@@ -822,7 +821,7 @@ var ArrayUserProvider = class {
822
821
  }
823
822
  /**
824
823
  * Re-hash and persist the user's password when its cost parameters no longer match the hasher's
825
- * (or always, when `force` is set) — the Laravel `rehashPasswordIfRequired`. Persists through the
824
+ * (or always, when `force` is set) - the `rehashPasswordIfRequired`. Persists through the
826
825
  * {@link PasswordUpdatable} seam, mirroring how remember tokens are persisted.
827
826
  */
828
827
  rehashPasswordIfRequired(user, credentials, force = false) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/events.ts","../src/email-verification.ts","../src/guards.ts","../src/manager.ts","../src/middleware.ts","../src/passwords.ts","../src/providers.ts","../src/index.ts"],"names":["createHash","createHmac","timingSafeEqual","randomBytes","HttpResponse","Request","HttpException","session","getSession","Response","safeEqual"],"mappings":";;;;;;;;;AAaO,IAAM,aAAN,MAAiB;AAAA,EACtB,WAAA,CAEW,KAAA,EAEA,WAAA,EAEA,QAAA,GAAW,KAAA,EACpB;AALS,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAEA,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAEA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA,EACR;AAAA,EALQ,KAAA;AAAA,EAEA,WAAA;AAAA,EAEA,QAAA;AAEb;AAGO,IAAM,YAAN,MAAgB;AAAA,EACrB,WAAA,CAEW,OAEA,IAAA,EACT;AAHS,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAEA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EACR;AAAA,EAHQ,KAAA;AAAA,EAEA,IAAA;AAEb;AAGO,IAAM,QAAN,MAAY;AAAA,EACjB,WAAA,CAEW,KAAA,EAEA,IAAA,EAEA,QAAA,EACT;AALS,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAEA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAEA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA,EACR;AAAA,EALQ,KAAA;AAAA,EAEA,IAAA;AAAA,EAEA,QAAA;AAEb;AAGO,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CAAA;AACvC,IAAA,IAAI,OAAO,QAAA,KAAa,QAAA,EAAU,OAAO,QAAQ,OAAA,EAAQ;AACzD,IAAA,IAAI,CAAC,KAAA,IAAS,CAAC,IAAA,CAAK,MAAA,CAAO,WAAA,CAAY,IAAA,CAAK,eAAA,EAAiB,CAAA,EAAG,OAAO,OAAA,CAAQ,OAAA,EAAQ;AACvF,IAAA,IAAI,mBAAA,CAAoB,IAAI,CAAA,EAAG,IAAA,CAAK,gBAAgB,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAC,CAAA;AAC9E,IAAA,OAAO,QAAQ,OAAA,EAAQ;AAAA,EACzB;AACF;AAGA,SAAS,eAAe,IAAA,EAA+D;AACrF,EAAA,OAAO,kBAAA,IAAsB,IAAA,IAAQ,OAAO,IAAA,CAAK,gBAAA,KAAqB,UAAA;AACxE;AAGA,SAAS,oBAAoB,IAAA,EAAoE;AAC/F,EAAA,OAAO,iBAAA,IAAqB,IAAA,IAAQ,OAAO,IAAA,CAAK,eAAA,KAAoB,UAAA;AACtE;AAGA,SAASA,UAAAA,CAAU,GAAW,CAAA,EAAoB;AAChD,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA;AAC7B,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA;AAC7B,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,OAAA,CAAQ,MAAA,EAAQ,OAAO,KAAA;AAC9C,EAAA,OAAOR,sBAAAA,CAAgB,SAAS,OAAO,CAAA;AACzC;;;AC7HO,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["/**\n * Authentication events — the Laravel `Illuminate\\Auth\\Events` classes. Guards and brokers dispatch\n * these through the optional {@link AuthEvents} seam at the same moments Laravel fires them:\n * {@link Attempting} before a credential attempt, {@link Validated} once credentials check out,\n * {@link Login} + {@link Authenticated} when a user is logged in / set on the guard, {@link Failed}\n * on a bad attempt, {@link Logout} / {@link CurrentDeviceLogout} / {@link OtherDeviceLogout} on the\n * logout variants, and {@link Registered} / {@link Verified} / {@link PasswordReset} /\n * {@link Lockout} around the account lifecycle. Plain classes with readonly data — dispatchable\n * through any dispatcher that takes an object.\n */\nimport type { Authenticatable, Credentials } from './contracts'\n\n/** Fired before every credential attempt — the Laravel `Attempting` event. */\nexport class Attempting {\n constructor(\n /** The guard name the attempt runs on. */\n readonly guard: string,\n /** The credentials being attempted (includes the plaintext password — handle with care). */\n readonly credentials: Credentials,\n /** Whether the attempt asked for \"remember me\" persistence. */\n readonly remember = false,\n ) {}\n}\n\n/** Fired when credentials validate against a user — the Laravel `Validated` event. */\nexport class Validated {\n constructor(\n /** The guard name the validation ran on. */\n readonly guard: string,\n /** The user the credentials validated against. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a user is logged in for the session — the Laravel `Login` event. */\nexport class Login {\n constructor(\n /** The guard name the login happened on. */\n readonly guard: string,\n /** The user that logged in. */\n readonly user: Authenticatable,\n /** Whether the login came from a remember-me recaller. */\n readonly remember: boolean,\n ) {}\n}\n\n/** Fired whenever a user is set on a guard — the Laravel `Authenticated` event. */\nexport class Authenticated {\n constructor(\n /** The guard name the user was set on. */\n readonly guard: string,\n /** The user that is now authenticated. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a credential attempt fails — the Laravel `Failed` event. */\nexport class Failed {\n constructor(\n /** The guard name the attempt ran on. */\n readonly guard: string,\n /** The user the credentials matched, or `null` when no user was found. */\n readonly user: Authenticatable | null,\n /** The credentials that failed. */\n readonly credentials: Credentials,\n ) {}\n}\n\n/** Fired when the user logs out (remember token cycled) — the Laravel `Logout` event. */\nexport class Logout {\n constructor(\n /** The guard name the logout happened on. */\n readonly guard: string,\n /** The user that logged out. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired on a current-device-only logout — the Laravel `CurrentDeviceLogout` event. */\nexport class CurrentDeviceLogout {\n constructor(\n /** The guard name the logout happened on. */\n readonly guard: string,\n /** The user that logged out on this device. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when the user's other devices are logged out — the Laravel `OtherDeviceLogout` event. */\nexport class OtherDeviceLogout {\n constructor(\n /** The guard name the logout happened on. */\n readonly guard: string,\n /** The user whose other sessions were invalidated. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a new account is registered (dispatched by application code) — the Laravel `Registered` event. */\nexport class Registered {\n constructor(\n /** The freshly registered user. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a user's email address is verified — the Laravel `Verified` event. */\nexport class Verified {\n constructor(\n /** The user whose email was just verified. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a password is reset through the broker — the Laravel `PasswordReset` event. */\nexport class PasswordReset {\n constructor(\n /** The user whose password was reset. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/**\n * Fired when login attempts are rate-limited — the Laravel `Lockout` event. Laravel carries the\n * HTTP request; Mason carries the credentials that triggered the lockout (dispatched by whatever\n * rate-limiting layer the application wires up).\n */\nexport class Lockout {\n constructor(\n /** The credentials whose attempts were locked out. */\n readonly credentials: Credentials,\n ) {}\n}\n","/**\n * Email verification — the Laravel `MustVerifyEmail` flow. {@link EmailVerifier} mints a signed,\n * expiring proof that a verification link was issued for a user's current email, and verifies it\n * before marking the user verified. The proof is an HMAC over the user id, a hash of the email, and\n * an expiry, so it cannot be forged and is invalidated if the email changes. Signing/clock are\n * injected, so it is deterministic and transport-agnostic (embed the payload in your verify URL).\n */\nimport { createHash, createHmac, timingSafeEqual } from 'node:crypto'\n\nimport { Verified } from './events'\n\nimport type { AuthEvents, Authenticatable } from './contracts'\n\n/** A user whose email address can be verified. The Laravel `MustVerifyEmail` contract. */\nexport interface MustVerifyEmail {\n /** The email address being verified. */\n getEmailForVerification(): string\n /** Whether the email has already been verified. */\n hasVerifiedEmail(): boolean\n /** Mark the email as verified (persist `email_verified_at`). */\n markEmailAsVerified(): void | Promise<void>\n}\n\n/** A verifiable user — an {@link Authenticatable} that also implements {@link MustVerifyEmail}. */\nexport type VerifiableUser = Authenticatable & MustVerifyEmail\n\n/** A signed, expiring verification payload — what a verification link carries. */\nexport interface VerificationSignature {\n /** Expiry as epoch milliseconds. */\n expires: number\n /** HMAC signature over the user id, email hash, and expiry. */\n signature: string\n}\n\n/** Options for {@link EmailVerifier}. */\nexport interface EmailVerifierOptions {\n /** Secret key the verification payload is HMAC-signed with. */\n secret: string\n /** Link lifetime in minutes. Default `60`. */\n expireMinutes?: number\n /** Injected clock for deterministic expiry. Default `() => new Date()`. */\n now?: () => Date\n /** Optional event dispatcher; `Verified` is dispatched when a user is first verified. */\n events?: AuthEvents\n}\n\n/** Mints and checks signed, expiring email-verification payloads. */\nexport class EmailVerifier {\n private readonly secret: string\n private readonly expireMinutes: number\n private readonly now: () => Date\n private readonly events: AuthEvents | undefined\n\n constructor(options: EmailVerifierOptions) {\n this.secret = options.secret\n this.expireMinutes = options.expireMinutes ?? 60\n this.now = options.now ?? ((): Date => new Date())\n this.events = options.events\n }\n\n /** A stable hash of the user's email — proves the link was issued for this exact address. */\n hashFor(user: VerifiableUser): string {\n return createHash('sha256').update(user.getEmailForVerification()).digest('hex')\n }\n\n /** Build a signed, expiring verification payload for `user` (embed it in the verification URL). */\n sign(user: VerifiableUser): VerificationSignature {\n const expires = this.now().getTime() + this.expireMinutes * 60_000\n return { expires, signature: this.signature(user, expires) }\n }\n\n /** Whether `payload` is a valid, unexpired signature for `user`'s current email. */\n isValid(user: VerifiableUser, payload: VerificationSignature): boolean {\n if (this.now().getTime() > payload.expires) return false\n return safeEqual(this.signature(user, payload.expires), payload.signature)\n }\n\n /**\n * Verify a payload and mark the user verified. Returns `false` on a bad or expired signature;\n * idempotent — an already-verified user returns `true` without re-marking.\n */\n async verify(user: VerifiableUser, payload: VerificationSignature): Promise<boolean> {\n if (!this.isValid(user, payload)) return false\n if (!user.hasVerifiedEmail()) {\n await user.markEmailAsVerified()\n this.events?.dispatch(new Verified(user))\n }\n return true\n }\n\n /** The HMAC binding the user id, email hash, and expiry. */\n private signature(user: VerifiableUser, expires: number): string {\n const data = `${String(user.getAuthIdentifier())}.${this.hashFor(user)}.${String(expires)}`\n return createHmac('sha256', this.secret).update(data).digest('hex')\n }\n}\n\n/** Constant-time comparison of two hex signatures. */\nfunction safeEqual(a: string, b: string): boolean {\n const bufferA = Buffer.from(a)\n const bufferB = Buffer.from(b)\n if (bufferA.length !== bufferB.length) return false\n return timingSafeEqual(bufferA, bufferB)\n}\n","/**\n * Authentication guards — the Laravel `SessionGuard` (stateful, web), `TokenGuard` (stateless,\n * API), and `RequestGuard` (closure-driven). A {@link SessionGuard} persists the authenticated\n * user's id in the session and lazily resolves the user through a {@link UserProvider}; a\n * {@link TokenGuard} authenticates each request from a bearer/query/input token with no server-side\n * state; a {@link RequestGuard} delegates to a callback over the request (the `Auth::viaRequest`\n * driver). All cache the resolved user per instance so repeated `user()` calls hit the provider\n * once, and all accept an optional {@link AuthEvents} dispatcher that fires the Laravel auth events\n * at the equivalent moments (zero overhead when unset).\n */\nimport { randomBytes } from 'node:crypto'\n\nimport { Request, Response as HttpResponse } from '@plinthjs/http'\n\nimport {\n Attempting,\n Authenticated,\n CurrentDeviceLogout,\n Failed,\n Login,\n Logout,\n OtherDeviceLogout,\n Validated,\n} from './events'\n\nimport type {\n AuthEvents,\n Authenticatable,\n Credentials,\n Guard,\n Rememberable,\n StatefulGuard,\n UserProvider,\n} from './contracts'\nimport type { Session } from '@plinthjs/session'\n\n/** Default session key holding the authenticated user's identifier. */\nconst SESSION_KEY = 'auth.id'\n\n/** Default request field/query key holding an API token. */\nconst TOKEN_KEY = 'api_token'\n\n/**\n * Session key holding the hash of the authenticated user's password — the Laravel\n * `AuthenticateSession` mechanism. The session middleware compares it against the user's current\n * hash each request, so {@link SessionGuard.logoutOtherDevices} (which re-hashes the password)\n * invalidates every other session while this one is kept in step.\n */\nexport const PASSWORD_HASH_SESSION_KEY = 'auth.password_hash'\n\n/** Default \"remember me\" cookie lifetime in minutes (400 days) — Laravel's `$rememberDuration`. */\nconst DEFAULT_REMEMBER_DURATION = 576_000\n\n/** An `attemptWhen` callback — runs after credential validation; all must return `true` to log in. */\nexport type AttemptCallback = (\n user: Authenticatable,\n guard: SessionGuard,\n) => boolean | Promise<boolean>\n\n/** Options for {@link SessionGuard}. */\nexport interface SessionGuardOptions {\n /** Guard name carried on dispatched events. Default `'web'`. */\n name?: string\n /** The current request — required only for the HTTP Basic helpers. */\n request?: Request\n /** Optional event dispatcher; when unset no events are dispatched. */\n events?: AuthEvents\n}\n\n/** Session-backed, stateful guard. The Laravel `SessionGuard` equivalent. */\nexport class SessionGuard implements StatefulGuard {\n private cachedUser: Authenticatable | null = null\n private resolved = false\n private lastAttempted: Authenticatable | null = null\n private viaRememberFlag = false\n private rememberDuration = DEFAULT_REMEMBER_DURATION\n private request: Request | undefined\n private readonly name: string\n private readonly events: AuthEvents | undefined\n\n constructor(\n private readonly provider: UserProvider,\n private readonly session: Session,\n private readonly key: string = SESSION_KEY,\n options: SessionGuardOptions = {},\n ) {\n this.name = options.name ?? 'web'\n this.request = options.request\n this.events = options.events\n }\n\n async user(): Promise<Authenticatable | null> {\n if (this.resolved) return this.cachedUser\n const id = this.session.get<string | number>(this.key)\n this.cachedUser = id === null ? null : await this.provider.retrieveById(id)\n this.resolved = true\n return this.cachedUser\n }\n\n async check(): Promise<boolean> {\n return (await this.user()) !== null\n }\n\n async guest(): Promise<boolean> {\n return !(await this.check())\n }\n\n async id(): Promise<string | number | null> {\n const user = await this.user()\n return user === null ? null : user.getAuthIdentifier()\n }\n\n async validate(credentials: Credentials): Promise<boolean> {\n const user = await this.provider.retrieveByCredentials(credentials)\n this.lastAttempted = user\n if (user === null) return false\n return this.hasValidCredentials(user, credentials)\n }\n\n async attempt(credentials: Credentials): Promise<boolean> {\n return this.attemptWhen(credentials)\n }\n\n /**\n * Attempt to authenticate with additional callbacks — the Laravel `attemptWhen`. The callbacks\n * run after the credentials validate, receiving the user and this guard; every one must return\n * `true` (a falsy result fails the attempt without logging the user in).\n */\n async attemptWhen(\n credentials: Credentials,\n callbacks: AttemptCallback | readonly AttemptCallback[] = [],\n ): Promise<boolean> {\n this.events?.dispatch(new Attempting(this.name, credentials))\n const user = await this.provider.retrieveByCredentials(credentials)\n this.lastAttempted = user\n if (\n user !== null &&\n (await this.hasValidCredentials(user, credentials)) &&\n (await this.shouldLogin(callbacks, user))\n ) {\n await this.provider.rehashPasswordIfRequired?.(user, credentials)\n this.login(user)\n return true\n }\n this.events?.dispatch(new Failed(this.name, user, credentials))\n return false\n }\n\n async once(credentials: Credentials): Promise<boolean> {\n this.events?.dispatch(new Attempting(this.name, credentials))\n const user = await this.provider.retrieveByCredentials(credentials)\n this.lastAttempted = user\n if (user !== null && (await this.hasValidCredentials(user, credentials))) {\n this.setUser(user)\n return true\n }\n return false\n }\n\n login(user: Authenticatable): void {\n this.updateSession(user)\n this.events?.dispatch(new Login(this.name, user, false))\n this.setUser(user)\n }\n\n async loginUsingId(id: string | number): Promise<Authenticatable | null> {\n const user = await this.provider.retrieveById(id)\n if (user !== null) this.login(user)\n return user\n }\n\n /**\n * Log the current user out, cycling the remember token so every recaller dies — the Laravel\n * `logout`. The session keys are cleared synchronously; the returned promise resolves once the\n * token has been cycled through the provider and the `Logout` event dispatched.\n */\n logout(): Promise<void> {\n return this.performLogout(true)\n }\n\n /**\n * Log the current user out on this device only — the Laravel `logoutCurrentDevice`. Unlike\n * {@link SessionGuard.logout} the remember token is *not* cycled, so other remembered devices\n * stay logged in. Dispatches `CurrentDeviceLogout`.\n */\n logoutCurrentDevice(): Promise<void> {\n return this.performLogout(false)\n }\n\n /**\n * Invalidate the user's sessions on every other device — the Laravel `logoutOtherDevices`.\n * Validates `password` against the current user (throwing when it does not match), then:\n *\n * - force re-hashes the password through {@link UserProvider.rehashPasswordIfRequired} (when the\n * provider supports it) and refreshes this session's stored password hash, so any session\n * checked by `authenticateSession` whose stored hash is now stale is logged out — the same\n * session-password-hash mechanism Laravel's `AuthenticateSession` middleware uses; and\n * - cycles the remember token, killing every previously issued recaller cookie.\n *\n * Returns the fresh recaller value for *this* device (the Laravel `queueRecallerCookie`\n * re-issue), or `null` when nobody is authenticated.\n */\n async logoutOtherDevices(password: string): Promise<string | null> {\n const user = await this.user()\n if (user === null) return null\n if (!(await this.provider.validateCredentials(user, { password }))) {\n throw new Error('The given password does not match the current password.')\n }\n await this.provider.rehashPasswordIfRequired?.(user, { password }, true)\n this.session.put(PASSWORD_HASH_SESSION_KEY, user.getAuthPassword())\n const recaller = await this.remember(user)\n this.events?.dispatch(new OtherDeviceLogout(this.name, user))\n return recaller\n }\n\n setUser(user: Authenticatable): void {\n this.cachedUser = user\n this.resolved = true\n this.events?.dispatch(new Authenticated(this.name, user))\n }\n\n /** Set the current request (used by the HTTP Basic helpers). The `setRequest` equivalent. */\n setRequest(request: Request): this {\n this.request = request\n return this\n }\n\n /** The last user a credential attempt resolved, or `null`. The `getLastAttempted` equivalent. */\n getLastAttempted(): Authenticatable | null {\n return this.lastAttempted\n }\n\n /** Whether the current user was authenticated via a remember-me recaller. The `viaRemember` equivalent. */\n viaRemember(): boolean {\n return this.viaRememberFlag\n }\n\n /**\n * Set how long (in minutes) issued recaller cookies should live — the `setRememberDuration`\n * equivalent. The guard does not write cookies itself; read it back via\n * {@link SessionGuard.getRememberDuration} when turning a recaller value into a cookie.\n */\n setRememberDuration(minutes: number): this {\n this.rememberDuration = minutes\n return this\n }\n\n /** The \"remember me\" cookie lifetime in minutes. The `getRememberDuration` equivalent. */\n getRememberDuration(): number {\n return this.rememberDuration\n }\n\n /**\n * Attempt HTTP Basic authentication, logging the user in for the session — the Laravel `basic`.\n * Resolves to `undefined` when already authenticated or when the `Authorization: Basic` header\n * validates; otherwise resolves to a `401` challenge response (`WWW-Authenticate: Basic`).\n * Requires the request (constructor option or {@link SessionGuard.setRequest}).\n */\n async basic(field = 'email'): Promise<HttpResponse | undefined> {\n if (await this.check()) return undefined\n const credentials = this.basicCredentialsFromRequest(field)\n if (credentials !== null && (await this.attempt(credentials))) return undefined\n return failedBasicResponse()\n }\n\n /**\n * Perform a stateless HTTP Basic attempt (no session persistence) — the Laravel `onceBasic`.\n * Resolves to `undefined` on success, or the `401` challenge response on failure.\n */\n async onceBasic(field = 'email'): Promise<HttpResponse | undefined> {\n const credentials = this.basicCredentialsFromRequest(field)\n if (credentials !== null && (await this.once(credentials))) return undefined\n return failedBasicResponse()\n }\n\n /**\n * Issue a fresh remember-me token for `user`, persist it through the provider, and return the\n * recaller value (`id|token`) to store in a long-lived cookie. The Laravel \"remember me\" persist.\n */\n async remember(user: Authenticatable): Promise<string> {\n const token = randomBytes(20).toString('hex')\n await this.provider.updateRememberToken(user, token)\n return recallerValue(user.getAuthIdentifier(), token)\n }\n\n /**\n * Authenticate from a recaller cookie value (`id|token`), logging the user in for the session on a\n * constant-time token match (the Laravel `viaRemember` path). Returns the user, or `null`.\n */\n async loginUsingRecaller(value: string): Promise<Authenticatable | null> {\n const recaller = parseRecaller(value)\n if (recaller === null) return null\n const user = await this.provider.retrieveByToken(recaller.id, recaller.token)\n if (user !== null) {\n this.viaRememberFlag = true\n this.updateSession(user)\n this.events?.dispatch(new Login(this.name, user, true))\n this.setUser(user)\n }\n return user\n }\n\n /** Persist the user's id and current password hash into the session. */\n private updateSession(user: Authenticatable): void {\n this.session.put(this.key, user.getAuthIdentifier())\n this.session.put(PASSWORD_HASH_SESSION_KEY, user.getAuthPassword())\n }\n\n /** Whether `credentials` validate against `user`, dispatching `Validated` when they do. */\n private async hasValidCredentials(\n user: Authenticatable,\n credentials: Credentials,\n ): Promise<boolean> {\n const valid = await this.provider.validateCredentials(user, credentials)\n if (valid) this.events?.dispatch(new Validated(this.name, user))\n return valid\n }\n\n /** Run the `attemptWhen` callbacks; every one must return `true` for the login to proceed. */\n private async shouldLogin(\n callbacks: AttemptCallback | readonly AttemptCallback[],\n user: Authenticatable,\n ): Promise<boolean> {\n const list = typeof callbacks === 'function' ? [callbacks] : callbacks\n for (const callback of list) {\n if (!(await callback(user, this))) return false\n }\n return true\n }\n\n /** Clear the session synchronously, then finish teardown (token cycling + event) async. */\n private performLogout(cycleToken: boolean): Promise<void> {\n const known = this.resolved ? this.cachedUser : null\n const id = this.session.get<string | number>(this.key)\n this.session.forget(this.key)\n this.session.forget(PASSWORD_HASH_SESSION_KEY)\n this.cachedUser = null\n this.resolved = true\n this.viaRememberFlag = false\n return this.finishLogout(known, id, cycleToken)\n }\n\n /** Resolve the user that was logged out, cycle their remember token, and dispatch the event. */\n private async finishLogout(\n known: Authenticatable | null,\n id: string | number | null,\n cycleToken: boolean,\n ): Promise<void> {\n const user = known ?? (id === null ? null : await this.provider.retrieveById(id))\n if (user === null) return\n if (cycleToken && hasRememberToken(user)) {\n await this.provider.updateRememberToken(user, randomBytes(20).toString('hex'))\n }\n this.events?.dispatch(\n cycleToken ? new Logout(this.name, user) : new CurrentDeviceLogout(this.name, user),\n )\n }\n\n /** Parse `Authorization: Basic …` from the request into `{ [field], password }`, or `null`. */\n private basicCredentialsFromRequest(field: string): Credentials | null {\n if (this.request === undefined) return null\n const header = this.request.header('authorization')\n if (!header?.toLowerCase().startsWith('basic ')) return null\n const decoded = Buffer.from(header.slice(6).trim(), 'base64').toString('utf8')\n const separator = decoded.indexOf(':')\n if (separator === -1) return null\n return { [field]: decoded.slice(0, separator), password: decoded.slice(separator + 1) }\n }\n}\n\n/** The `401` challenge sent when HTTP Basic authentication fails (Laravel's `UnauthorizedHttpException`). */\nfunction failedBasicResponse(): HttpResponse {\n return HttpResponse.make('Invalid Basic credentials.', 401).withHeaders({\n 'WWW-Authenticate': 'Basic',\n })\n}\n\n/** Whether `user` exposes a non-empty remember-me token. */\nfunction hasRememberToken(user: Authenticatable): boolean {\n if (!('getRememberToken' in user)) return false\n const token = (user as Authenticatable & Rememberable).getRememberToken()\n return typeof token === 'string' && token.length > 0\n}\n\n/** Encode a recaller cookie value from a user id and remember-me token. */\nfunction recallerValue(id: string | number, token: string): string {\n return `${String(id)}|${token}`\n}\n\n/** Parse a recaller cookie value (`id|token`) into its parts, or `null` if malformed. */\nfunction parseRecaller(value: string): { id: string; token: string } | null {\n const separator = value.indexOf('|')\n if (separator <= 0) return null\n const token = value.slice(separator + 1)\n if (token.length === 0) return null\n return { id: value.slice(0, separator), token }\n}\n\n/** Options for {@link TokenGuard}. */\nexport interface TokenGuardOptions {\n /** Guard name carried on dispatched events. Default `'api'`. */\n name?: string\n /** Optional event dispatcher; when unset no events are dispatched. */\n events?: AuthEvents\n}\n\n/** Stateless token guard. The Laravel `TokenGuard` equivalent. */\nexport class TokenGuard implements Guard {\n private cachedUser: Authenticatable | null = null\n private resolved = false\n private readonly name: string\n private readonly events: AuthEvents | undefined\n\n constructor(\n private readonly provider: UserProvider,\n private readonly request: Request,\n private readonly inputKey: string = TOKEN_KEY,\n options: TokenGuardOptions = {},\n ) {\n this.name = options.name ?? 'api'\n this.events = options.events\n }\n\n async user(): Promise<Authenticatable | null> {\n if (this.resolved) return this.cachedUser\n const token = this.tokenForRequest()\n this.cachedUser =\n token === undefined\n ? null\n : await this.provider.retrieveByCredentials({ [this.inputKey]: token })\n this.resolved = true\n if (this.cachedUser !== null) {\n this.events?.dispatch(new Authenticated(this.name, this.cachedUser))\n }\n return this.cachedUser\n }\n\n async check(): Promise<boolean> {\n return (await this.user()) !== null\n }\n\n async guest(): Promise<boolean> {\n return !(await this.check())\n }\n\n async id(): Promise<string | number | null> {\n const user = await this.user()\n return user === null ? null : user.getAuthIdentifier()\n }\n\n async validate(credentials: Credentials): Promise<boolean> {\n const user = await this.provider.retrieveByCredentials(credentials)\n if (user === null) return false\n return this.provider.validateCredentials(user, credentials)\n }\n\n setUser(user: Authenticatable): void {\n this.cachedUser = user\n this.resolved = true\n this.events?.dispatch(new Authenticated(this.name, user))\n }\n\n /** Read the API token from the bearer header, then the query string, then the input bag. */\n private tokenForRequest(): string | undefined {\n const bearer = this.request.bearerToken()\n if (bearer !== undefined) return bearer\n const query = this.request.query(this.inputKey)\n if (typeof query === 'string' && query.length > 0) return query\n const input = this.request.input<string>(this.inputKey)\n return typeof input === 'string' && input.length > 0 ? input : undefined\n }\n}\n\n/**\n * The user-resolver callback behind a {@link RequestGuard} — the closure passed to\n * `Auth::viaRequest`. Receives the request (and the provider, when one was registered) and returns\n * the authenticated user, or `null`/`undefined` for a guest.\n */\nexport type RequestUserResolver = (\n request: Request,\n provider?: UserProvider,\n) => Authenticatable | null | undefined | Promise<Authenticatable | null | undefined>\n\n/**\n * Closure-driven guard over the current request — the Laravel `RequestGuard` (the engine behind\n * `Auth::viaRequest`). Resolves the user once per instance through the callback.\n */\nexport class RequestGuard implements Guard {\n private cachedUser: Authenticatable | null = null\n private resolved = false\n private request: Request | undefined\n\n constructor(\n private readonly callback: RequestUserResolver,\n request?: Request,\n private readonly provider?: UserProvider | undefined,\n ) {\n this.request = request\n }\n\n async user(): Promise<Authenticatable | null> {\n if (this.resolved) return this.cachedUser\n this.cachedUser =\n this.request === undefined\n ? null\n : ((await this.callback(this.request, this.provider)) ?? null)\n this.resolved = true\n return this.cachedUser\n }\n\n async check(): Promise<boolean> {\n return (await this.user()) !== null\n }\n\n async guest(): Promise<boolean> {\n return !(await this.check())\n }\n\n async id(): Promise<string | number | null> {\n const user = await this.user()\n return user === null ? null : user.getAuthIdentifier()\n }\n\n /**\n * Whether the callback resolves a user for `credentials['request']` — the Laravel\n * `RequestGuard::validate`, which runs the resolver against the given request.\n */\n async validate(credentials: Credentials): Promise<boolean> {\n const request = credentials['request']\n if (!(request instanceof Request)) return false\n return ((await this.callback(request, this.provider)) ?? null) !== null\n }\n\n setUser(user: Authenticatable): void {\n this.cachedUser = user\n this.resolved = true\n }\n\n /** Swap the request and reset the cached user. The `setRequest` equivalent. */\n setRequest(request: Request): this {\n this.request = request\n this.cachedUser = null\n this.resolved = false\n return this\n }\n}\n","/**\n * `AuthManager` — resolves named authentication guards, the Laravel `Illuminate\\Auth\\AuthManager` /\n * `Auth` facade equivalent. Guards are registered as factories (so request-scoped guards are built\n * fresh each time) and resolved by name, falling back to the configured default. Factories may\n * accept the current request, which {@link AuthManager.guard} forwards — the seam\n * {@link AuthManager.viaRequest} uses to register closure-driven {@link RequestGuard} drivers.\n */\nimport { RequestGuard } from './guards'\n\nimport type { Guard, UserProvider } from './contracts'\nimport type { RequestUserResolver } from './guards'\nimport type { Request } from '@plinthjs/http'\n\n/**\n * Builds a guard on demand. Request-scoped guards capture per-request state in the closure, or read\n * the request {@link AuthManager.guard} forwards (factories registered before this parameter\n * existed simply ignore it).\n */\nexport type GuardFactory = (request?: Request) => Guard\n\nexport class AuthManager {\n private readonly guards = new Map<string, GuardFactory>()\n\n constructor(private defaultGuard = 'web') {}\n\n /** Register a guard factory under `name`. The `Auth::extend()` equivalent. */\n extend(name: string, factory: GuardFactory): this {\n this.guards.set(name, factory)\n return this\n }\n\n /**\n * Register a closure-driven guard under `name` — the `Auth::viaRequest()` equivalent. The\n * callback receives the request (and `provider`, when given) and returns the authenticated user\n * or `null`; the manager builds a {@link RequestGuard} around it on every resolve.\n */\n viaRequest(name: string, callback: RequestUserResolver, provider?: UserProvider): this {\n return this.extend(name, (request?: Request) => new RequestGuard(callback, request, provider))\n }\n\n /**\n * Resolve a guard by name (or the default), forwarding `request` to the factory so\n * request-scoped guards (e.g. {@link AuthManager.viaRequest}) can read it. Throws if the guard is\n * not registered.\n */\n guard(name?: string, request?: Request): Guard {\n const resolved = name ?? this.defaultGuard\n const factory = this.guards.get(resolved)\n if (factory === undefined) {\n throw new Error(`Auth guard [${resolved}] is not defined.`)\n }\n return factory(request)\n }\n\n /** Change the default guard name. The `Auth::shouldUse()` equivalent. */\n setDefaultGuard(name: string): this {\n this.defaultGuard = name\n return this\n }\n\n /** The current default guard name. */\n getDefaultGuard(): string {\n return this.defaultGuard\n }\n}\n","/**\n * Authentication middleware bridging `@plinthjs/auth` to `@plinthjs/http` — the Laravel `Authenticate`\n * (`auth`) middleware family. {@link authenticateSession} resolves the user from the session\n * (requires the session middleware) and {@link authenticateToken} from a request token; both attach\n * the user to the request (readable via {@link getUser}) or render a `401` via\n * {@link AuthenticationError}. {@link authenticateSession} also keeps a hash of the user's password\n * in the session (the Laravel `AuthenticateSession` middleware) so sessions die when the password\n * changes — e.g. after `SessionGuard.logoutOtherDevices`. {@link redirectIfAuthenticated} is the\n * `guest` middleware, and {@link requirePassword} / {@link confirmPassword} implement the Laravel\n * `password.confirm` flow over an `auth.password_confirmed_at` session timestamp.\n */\nimport { HttpException, Response } from '@plinthjs/http'\nimport { getSession } from '@plinthjs/session'\n\nimport { PASSWORD_HASH_SESSION_KEY, SessionGuard, TokenGuard } from './guards'\n\nimport type { Authenticatable, Credentials, UserProvider } from './contracts'\nimport type { Middleware, Request } from '@plinthjs/http'\nimport type { Session } from '@plinthjs/session'\n\n/** Request-attribute key under which the authenticated user is stored. */\nconst USER_ATTRIBUTE = 'mason.user'\n\n/** Session key holding the epoch-seconds timestamp of the last password confirmation. */\nexport const PASSWORD_CONFIRMED_AT_SESSION_KEY = 'auth.password_confirmed_at'\n\n/** Default password-confirmation window in seconds — Laravel's `auth.password_timeout`. */\nconst DEFAULT_PASSWORD_TIMEOUT_SECONDS = 10_800\n\n/** Raised when authentication is required but the request is unauthenticated (renders `401`). */\nexport class AuthenticationError extends HttpException {\n constructor(message = 'Unauthenticated.') {\n super(401, message)\n this.name = 'AuthenticationError'\n }\n}\n\n/** The authenticated user attached by an authenticate middleware, or `undefined`. */\nexport function getUser(req: Request): Authenticatable | undefined {\n return req.attribute<Authenticatable>(USER_ATTRIBUTE)\n}\n\n/**\n * Authenticate via the session — the web `auth` middleware. Requires the session middleware to have\n * run; resolves the user from the session id and attaches it, or throws {@link AuthenticationError}.\n * Also enforces the Laravel `AuthenticateSession` password-hash check: the user's password hash is\n * stored in the session on first sight and compared on every request, so a password change (e.g.\n * `SessionGuard.logoutOtherDevices`) logs every stale session out.\n */\nexport function authenticateSession(provider: UserProvider): Middleware {\n return async (req, next) => {\n const session = requireSession(req)\n const guard = new SessionGuard(provider, session)\n const user = await guard.user()\n if (user === null) throw new AuthenticationError()\n const storedHash = session.get<string>(PASSWORD_HASH_SESSION_KEY)\n if (storedHash !== null && storedHash !== user.getAuthPassword()) {\n // The password changed since this session authenticated — invalidate it (without cycling\n // the remember token, which the password-changing device already re-issued).\n await guard.logoutCurrentDevice()\n throw new AuthenticationError()\n }\n if (storedHash === null) session.put(PASSWORD_HASH_SESSION_KEY, user.getAuthPassword())\n return next(req.withAttribute(USER_ATTRIBUTE, user))\n }\n}\n\n/**\n * Authenticate via a request token — the stateless `auth:api` middleware. Resolves the user from a\n * bearer/query/input token and attaches it, or throws {@link AuthenticationError}.\n */\nexport function authenticateToken(provider: UserProvider, inputKey?: string): Middleware {\n return async (req, next) => {\n const guard =\n inputKey === undefined\n ? new TokenGuard(provider, req)\n : new TokenGuard(provider, req, inputKey)\n const user = await guard.user()\n if (user === null) throw new AuthenticationError()\n return next(req.withAttribute(USER_ATTRIBUTE, user))\n }\n}\n\n/**\n * Redirect authenticated users away (e.g. from login/register pages) — the Laravel\n * `RedirectIfAuthenticated` (`guest`) middleware. Guests (and requests without a session) pass\n * through; an authenticated session is redirected to `redirectTo`.\n */\nexport function redirectIfAuthenticated(provider: UserProvider, redirectTo = '/home'): Middleware {\n return async (req, next) => {\n const session = getSession(req)\n if (session === undefined) return next(req)\n const user = await new SessionGuard(provider, session).user()\n return user === null ? next(req) : Response.redirectTo(redirectTo)\n }\n}\n\n/**\n * Require a recent password confirmation — the Laravel `RequirePassword` (`password.confirm`)\n * middleware. Passes when the session's `auth.password_confirmed_at` timestamp is within\n * `passwordTimeoutSeconds`; otherwise redirects to `redirectTo` (or renders `423 Locked` for JSON\n * clients). Stamp the timestamp via {@link confirmPassword} after re-validating the password.\n */\nexport function requirePassword(\n redirectTo = '/confirm-password',\n passwordTimeoutSeconds: number = DEFAULT_PASSWORD_TIMEOUT_SECONDS,\n now: () => Date = (): Date => new Date(),\n): Middleware {\n return async (req, next) => {\n const session = requireSession(req)\n const confirmedAt = session.get<number>(PASSWORD_CONFIRMED_AT_SESSION_KEY)\n const fresh =\n typeof confirmedAt === 'number' &&\n now().getTime() / 1000 - confirmedAt < passwordTimeoutSeconds\n if (fresh) return next(req)\n if (req.wantsJson()) {\n return Response.json({ message: 'Password confirmation required.' }, 423)\n }\n return Response.redirectTo(redirectTo)\n }\n}\n\n/**\n * Re-validate the user's password and stamp the session's confirmation timestamp — what Laravel's\n * `ConfirmablePasswordController` does for the `password.confirm` flow. Returns `false` (leaving\n * the session untouched) when the password does not match.\n */\nexport async function confirmPassword(\n provider: UserProvider,\n session: Session,\n user: Authenticatable,\n password: string,\n now: () => Date = (): Date => new Date(),\n): Promise<boolean> {\n const credentials: Credentials = { password }\n if (!(await provider.validateCredentials(user, credentials))) return false\n session.put(PASSWORD_CONFIRMED_AT_SESSION_KEY, Math.floor(now().getTime() / 1000))\n return true\n}\n\n/** The request's session, or a `500` explaining that the session middleware must run first. */\nfunction requireSession(req: Request): Session {\n const session = getSession(req)\n if (session === undefined) {\n throw new HttpException(\n 500,\n 'Session authentication requires the session middleware to run first.',\n )\n }\n return session\n}\n","/**\n * Password reset — the Laravel `Illuminate\\Auth\\Passwords` layer. A {@link PasswordBroker} drives the\n * \"forgot password\" flow: find the user, throttle re-sends, mint a single-use time-limited token,\n * hand it to a sender callback, and later verify it before letting a callback persist the new\n * password. Tokens live behind a {@link TokenRepository} seam; {@link ArrayTokenRepository} is the\n * in-memory implementation (token hashes only, an injected clock for expiry/throttle, the\n * `@plinthjs/encryption` {@link Hasher} for hashing). The broker is transport-agnostic — the caller\n * supplies how the link is delivered and how the password is saved.\n */\nimport { randomBytes } from 'node:crypto'\n\nimport { PasswordReset } from './events'\n\nimport type { AuthEvents, Authenticatable, Credentials, UserProvider } from './contracts'\nimport type { Hasher } from '@plinthjs/encryption'\n\n/** The outcome of a broker operation — the Laravel `Password::*` status constants. */\nexport const PasswordStatus = {\n ResetLinkSent: 'passwords.sent',\n PasswordReset: 'passwords.reset',\n InvalidUser: 'passwords.user',\n InvalidToken: 'passwords.token',\n InvalidPassword: 'passwords.password',\n ResetThrottled: 'passwords.throttled',\n} as const\n\n/** A password-broker status value. */\nexport type PasswordStatus = (typeof PasswordStatus)[keyof typeof PasswordStatus]\n\n/** Stores, verifies, and expires password-reset tokens. The Laravel `TokenRepositoryInterface`. */\nexport interface TokenRepository {\n /** Mint, store, and return a fresh plaintext token for `user` (only its hash is kept). */\n create(user: Authenticatable): Promise<string>\n /** Whether `token` matches a stored, non-expired token for `user`. */\n exists(user: Authenticatable, token: string): Promise<boolean>\n /** Whether `user` was issued a token within the throttle window (for re-send throttling). */\n recentlyCreatedToken(user: Authenticatable): Promise<boolean>\n /** Forget `user`'s token (after a successful reset). */\n delete(user: Authenticatable): Promise<void>\n /** Purge every expired token. */\n deleteExpired(): Promise<void>\n}\n\ninterface StoredToken {\n hashed: string\n createdAt: number\n}\n\n/** Options for {@link ArrayTokenRepository}. */\nexport interface ArrayTokenRepositoryOptions {\n /** Hasher used to store token hashes (never the plaintext). */\n hasher: Hasher\n /** Token lifetime in minutes (the Laravel `expire`). Default `60`. */\n expireMinutes?: number\n /** Re-send throttle window in seconds (the Laravel `throttle`). Default `60`. */\n throttleSeconds?: number\n /** Injected clock for deterministic expiry/throttle. Default `() => new Date()`. */\n now?: () => Date\n /** Plaintext token generator. Default 40 random hex chars; tests may inject a fixed value. */\n createToken?: () => string\n}\n\n/** In-memory {@link TokenRepository}, keyed by the user's auth identifier — ideal for tests/small apps. */\nexport class ArrayTokenRepository implements TokenRepository {\n private readonly store = new Map<string | number, StoredToken>()\n private readonly hasher: Hasher\n private readonly expireMinutes: number\n private readonly throttleSeconds: number\n private readonly now: () => Date\n private readonly makeToken: () => string\n\n constructor(options: ArrayTokenRepositoryOptions) {\n this.hasher = options.hasher\n this.expireMinutes = options.expireMinutes ?? 60\n this.throttleSeconds = options.throttleSeconds ?? 60\n this.now = options.now ?? ((): Date => new Date())\n this.makeToken = options.createToken ?? ((): string => randomBytes(20).toString('hex'))\n }\n\n async create(user: Authenticatable): Promise<string> {\n const token = this.makeToken()\n this.store.set(user.getAuthIdentifier(), {\n hashed: this.hasher.make(token),\n createdAt: this.now().getTime(),\n })\n return token\n }\n\n async exists(user: Authenticatable, token: string): Promise<boolean> {\n const record = this.store.get(user.getAuthIdentifier())\n if (record === undefined || this.expired(record)) return false\n return this.hasher.check(token, record.hashed)\n }\n\n async recentlyCreatedToken(user: Authenticatable): Promise<boolean> {\n const record = this.store.get(user.getAuthIdentifier())\n if (record === undefined) return false\n return (this.now().getTime() - record.createdAt) / 1000 < this.throttleSeconds\n }\n\n async delete(user: Authenticatable): Promise<void> {\n this.store.delete(user.getAuthIdentifier())\n }\n\n async deleteExpired(): Promise<void> {\n for (const [key, record] of this.store) {\n if (this.expired(record)) this.store.delete(key)\n }\n }\n\n private expired(record: StoredToken): boolean {\n return (this.now().getTime() - record.createdAt) / 60_000 >= this.expireMinutes\n }\n}\n\n/** Credentials for a reset: the lookup fields plus the `token` and new `password`. */\nexport type ResetCredentials = Credentials & { token: string; password: string }\n\n/** A callback that delivers the reset link/token to the user (email, SMS, …). */\nexport type ResetLinkSender = (user: Authenticatable, token: string) => void | Promise<void>\n\n/** A callback that persists the user's new password. */\nexport type PasswordResetCallback = (\n user: Authenticatable,\n password: string,\n) => void | Promise<void>\n\n/** Drives the password-reset flow over a {@link UserProvider} and {@link TokenRepository}. */\nexport class PasswordBroker {\n private readonly events: AuthEvents | undefined\n\n constructor(\n private readonly users: UserProvider,\n private readonly tokens: TokenRepository,\n events?: AuthEvents,\n ) {\n this.events = events\n }\n\n /**\n * Send a reset link: resolve the user from `credentials`, throttle repeat requests, mint a token,\n * and hand it to `send`. Returns {@link PasswordStatus.ResetLinkSent} on success.\n */\n async sendResetLink(credentials: Credentials, send: ResetLinkSender): Promise<PasswordStatus> {\n const user = await this.users.retrieveByCredentials(credentials)\n if (user === null) return PasswordStatus.InvalidUser\n if (await this.tokens.recentlyCreatedToken(user)) return PasswordStatus.ResetThrottled\n const token = await this.tokens.create(user)\n await send(user, token)\n return PasswordStatus.ResetLinkSent\n }\n\n /**\n * Reset a password: resolve the user, require a non-empty password, verify the token, then run\n * `reset` to persist and delete the token. Returns {@link PasswordStatus.PasswordReset} on success.\n */\n async reset(\n credentials: ResetCredentials,\n reset: PasswordResetCallback,\n ): Promise<PasswordStatus> {\n const user = await this.users.retrieveByCredentials(this.lookupOnly(credentials))\n if (user === null) return PasswordStatus.InvalidUser\n if (typeof credentials.password !== 'string' || credentials.password === '') {\n return PasswordStatus.InvalidPassword\n }\n if (!(await this.tokens.exists(user, credentials.token))) return PasswordStatus.InvalidToken\n await reset(user, credentials.password)\n await this.tokens.delete(user)\n this.events?.dispatch(new PasswordReset(user))\n return PasswordStatus.PasswordReset\n }\n\n /** The user-lookup credentials, with `token`/`password` removed so they don't act as match fields. */\n private lookupOnly(credentials: Credentials): Credentials {\n const lookup: Credentials = {}\n for (const [key, value] of Object.entries(credentials)) {\n if (key !== 'token' && key !== 'password') lookup[key] = value\n }\n return lookup\n }\n}\n","/**\n * User providers — the Laravel `Illuminate\\Auth\\GenericUser` and array/database providers.\n * {@link GenericUser} is a record-backed {@link Authenticatable}; {@link ArrayUserProvider} resolves\n * users from an in-memory list, validating passwords through an injected {@link Hasher}. A\n * database/Eloquent provider implements the same {@link UserProvider} seam against `@plinthjs/orm`.\n */\nimport { timingSafeEqual } from 'node:crypto'\n\nimport type {\n Authenticatable,\n Credentials,\n PasswordUpdatable,\n Rememberable,\n UserProvider,\n} from './contracts'\nimport type { Hasher } from '@plinthjs/encryption'\n\n/** Default column holding a user's remember-me token. */\nconst REMEMBER_TOKEN = 'remember_token'\n\n/** A simple record-backed {@link Authenticatable}. The Laravel `GenericUser` equivalent. */\nexport class GenericUser implements Authenticatable, Rememberable, PasswordUpdatable {\n constructor(\n readonly attributes: Record<string, unknown>,\n private readonly identifierName = 'id',\n private readonly passwordName = 'password',\n ) {}\n\n getAuthIdentifier(): string | number {\n const id = this.attributes[this.identifierName]\n if (typeof id === 'number' || typeof id === 'string') return id\n return ''\n }\n\n getAuthIdentifierName(): string {\n return this.identifierName\n }\n\n getAuthPassword(): string {\n const password = this.attributes[this.passwordName]\n return typeof password === 'string' ? password : ''\n }\n\n setAuthPassword(hashed: string): void {\n this.attributes[this.passwordName] = hashed\n }\n\n getRememberToken(): string | null {\n const token = this.attributes[REMEMBER_TOKEN]\n return typeof token === 'string' ? token : null\n }\n\n setRememberToken(token: string): void {\n this.attributes[REMEMBER_TOKEN] = token\n }\n\n /** Read an arbitrary attribute, used by providers to match credentials. */\n getAttribute(key: string): unknown {\n return this.attributes[key]\n }\n}\n\n/** An in-memory {@link UserProvider} over a fixed list of users — ideal for tests and small apps. */\nexport class ArrayUserProvider implements UserProvider {\n constructor(\n private readonly users: GenericUser[],\n private readonly hasher: Hasher,\n ) {}\n\n retrieveById(identifier: string | number): Promise<Authenticatable | null> {\n const user = this.users.find((candidate) => candidate.getAuthIdentifier() === identifier)\n return Promise.resolve(user ?? null)\n }\n\n retrieveByToken(identifier: string | number, token: string): Promise<Authenticatable | null> {\n // Recaller ids arrive as cookie strings, so match by string form (tolerant of number ids).\n const user = this.users.find(\n (candidate) => String(candidate.getAuthIdentifier()) === String(identifier),\n )\n const stored = user?.getRememberToken()\n if (user === undefined || stored === null || stored === undefined || stored.length === 0) {\n return Promise.resolve(null)\n }\n return Promise.resolve(safeEqual(stored, token) ? user : null)\n }\n\n updateRememberToken(user: Authenticatable, token: string): Promise<void> {\n if (isRememberable(user)) user.setRememberToken(token)\n return Promise.resolve()\n }\n\n retrieveByCredentials(credentials: Credentials): Promise<Authenticatable | null> {\n const keys = Object.keys(credentials).filter((key) => !key.includes('password'))\n if (keys.length === 0) return Promise.resolve(null)\n const user = this.users.find((candidate) =>\n keys.every((key) => candidate.getAttribute(key) === credentials[key]),\n )\n return Promise.resolve(user ?? null)\n }\n\n validateCredentials(user: Authenticatable, credentials: Credentials): Promise<boolean> {\n const password = credentials['password']\n if (typeof password !== 'string') return Promise.resolve(false)\n return Promise.resolve(this.hasher.check(password, user.getAuthPassword()))\n }\n\n /**\n * Re-hash and persist the user's password when its cost parameters no longer match the hasher's\n * (or always, when `force` is set) — the Laravel `rehashPasswordIfRequired`. Persists through the\n * {@link PasswordUpdatable} seam, mirroring how remember tokens are persisted.\n */\n rehashPasswordIfRequired(\n user: Authenticatable,\n credentials: Credentials,\n force = false,\n ): Promise<void> {\n const password = credentials['password']\n if (typeof password !== 'string') return Promise.resolve()\n if (!force && !this.hasher.needsRehash(user.getAuthPassword())) return Promise.resolve()\n if (isPasswordUpdatable(user)) user.setAuthPassword(this.hasher.make(password))\n return Promise.resolve()\n }\n}\n\n/** Whether `user` supports remember-me persistence. */\nfunction isRememberable(user: Authenticatable): user is Authenticatable & Rememberable {\n return 'setRememberToken' in user && typeof user.setRememberToken === 'function'\n}\n\n/** Whether `user` supports password-hash persistence. */\nfunction isPasswordUpdatable(user: Authenticatable): user is Authenticatable & PasswordUpdatable {\n return 'setAuthPassword' in user && typeof user.setAuthPassword === 'function'\n}\n\n/** Constant-time comparison of two remember-me tokens. */\nfunction safeEqual(a: string, b: string): boolean {\n const bufferA = Buffer.from(a)\n const bufferB = Buffer.from(b)\n if (bufferA.length !== bufferB.length) return false\n return timingSafeEqual(bufferA, bufferB)\n}\n","/**\n * @plinthjs/auth — authentication, the Laravel `Illuminate\\Auth` equivalent.\n *\n * The {@link Authenticatable} / {@link UserProvider} / {@link Guard} contracts, an in-memory\n * {@link ArrayUserProvider} over {@link GenericUser}s (passwords verified through `@plinthjs/encryption`,\n * re-hashed on login via {@link UserProvider.rehashPasswordIfRequired}), the {@link SessionGuard}\n * (stateful, web — with `attemptWhen`, HTTP Basic, remember-me, and the logout variants), the\n * {@link TokenGuard} (stateless, API), the {@link RequestGuard} behind\n * {@link AuthManager.viaRequest}, an {@link AuthManager} that resolves named guards, the Laravel\n * auth event classes dispatched through the structural {@link AuthEvents} seam, and the\n * {@link authenticateSession} / {@link authenticateToken} / {@link redirectIfAuthenticated} /\n * {@link requirePassword} HTTP middleware (with {@link getUser} to read the user off the request).\n */\n\n/** The Mason version this build of `auth` ships with. */\nexport const VERSION = '0.1.0'\n\nexport type {\n Authenticatable,\n AuthEvents,\n Credentials,\n Guard,\n PasswordUpdatable,\n Rememberable,\n StatefulGuard,\n UserProvider,\n} from './contracts'\nexport {\n EmailVerifier,\n type EmailVerifierOptions,\n type MustVerifyEmail,\n type VerifiableUser,\n type VerificationSignature,\n} from './email-verification'\nexport {\n Attempting,\n Authenticated,\n CurrentDeviceLogout,\n Failed,\n Lockout,\n Login,\n Logout,\n OtherDeviceLogout,\n PasswordReset,\n Registered,\n Validated,\n Verified,\n} from './events'\nexport {\n type AttemptCallback,\n PASSWORD_HASH_SESSION_KEY,\n RequestGuard,\n type RequestUserResolver,\n SessionGuard,\n type SessionGuardOptions,\n TokenGuard,\n type TokenGuardOptions,\n} from './guards'\nexport { AuthManager, type GuardFactory } from './manager'\nexport {\n AuthenticationError,\n authenticateSession,\n authenticateToken,\n confirmPassword,\n getUser,\n PASSWORD_CONFIRMED_AT_SESSION_KEY,\n redirectIfAuthenticated,\n requirePassword,\n} from './middleware'\nexport {\n ArrayTokenRepository,\n type ArrayTokenRepositoryOptions,\n PasswordBroker,\n type PasswordResetCallback,\n PasswordStatus,\n type ResetCredentials,\n type ResetLinkSender,\n type TokenRepository,\n} from './passwords'\nexport { ArrayUserProvider, GenericUser } from './providers'\n"]}
1
+ {"version":3,"sources":["../src/events.ts","../src/email-verification.ts","../src/guards.ts","../src/manager.ts","../src/middleware.ts","../src/passwords.ts","../src/providers.ts","../src/index.ts"],"names":["createHash","createHmac","timingSafeEqual","randomBytes","HttpResponse","Request","HttpException","session","getSession","Response","safeEqual"],"mappings":";;;;;;;;;AAaO,IAAM,aAAN,MAAiB;AAAA,EACtB,WAAA,CAEW,KAAA,EAEA,WAAA,EAEA,QAAA,GAAW,KAAA,EACpB;AALS,IAAA,IAAA,CAAA,KAAA,GAAA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iBAAA,IAAqB,IAAA,IAAQ,OAAO,IAAA,CAAK,eAAA,KAAoB,UAAA;AACtE;AAGA,SAASA,UAAAA,CAAU,GAAW,CAAA,EAAoB;AAChD,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA;AAC7B,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA;AAC7B,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,OAAA,CAAQ,MAAA,EAAQ,OAAO,KAAA;AAC9C,EAAA,OAAOR,sBAAAA,CAAgB,SAAS,OAAO,CAAA;AACzC;;;AC7HO,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["/**\n * Authentication events - the conventional API classes. Guards and brokers dispatch\n * these through the optional {@link AuthEvents} seam at the same moments conventional implementations fire them:\n * {@link Attempting} before a credential attempt, {@link Validated} once credentials check out,\n * {@link Login} + {@link Authenticated} when a user is logged in / set on the guard, {@link Failed}\n * on a bad attempt, {@link Logout} / {@link CurrentDeviceLogout} / {@link OtherDeviceLogout} on the\n * logout variants, and {@link Registered} / {@link Verified} / {@link PasswordReset} /\n * {@link Lockout} around the account lifecycle. Plain classes with readonly data - dispatchable\n * through any dispatcher that takes an object.\n */\nimport type { Authenticatable, Credentials } from './contracts'\n\n/** Fired before every credential attempt - the `Attempting` event. */\nexport class Attempting {\n constructor(\n /** The guard name the attempt runs on. */\n readonly guard: string,\n /** The credentials being attempted (includes the plaintext password - handle with care). */\n readonly credentials: Credentials,\n /** Whether the attempt asked for \"remember me\" persistence. */\n readonly remember = false,\n ) {}\n}\n\n/** Fired when credentials validate against a user - the `Validated` event. */\nexport class Validated {\n constructor(\n /** The guard name the validation ran on. */\n readonly guard: string,\n /** The user the credentials validated against. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a user is logged in for the session - the `Login` event. */\nexport class Login {\n constructor(\n /** The guard name the login happened on. */\n readonly guard: string,\n /** The user that logged in. */\n readonly user: Authenticatable,\n /** Whether the login came from a remember-me recaller. */\n readonly remember: boolean,\n ) {}\n}\n\n/** Fired whenever a user is set on a guard - the `Authenticated` event. */\nexport class Authenticated {\n constructor(\n /** The guard name the user was set on. */\n readonly guard: string,\n /** The user that is now authenticated. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a credential attempt fails - the `Failed` event. */\nexport class Failed {\n constructor(\n /** The guard name the attempt ran on. */\n readonly guard: string,\n /** The user the credentials matched, or `null` when no user was found. */\n readonly user: Authenticatable | null,\n /** The credentials that failed. */\n readonly credentials: Credentials,\n ) {}\n}\n\n/** Fired when the user logs out (remember token cycled) - the `Logout` event. */\nexport class Logout {\n constructor(\n /** The guard name the logout happened on. */\n readonly guard: string,\n /** The user that logged out. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired on a current-device-only logout - the `CurrentDeviceLogout` event. */\nexport class CurrentDeviceLogout {\n constructor(\n /** The guard name the logout happened on. */\n readonly guard: string,\n /** The user that logged out on this device. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when the user's other devices are logged out - the `OtherDeviceLogout` event. */\nexport class OtherDeviceLogout {\n constructor(\n /** The guard name the logout happened on. */\n readonly guard: string,\n /** The user whose other sessions were invalidated. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a new account is registered (dispatched by application code) - the `Registered` event. */\nexport class Registered {\n constructor(\n /** The freshly registered user. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a user's email address is verified - the `Verified` event. */\nexport class Verified {\n constructor(\n /** The user whose email was just verified. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/** Fired when a password is reset through the broker - the `PasswordReset` event. */\nexport class PasswordReset {\n constructor(\n /** The user whose password was reset. */\n readonly user: Authenticatable,\n ) {}\n}\n\n/**\n * Fired when login attempts are rate-limited - the `Lockout` event. Conventional implementations carry the\n * HTTP request; Plinth carries the credentials that triggered the lockout (dispatched by whatever\n * rate-limiting layer the application wires up).\n */\nexport class Lockout {\n constructor(\n /** The credentials whose attempts were locked out. */\n readonly credentials: Credentials,\n ) {}\n}\n","/**\n * Email verification - the `MustVerifyEmail` flow. {@link EmailVerifier} mints a signed,\n * expiring proof that a verification link was issued for a user's current email, and verifies it\n * before marking the user verified. The proof is an HMAC over the user id, a hash of the email, and\n * an expiry, so it cannot be forged and is invalidated if the email changes. Signing/clock are\n * injected, so it is deterministic and transport-agnostic (embed the payload in your verify URL).\n */\nimport { createHash, createHmac, timingSafeEqual } from 'node:crypto'\n\nimport { Verified } from './events'\n\nimport type { AuthEvents, Authenticatable } from './contracts'\n\n/** A user whose email address can be verified. */\nexport interface MustVerifyEmail {\n /** The email address being verified. */\n getEmailForVerification(): string\n /** Whether the email has already been verified. */\n hasVerifiedEmail(): boolean\n /** Mark the email as verified (persist `email_verified_at`). */\n markEmailAsVerified(): void | Promise<void>\n}\n\n/** A verifiable user - an {@link Authenticatable} that also implements {@link MustVerifyEmail}. */\nexport type VerifiableUser = Authenticatable & MustVerifyEmail\n\n/** A signed, expiring verification payload - what a verification link carries. */\nexport interface VerificationSignature {\n /** Expiry as epoch milliseconds. */\n expires: number\n /** HMAC signature over the user id, email hash, and expiry. */\n signature: string\n}\n\n/** Options for {@link EmailVerifier}. */\nexport interface EmailVerifierOptions {\n /** Secret key the verification payload is HMAC-signed with. */\n secret: string\n /** Link lifetime in minutes. Default `60`. */\n expireMinutes?: number\n /** Injected clock for deterministic expiry. Default `() => new Date()`. */\n now?: () => Date\n /** Optional event dispatcher; `Verified` is dispatched when a user is first verified. */\n events?: AuthEvents\n}\n\n/** Mints and checks signed, expiring email-verification payloads. */\nexport class EmailVerifier {\n private readonly secret: string\n private readonly expireMinutes: number\n private readonly now: () => Date\n private readonly events: AuthEvents | undefined\n\n constructor(options: EmailVerifierOptions) {\n this.secret = options.secret\n this.expireMinutes = options.expireMinutes ?? 60\n this.now = options.now ?? ((): Date => new Date())\n this.events = options.events\n }\n\n /** A stable hash of the user's email - proves the link was issued for this exact address. */\n hashFor(user: VerifiableUser): string {\n return createHash('sha256').update(user.getEmailForVerification()).digest('hex')\n }\n\n /** Build a signed, expiring verification payload for `user` (embed it in the verification URL). */\n sign(user: VerifiableUser): VerificationSignature {\n const expires = this.now().getTime() + this.expireMinutes * 60_000\n return { expires, signature: this.signature(user, expires) }\n }\n\n /** Whether `payload` is a valid, unexpired signature for `user`'s current email. */\n isValid(user: VerifiableUser, payload: VerificationSignature): boolean {\n if (this.now().getTime() > payload.expires) return false\n return safeEqual(this.signature(user, payload.expires), payload.signature)\n }\n\n /**\n * Verify a payload and mark the user verified. Returns `false` on a bad or expired signature;\n * idempotent - an already-verified user returns `true` without re-marking.\n */\n async verify(user: VerifiableUser, payload: VerificationSignature): Promise<boolean> {\n if (!this.isValid(user, payload)) return false\n if (!user.hasVerifiedEmail()) {\n await user.markEmailAsVerified()\n this.events?.dispatch(new Verified(user))\n }\n return true\n }\n\n /** The HMAC binding the user id, email hash, and expiry. */\n private signature(user: VerifiableUser, expires: number): string {\n const data = `${String(user.getAuthIdentifier())}.${this.hashFor(user)}.${String(expires)}`\n return createHmac('sha256', this.secret).update(data).digest('hex')\n }\n}\n\n/** Constant-time comparison of two hex signatures. */\nfunction safeEqual(a: string, b: string): boolean {\n const bufferA = Buffer.from(a)\n const bufferB = Buffer.from(b)\n if (bufferA.length !== bufferB.length) return false\n return timingSafeEqual(bufferA, bufferB)\n}\n","/**\n * Authentication guards - the `SessionGuard` (stateful, web), `TokenGuard` (stateless,\n * API), and `RequestGuard` (closure-driven). A {@link SessionGuard} persists the authenticated\n * user's id in the session and lazily resolves the user through a {@link UserProvider}; a\n * {@link TokenGuard} authenticates each request from a bearer/query/input token with no server-side\n * state; a {@link RequestGuard} delegates to a callback over the request (the `Auth::viaRequest`\n * driver). All cache the resolved user per instance so repeated `user()` calls hit the provider\n * once, and all accept an optional {@link AuthEvents} dispatcher that fires the auth events\n * at the equivalent moments (zero overhead when unset).\n */\nimport { randomBytes } from 'node:crypto'\n\nimport { Request, Response as HttpResponse } from '@plinthjs/http'\n\nimport {\n Attempting,\n Authenticated,\n CurrentDeviceLogout,\n Failed,\n Login,\n Logout,\n OtherDeviceLogout,\n Validated,\n} from './events'\n\nimport type {\n AuthEvents,\n Authenticatable,\n Credentials,\n Guard,\n Rememberable,\n StatefulGuard,\n UserProvider,\n} from './contracts'\nimport type { Session } from '@plinthjs/session'\n\n/** Default session key holding the authenticated user's identifier. */\nconst SESSION_KEY = 'auth.id'\n\n/** Default request field/query key holding an API token. */\nconst TOKEN_KEY = 'api_token'\n\n/**\n * Session key holding the hash of the authenticated user's password - the conventional\n * `AuthenticateSession` mechanism. The session middleware compares it against the user's current\n * hash each request, so {@link SessionGuard.logoutOtherDevices} (which re-hashes the password)\n * invalidates every other session while this one is kept in step.\n */\nexport const PASSWORD_HASH_SESSION_KEY = 'auth.password_hash'\n\n/** Default \"remember me\" cookie lifetime in minutes (400 days) - the conventional `$rememberDuration`. */\nconst DEFAULT_REMEMBER_DURATION = 576_000\n\n/** An `attemptWhen` callback - runs after credential validation; all must return `true` to log in. */\nexport type AttemptCallback = (\n user: Authenticatable,\n guard: SessionGuard,\n) => boolean | Promise<boolean>\n\n/** Options for {@link SessionGuard}. */\nexport interface SessionGuardOptions {\n /** Guard name carried on dispatched events. Default `'web'`. */\n name?: string\n /** The current request - required only for the HTTP Basic helpers. */\n request?: Request\n /** Optional event dispatcher; when unset no events are dispatched. */\n events?: AuthEvents\n}\n\n/** Session-backed, stateful guard. */\nexport class SessionGuard implements StatefulGuard {\n private cachedUser: Authenticatable | null = null\n private resolved = false\n private lastAttempted: Authenticatable | null = null\n private viaRememberFlag = false\n private rememberDuration = DEFAULT_REMEMBER_DURATION\n private request: Request | undefined\n private readonly name: string\n private readonly events: AuthEvents | undefined\n\n constructor(\n private readonly provider: UserProvider,\n private readonly session: Session,\n private readonly key: string = SESSION_KEY,\n options: SessionGuardOptions = {},\n ) {\n this.name = options.name ?? 'web'\n this.request = options.request\n this.events = options.events\n }\n\n async user(): Promise<Authenticatable | null> {\n if (this.resolved) return this.cachedUser\n const id = this.session.get<string | number>(this.key)\n this.cachedUser = id === null ? null : await this.provider.retrieveById(id)\n this.resolved = true\n return this.cachedUser\n }\n\n async check(): Promise<boolean> {\n return (await this.user()) !== null\n }\n\n async guest(): Promise<boolean> {\n return !(await this.check())\n }\n\n async id(): Promise<string | number | null> {\n const user = await this.user()\n return user === null ? null : user.getAuthIdentifier()\n }\n\n async validate(credentials: Credentials): Promise<boolean> {\n const user = await this.provider.retrieveByCredentials(credentials)\n this.lastAttempted = user\n if (user === null) return false\n return this.hasValidCredentials(user, credentials)\n }\n\n async attempt(credentials: Credentials): Promise<boolean> {\n return this.attemptWhen(credentials)\n }\n\n /**\n * Attempt to authenticate with additional callbacks - the `attemptWhen`. The callbacks\n * run after the credentials validate, receiving the user and this guard; every one must return\n * `true` (a falsy result fails the attempt without logging the user in).\n */\n async attemptWhen(\n credentials: Credentials,\n callbacks: AttemptCallback | readonly AttemptCallback[] = [],\n ): Promise<boolean> {\n this.events?.dispatch(new Attempting(this.name, credentials))\n const user = await this.provider.retrieveByCredentials(credentials)\n this.lastAttempted = user\n if (\n user !== null &&\n (await this.hasValidCredentials(user, credentials)) &&\n (await this.shouldLogin(callbacks, user))\n ) {\n await this.provider.rehashPasswordIfRequired?.(user, credentials)\n this.login(user)\n return true\n }\n this.events?.dispatch(new Failed(this.name, user, credentials))\n return false\n }\n\n async once(credentials: Credentials): Promise<boolean> {\n this.events?.dispatch(new Attempting(this.name, credentials))\n const user = await this.provider.retrieveByCredentials(credentials)\n this.lastAttempted = user\n if (user !== null && (await this.hasValidCredentials(user, credentials))) {\n this.setUser(user)\n return true\n }\n return false\n }\n\n login(user: Authenticatable): void {\n this.updateSession(user)\n this.events?.dispatch(new Login(this.name, user, false))\n this.setUser(user)\n }\n\n async loginUsingId(id: string | number): Promise<Authenticatable | null> {\n const user = await this.provider.retrieveById(id)\n if (user !== null) this.login(user)\n return user\n }\n\n /**\n * Log the current user out, cycling the remember token so every recaller dies - the conventional\n * `logout`. The session keys are cleared synchronously; the returned promise resolves once the\n * token has been cycled through the provider and the `Logout` event dispatched.\n */\n logout(): Promise<void> {\n return this.performLogout(true)\n }\n\n /**\n * Log the current user out on this device only - the `logoutCurrentDevice`. Unlike\n * {@link SessionGuard.logout} the remember token is *not* cycled, so other remembered devices\n * stay logged in. Dispatches `CurrentDeviceLogout`.\n */\n logoutCurrentDevice(): Promise<void> {\n return this.performLogout(false)\n }\n\n /**\n * Invalidate the user's sessions on every other device - the `logoutOtherDevices`.\n * Validates `password` against the current user (throwing when it does not match), then:\n *\n * - force re-hashes the password through {@link UserProvider.rehashPasswordIfRequired} (when the\n * provider supports it) and refreshes this session's stored password hash, so any session\n * checked by `authenticateSession` whose stored hash is now stale is logged out - the same\n * session-password-hash mechanism the conventional `AuthenticateSession` middleware uses; and\n * - cycles the remember token, killing every previously issued recaller cookie.\n *\n * Returns the fresh recaller value for *this* device, or `null` when nobody is authenticated.\n */\n async logoutOtherDevices(password: string): Promise<string | null> {\n const user = await this.user()\n if (user === null) return null\n if (!(await this.provider.validateCredentials(user, { password }))) {\n throw new Error('The given password does not match the current password.')\n }\n await this.provider.rehashPasswordIfRequired?.(user, { password }, true)\n this.session.put(PASSWORD_HASH_SESSION_KEY, user.getAuthPassword())\n const recaller = await this.remember(user)\n this.events?.dispatch(new OtherDeviceLogout(this.name, user))\n return recaller\n }\n\n setUser(user: Authenticatable): void {\n this.cachedUser = user\n this.resolved = true\n this.events?.dispatch(new Authenticated(this.name, user))\n }\n\n /** Set the current request (used by the HTTP Basic helpers). The `setRequest` equivalent. */\n setRequest(request: Request): this {\n this.request = request\n return this\n }\n\n /** The last user a credential attempt resolved, or `null`. The `getLastAttempted` equivalent. */\n getLastAttempted(): Authenticatable | null {\n return this.lastAttempted\n }\n\n /** Whether the current user was authenticated via a remember-me recaller. The `viaRemember` equivalent. */\n viaRemember(): boolean {\n return this.viaRememberFlag\n }\n\n /**\n * Set how long (in minutes) issued recaller cookies should live - the `setRememberDuration`\n * equivalent. The guard does not write cookies itself; read it back via\n * {@link SessionGuard.getRememberDuration} when turning a recaller value into a cookie.\n */\n setRememberDuration(minutes: number): this {\n this.rememberDuration = minutes\n return this\n }\n\n /** The \"remember me\" cookie lifetime in minutes. The `getRememberDuration` equivalent. */\n getRememberDuration(): number {\n return this.rememberDuration\n }\n\n /**\n * Attempt HTTP Basic authentication, logging the user in for the session - the `basic`.\n * Resolves to `undefined` when already authenticated or when the `Authorization: Basic` header\n * validates; otherwise resolves to a `401` challenge response (`WWW-Authenticate: Basic`).\n * Requires the request (constructor option or {@link SessionGuard.setRequest}).\n */\n async basic(field = 'email'): Promise<HttpResponse | undefined> {\n if (await this.check()) return undefined\n const credentials = this.basicCredentialsFromRequest(field)\n if (credentials !== null && (await this.attempt(credentials))) return undefined\n return failedBasicResponse()\n }\n\n /**\n * Perform a stateless HTTP Basic attempt (no session persistence) - the `onceBasic`.\n * Resolves to `undefined` on success, or the `401` challenge response on failure.\n */\n async onceBasic(field = 'email'): Promise<HttpResponse | undefined> {\n const credentials = this.basicCredentialsFromRequest(field)\n if (credentials !== null && (await this.once(credentials))) return undefined\n return failedBasicResponse()\n }\n\n /**\n * Issue a fresh remember-me token for `user`, persist it through the provider, and return the\n * recaller value (`id|token`) to store in a long-lived cookie.\n */\n async remember(user: Authenticatable): Promise<string> {\n const token = randomBytes(20).toString('hex')\n await this.provider.updateRememberToken(user, token)\n return recallerValue(user.getAuthIdentifier(), token)\n }\n\n /**\n * Authenticate from a recaller cookie value (`id|token`), logging the user in for the session on a\n * constant-time token match. Returns the user, or `null`.\n */\n async loginUsingRecaller(value: string): Promise<Authenticatable | null> {\n const recaller = parseRecaller(value)\n if (recaller === null) return null\n const user = await this.provider.retrieveByToken(recaller.id, recaller.token)\n if (user !== null) {\n this.viaRememberFlag = true\n this.updateSession(user)\n this.events?.dispatch(new Login(this.name, user, true))\n this.setUser(user)\n }\n return user\n }\n\n /** Persist the user's id and current password hash into the session. */\n private updateSession(user: Authenticatable): void {\n this.session.put(this.key, user.getAuthIdentifier())\n this.session.put(PASSWORD_HASH_SESSION_KEY, user.getAuthPassword())\n }\n\n /** Whether `credentials` validate against `user`, dispatching `Validated` when they do. */\n private async hasValidCredentials(\n user: Authenticatable,\n credentials: Credentials,\n ): Promise<boolean> {\n const valid = await this.provider.validateCredentials(user, credentials)\n if (valid) this.events?.dispatch(new Validated(this.name, user))\n return valid\n }\n\n /** Run the `attemptWhen` callbacks; every one must return `true` for the login to proceed. */\n private async shouldLogin(\n callbacks: AttemptCallback | readonly AttemptCallback[],\n user: Authenticatable,\n ): Promise<boolean> {\n const list = typeof callbacks === 'function' ? [callbacks] : callbacks\n for (const callback of list) {\n if (!(await callback(user, this))) return false\n }\n return true\n }\n\n /** Clear the session synchronously, then finish teardown (token cycling + event) async. */\n private performLogout(cycleToken: boolean): Promise<void> {\n const known = this.resolved ? this.cachedUser : null\n const id = this.session.get<string | number>(this.key)\n this.session.forget(this.key)\n this.session.forget(PASSWORD_HASH_SESSION_KEY)\n this.cachedUser = null\n this.resolved = true\n this.viaRememberFlag = false\n return this.finishLogout(known, id, cycleToken)\n }\n\n /** Resolve the user that was logged out, cycle their remember token, and dispatch the event. */\n private async finishLogout(\n known: Authenticatable | null,\n id: string | number | null,\n cycleToken: boolean,\n ): Promise<void> {\n const user = known ?? (id === null ? null : await this.provider.retrieveById(id))\n if (user === null) return\n if (cycleToken && hasRememberToken(user)) {\n await this.provider.updateRememberToken(user, randomBytes(20).toString('hex'))\n }\n this.events?.dispatch(\n cycleToken ? new Logout(this.name, user) : new CurrentDeviceLogout(this.name, user),\n )\n }\n\n /** Parse `Authorization: Basic …` from the request into `{ [field], password }`, or `null`. */\n private basicCredentialsFromRequest(field: string): Credentials | null {\n if (this.request === undefined) return null\n const header = this.request.header('authorization')\n if (!header?.toLowerCase().startsWith('basic ')) return null\n const decoded = Buffer.from(header.slice(6).trim(), 'base64').toString('utf8')\n const separator = decoded.indexOf(':')\n if (separator === -1) return null\n return { [field]: decoded.slice(0, separator), password: decoded.slice(separator + 1) }\n }\n}\n\n/** The `401` challenge sent when HTTP Basic authentication fails. */\nfunction failedBasicResponse(): HttpResponse {\n return HttpResponse.make('Invalid Basic credentials.', 401).withHeaders({\n 'WWW-Authenticate': 'Basic',\n })\n}\n\n/** Whether `user` exposes a non-empty remember-me token. */\nfunction hasRememberToken(user: Authenticatable): boolean {\n if (!('getRememberToken' in user)) return false\n const token = (user as Authenticatable & Rememberable).getRememberToken()\n return typeof token === 'string' && token.length > 0\n}\n\n/** Encode a recaller cookie value from a user id and remember-me token. */\nfunction recallerValue(id: string | number, token: string): string {\n return `${String(id)}|${token}`\n}\n\n/** Parse a recaller cookie value (`id|token`) into its parts, or `null` if malformed. */\nfunction parseRecaller(value: string): { id: string; token: string } | null {\n const separator = value.indexOf('|')\n if (separator <= 0) return null\n const token = value.slice(separator + 1)\n if (token.length === 0) return null\n return { id: value.slice(0, separator), token }\n}\n\n/** Options for {@link TokenGuard}. */\nexport interface TokenGuardOptions {\n /** Guard name carried on dispatched events. Default `'api'`. */\n name?: string\n /** Optional event dispatcher; when unset no events are dispatched. */\n events?: AuthEvents\n}\n\n/** Stateless token guard. */\nexport class TokenGuard implements Guard {\n private cachedUser: Authenticatable | null = null\n private resolved = false\n private readonly name: string\n private readonly events: AuthEvents | undefined\n\n constructor(\n private readonly provider: UserProvider,\n private readonly request: Request,\n private readonly inputKey: string = TOKEN_KEY,\n options: TokenGuardOptions = {},\n ) {\n this.name = options.name ?? 'api'\n this.events = options.events\n }\n\n async user(): Promise<Authenticatable | null> {\n if (this.resolved) return this.cachedUser\n const token = this.tokenForRequest()\n this.cachedUser =\n token === undefined\n ? null\n : await this.provider.retrieveByCredentials({ [this.inputKey]: token })\n this.resolved = true\n if (this.cachedUser !== null) {\n this.events?.dispatch(new Authenticated(this.name, this.cachedUser))\n }\n return this.cachedUser\n }\n\n async check(): Promise<boolean> {\n return (await this.user()) !== null\n }\n\n async guest(): Promise<boolean> {\n return !(await this.check())\n }\n\n async id(): Promise<string | number | null> {\n const user = await this.user()\n return user === null ? null : user.getAuthIdentifier()\n }\n\n async validate(credentials: Credentials): Promise<boolean> {\n const user = await this.provider.retrieveByCredentials(credentials)\n if (user === null) return false\n return this.provider.validateCredentials(user, credentials)\n }\n\n setUser(user: Authenticatable): void {\n this.cachedUser = user\n this.resolved = true\n this.events?.dispatch(new Authenticated(this.name, user))\n }\n\n /** Read the API token from the bearer header, then the query string, then the input bag. */\n private tokenForRequest(): string | undefined {\n const bearer = this.request.bearerToken()\n if (bearer !== undefined) return bearer\n const query = this.request.query(this.inputKey)\n if (typeof query === 'string' && query.length > 0) return query\n const input = this.request.input<string>(this.inputKey)\n return typeof input === 'string' && input.length > 0 ? input : undefined\n }\n}\n\n/**\n * The user-resolver callback behind a {@link RequestGuard} - the closure passed to\n * `Auth::viaRequest`. Receives the request (and the provider, when one was registered) and returns\n * the authenticated user, or `null`/`undefined` for a guest.\n */\nexport type RequestUserResolver = (\n request: Request,\n provider?: UserProvider,\n) => Authenticatable | null | undefined | Promise<Authenticatable | null | undefined>\n\n/**\n * Closure-driven guard over the current request - the `RequestGuard` (the engine behind\n * `Auth::viaRequest`). Resolves the user once per instance through the callback.\n */\nexport class RequestGuard implements Guard {\n private cachedUser: Authenticatable | null = null\n private resolved = false\n private request: Request | undefined\n\n constructor(\n private readonly callback: RequestUserResolver,\n request?: Request,\n private readonly provider?: UserProvider | undefined,\n ) {\n this.request = request\n }\n\n async user(): Promise<Authenticatable | null> {\n if (this.resolved) return this.cachedUser\n this.cachedUser =\n this.request === undefined\n ? null\n : ((await this.callback(this.request, this.provider)) ?? null)\n this.resolved = true\n return this.cachedUser\n }\n\n async check(): Promise<boolean> {\n return (await this.user()) !== null\n }\n\n async guest(): Promise<boolean> {\n return !(await this.check())\n }\n\n async id(): Promise<string | number | null> {\n const user = await this.user()\n return user === null ? null : user.getAuthIdentifier()\n }\n\n /**\n * Whether the callback resolves a user for `credentials['request']` - the conventional\n * `RequestGuard::validate`, which runs the resolver against the given request.\n */\n async validate(credentials: Credentials): Promise<boolean> {\n const request = credentials['request']\n if (!(request instanceof Request)) return false\n return ((await this.callback(request, this.provider)) ?? null) !== null\n }\n\n setUser(user: Authenticatable): void {\n this.cachedUser = user\n this.resolved = true\n }\n\n /** Swap the request and reset the cached user. The `setRequest` equivalent. */\n setRequest(request: Request): this {\n this.request = request\n this.cachedUser = null\n this.resolved = false\n return this\n }\n}\n","/**\n * `AuthManager` - resolves named authentication guards, the conventional API /\n * `Auth` facade equivalent. Guards are registered as factories (so request-scoped guards are built\n * fresh each time) and resolved by name, falling back to the configured default. Factories may\n * accept the current request, which {@link AuthManager.guard} forwards - the seam\n * {@link AuthManager.viaRequest} uses to register closure-driven {@link RequestGuard} drivers.\n */\nimport { RequestGuard } from './guards'\n\nimport type { Guard, UserProvider } from './contracts'\nimport type { RequestUserResolver } from './guards'\nimport type { Request } from '@plinthjs/http'\n\n/**\n * Builds a guard on demand. Request-scoped guards capture per-request state in the closure, or read\n * the request {@link AuthManager.guard} forwards (factories registered before this parameter\n * existed simply ignore it).\n */\nexport type GuardFactory = (request?: Request) => Guard\n\nexport class AuthManager {\n private readonly guards = new Map<string, GuardFactory>()\n\n constructor(private defaultGuard = 'web') {}\n\n /** Register a guard factory under `name`. The `Auth::extend()` equivalent. */\n extend(name: string, factory: GuardFactory): this {\n this.guards.set(name, factory)\n return this\n }\n\n /**\n * Register a closure-driven guard under `name` - the `Auth::viaRequest()` equivalent. The\n * callback receives the request (and `provider`, when given) and returns the authenticated user\n * or `null`; the manager builds a {@link RequestGuard} around it on every resolve.\n */\n viaRequest(name: string, callback: RequestUserResolver, provider?: UserProvider): this {\n return this.extend(name, (request?: Request) => new RequestGuard(callback, request, provider))\n }\n\n /**\n * Resolve a guard by name (or the default), forwarding `request` to the factory so\n * request-scoped guards (e.g. {@link AuthManager.viaRequest}) can read it. Throws if the guard is\n * not registered.\n */\n guard(name?: string, request?: Request): Guard {\n const resolved = name ?? this.defaultGuard\n const factory = this.guards.get(resolved)\n if (factory === undefined) {\n throw new Error(`Auth guard [${resolved}] is not defined.`)\n }\n return factory(request)\n }\n\n /** Change the default guard name. The `Auth::shouldUse()` equivalent. */\n setDefaultGuard(name: string): this {\n this.defaultGuard = name\n return this\n }\n\n /** The current default guard name. */\n getDefaultGuard(): string {\n return this.defaultGuard\n }\n}\n","/**\n * Authentication middleware bridging `@plinthjs/auth` to `@plinthjs/http` - the `Authenticate`\n * (`auth`) middleware family. {@link authenticateSession} resolves the user from the session\n * (requires the session middleware) and {@link authenticateToken} from a request token; both attach\n * the user to the request (readable via {@link getUser}) or render a `401` via\n * {@link AuthenticationError}. {@link authenticateSession} also keeps a hash of the user's password\n * in the session so sessions die when the password\n * changes - e.g. after `SessionGuard.logoutOtherDevices`. {@link redirectIfAuthenticated} is the\n * `guest` middleware, and {@link requirePassword} / {@link confirmPassword} implement the conventional\n * `password.confirm` flow over an `auth.password_confirmed_at` session timestamp.\n */\nimport { HttpException, Response } from '@plinthjs/http'\nimport { getSession } from '@plinthjs/session'\n\nimport { PASSWORD_HASH_SESSION_KEY, SessionGuard, TokenGuard } from './guards'\n\nimport type { Authenticatable, Credentials, UserProvider } from './contracts'\nimport type { Middleware, Request } from '@plinthjs/http'\nimport type { Session } from '@plinthjs/session'\n\n/** Request-attribute key under which the authenticated user is stored. */\nconst USER_ATTRIBUTE = 'plinth.user'\n\n/** Session key holding the epoch-seconds timestamp of the last password confirmation. */\nexport const PASSWORD_CONFIRMED_AT_SESSION_KEY = 'auth.password_confirmed_at'\n\n/** Default password-confirmation window in seconds - the conventional `auth.password_timeout`. */\nconst DEFAULT_PASSWORD_TIMEOUT_SECONDS = 10_800\n\n/** Raised when authentication is required but the request is unauthenticated (renders `401`). */\nexport class AuthenticationError extends HttpException {\n constructor(message = 'Unauthenticated.') {\n super(401, message)\n this.name = 'AuthenticationError'\n }\n}\n\n/** The authenticated user attached by an authenticate middleware, or `undefined`. */\nexport function getUser(req: Request): Authenticatable | undefined {\n return req.attribute<Authenticatable>(USER_ATTRIBUTE)\n}\n\n/**\n * Authenticate via the session - the web `auth` middleware. Requires the session middleware to have\n * run; resolves the user from the session id and attaches it, or throws {@link AuthenticationError}.\n * Also enforces the `AuthenticateSession` password-hash check: the user's password hash is\n * stored in the session on first sight and compared on every request, so a password change (e.g.\n * `SessionGuard.logoutOtherDevices`) logs every stale session out.\n */\nexport function authenticateSession(provider: UserProvider): Middleware {\n return async (req, next) => {\n const session = requireSession(req)\n const guard = new SessionGuard(provider, session)\n const user = await guard.user()\n if (user === null) throw new AuthenticationError()\n const storedHash = session.get<string>(PASSWORD_HASH_SESSION_KEY)\n if (storedHash !== null && storedHash !== user.getAuthPassword()) {\n // The password changed since this session authenticated - invalidate it (without cycling\n // the remember token, which the password-changing device already re-issued).\n await guard.logoutCurrentDevice()\n throw new AuthenticationError()\n }\n if (storedHash === null) session.put(PASSWORD_HASH_SESSION_KEY, user.getAuthPassword())\n return next(req.withAttribute(USER_ATTRIBUTE, user))\n }\n}\n\n/**\n * Authenticate via a request token - the stateless `auth:api` middleware. Resolves the user from a\n * bearer/query/input token and attaches it, or throws {@link AuthenticationError}.\n */\nexport function authenticateToken(provider: UserProvider, inputKey?: string): Middleware {\n return async (req, next) => {\n const guard =\n inputKey === undefined\n ? new TokenGuard(provider, req)\n : new TokenGuard(provider, req, inputKey)\n const user = await guard.user()\n if (user === null) throw new AuthenticationError()\n return next(req.withAttribute(USER_ATTRIBUTE, user))\n }\n}\n\n/**\n * Redirect authenticated users away (e.g. from login/register pages) - the conventional\n * `RedirectIfAuthenticated` (`guest`) middleware. Guests (and requests without a session) pass\n * through; an authenticated session is redirected to `redirectTo`.\n */\nexport function redirectIfAuthenticated(provider: UserProvider, redirectTo = '/home'): Middleware {\n return async (req, next) => {\n const session = getSession(req)\n if (session === undefined) return next(req)\n const user = await new SessionGuard(provider, session).user()\n return user === null ? next(req) : Response.redirectTo(redirectTo)\n }\n}\n\n/**\n * Require a recent password confirmation - the `RequirePassword` (`password.confirm`)\n * middleware. Passes when the session's `auth.password_confirmed_at` timestamp is within\n * `passwordTimeoutSeconds`; otherwise redirects to `redirectTo` (or renders `423 Locked` for JSON\n * clients). Stamp the timestamp via {@link confirmPassword} after re-validating the password.\n */\nexport function requirePassword(\n redirectTo = '/confirm-password',\n passwordTimeoutSeconds: number = DEFAULT_PASSWORD_TIMEOUT_SECONDS,\n now: () => Date = (): Date => new Date(),\n): Middleware {\n return async (req, next) => {\n const session = requireSession(req)\n const confirmedAt = session.get<number>(PASSWORD_CONFIRMED_AT_SESSION_KEY)\n const fresh =\n typeof confirmedAt === 'number' &&\n now().getTime() / 1000 - confirmedAt < passwordTimeoutSeconds\n if (fresh) return next(req)\n if (req.wantsJson()) {\n return Response.json({ message: 'Password confirmation required.' }, 423)\n }\n return Response.redirectTo(redirectTo)\n }\n}\n\n/**\n * Re-validate the user's password and stamp the session's confirmation timestamp - what the conventional\n * `ConfirmablePasswordController` does for the `password.confirm` flow. Returns `false` (leaving\n * the session untouched) when the password does not match.\n */\nexport async function confirmPassword(\n provider: UserProvider,\n session: Session,\n user: Authenticatable,\n password: string,\n now: () => Date = (): Date => new Date(),\n): Promise<boolean> {\n const credentials: Credentials = { password }\n if (!(await provider.validateCredentials(user, credentials))) return false\n session.put(PASSWORD_CONFIRMED_AT_SESSION_KEY, Math.floor(now().getTime() / 1000))\n return true\n}\n\n/** The request's session, or a `500` explaining that the session middleware must run first. */\nfunction requireSession(req: Request): Session {\n const session = getSession(req)\n if (session === undefined) {\n throw new HttpException(\n 500,\n 'Session authentication requires the session middleware to run first.',\n )\n }\n return session\n}\n","/**\n * Password reset - the conventional API layer. A {@link PasswordBroker} drives the\n * \"forgot password\" flow: find the user, throttle re-sends, mint a single-use time-limited token,\n * hand it to a sender callback, and later verify it before letting a callback persist the new\n * password. Tokens live behind a {@link TokenRepository} seam; {@link ArrayTokenRepository} is the\n * in-memory implementation (token hashes only, an injected clock for expiry/throttle, the\n * `@plinthjs/encryption` {@link Hasher} for hashing). The broker is transport-agnostic - the caller\n * supplies how the link is delivered and how the password is saved.\n */\nimport { randomBytes } from 'node:crypto'\n\nimport { PasswordReset } from './events'\n\nimport type { AuthEvents, Authenticatable, Credentials, UserProvider } from './contracts'\nimport type { Hasher } from '@plinthjs/encryption'\n\n/** The outcome of a broker operation - the `Password::*` status constants. */\nexport const PasswordStatus = {\n ResetLinkSent: 'passwords.sent',\n PasswordReset: 'passwords.reset',\n InvalidUser: 'passwords.user',\n InvalidToken: 'passwords.token',\n InvalidPassword: 'passwords.password',\n ResetThrottled: 'passwords.throttled',\n} as const\n\n/** A password-broker status value. */\nexport type PasswordStatus = (typeof PasswordStatus)[keyof typeof PasswordStatus]\n\n/** Stores, verifies, and expires password-reset tokens. */\nexport interface TokenRepository {\n /** Mint, store, and return a fresh plaintext token for `user` (only its hash is kept). */\n create(user: Authenticatable): Promise<string>\n /** Whether `token` matches a stored, non-expired token for `user`. */\n exists(user: Authenticatable, token: string): Promise<boolean>\n /** Whether `user` was issued a token within the throttle window (for re-send throttling). */\n recentlyCreatedToken(user: Authenticatable): Promise<boolean>\n /** Forget `user`'s token (after a successful reset). */\n delete(user: Authenticatable): Promise<void>\n /** Purge every expired token. */\n deleteExpired(): Promise<void>\n}\n\ninterface StoredToken {\n hashed: string\n createdAt: number\n}\n\n/** Options for {@link ArrayTokenRepository}. */\nexport interface ArrayTokenRepositoryOptions {\n /** Hasher used to store token hashes (never the plaintext). */\n hasher: Hasher\n /** Token lifetime in minutes. Default `60`. */\n expireMinutes?: number\n /** Re-send throttle window in seconds. Default `60`. */\n throttleSeconds?: number\n /** Injected clock for deterministic expiry/throttle. Default `() => new Date()`. */\n now?: () => Date\n /** Plaintext token generator. Default 40 random hex chars; tests may inject a fixed value. */\n createToken?: () => string\n}\n\n/** In-memory {@link TokenRepository}, keyed by the user's auth identifier - ideal for tests/small apps. */\nexport class ArrayTokenRepository implements TokenRepository {\n private readonly store = new Map<string | number, StoredToken>()\n private readonly hasher: Hasher\n private readonly expireMinutes: number\n private readonly throttleSeconds: number\n private readonly now: () => Date\n private readonly makeToken: () => string\n\n constructor(options: ArrayTokenRepositoryOptions) {\n this.hasher = options.hasher\n this.expireMinutes = options.expireMinutes ?? 60\n this.throttleSeconds = options.throttleSeconds ?? 60\n this.now = options.now ?? ((): Date => new Date())\n this.makeToken = options.createToken ?? ((): string => randomBytes(20).toString('hex'))\n }\n\n async create(user: Authenticatable): Promise<string> {\n const token = this.makeToken()\n this.store.set(user.getAuthIdentifier(), {\n hashed: this.hasher.make(token),\n createdAt: this.now().getTime(),\n })\n return token\n }\n\n async exists(user: Authenticatable, token: string): Promise<boolean> {\n const record = this.store.get(user.getAuthIdentifier())\n if (record === undefined || this.expired(record)) return false\n return this.hasher.check(token, record.hashed)\n }\n\n async recentlyCreatedToken(user: Authenticatable): Promise<boolean> {\n const record = this.store.get(user.getAuthIdentifier())\n if (record === undefined) return false\n return (this.now().getTime() - record.createdAt) / 1000 < this.throttleSeconds\n }\n\n async delete(user: Authenticatable): Promise<void> {\n this.store.delete(user.getAuthIdentifier())\n }\n\n async deleteExpired(): Promise<void> {\n for (const [key, record] of this.store) {\n if (this.expired(record)) this.store.delete(key)\n }\n }\n\n private expired(record: StoredToken): boolean {\n return (this.now().getTime() - record.createdAt) / 60_000 >= this.expireMinutes\n }\n}\n\n/** Credentials for a reset: the lookup fields plus the `token` and new `password`. */\nexport type ResetCredentials = Credentials & { token: string; password: string }\n\n/** A callback that delivers the reset link/token to the user (email, SMS, …). */\nexport type ResetLinkSender = (user: Authenticatable, token: string) => void | Promise<void>\n\n/** A callback that persists the user's new password. */\nexport type PasswordResetCallback = (\n user: Authenticatable,\n password: string,\n) => void | Promise<void>\n\n/** Drives the password-reset flow over a {@link UserProvider} and {@link TokenRepository}. */\nexport class PasswordBroker {\n private readonly events: AuthEvents | undefined\n\n constructor(\n private readonly users: UserProvider,\n private readonly tokens: TokenRepository,\n events?: AuthEvents,\n ) {\n this.events = events\n }\n\n /**\n * Send a reset link: resolve the user from `credentials`, throttle repeat requests, mint a token,\n * and hand it to `send`. Returns {@link PasswordStatus.ResetLinkSent} on success.\n */\n async sendResetLink(credentials: Credentials, send: ResetLinkSender): Promise<PasswordStatus> {\n const user = await this.users.retrieveByCredentials(credentials)\n if (user === null) return PasswordStatus.InvalidUser\n if (await this.tokens.recentlyCreatedToken(user)) return PasswordStatus.ResetThrottled\n const token = await this.tokens.create(user)\n await send(user, token)\n return PasswordStatus.ResetLinkSent\n }\n\n /**\n * Reset a password: resolve the user, require a non-empty password, verify the token, then run\n * `reset` to persist and delete the token. Returns {@link PasswordStatus.PasswordReset} on success.\n */\n async reset(\n credentials: ResetCredentials,\n reset: PasswordResetCallback,\n ): Promise<PasswordStatus> {\n const user = await this.users.retrieveByCredentials(this.lookupOnly(credentials))\n if (user === null) return PasswordStatus.InvalidUser\n if (typeof credentials.password !== 'string' || credentials.password === '') {\n return PasswordStatus.InvalidPassword\n }\n if (!(await this.tokens.exists(user, credentials.token))) return PasswordStatus.InvalidToken\n await reset(user, credentials.password)\n await this.tokens.delete(user)\n this.events?.dispatch(new PasswordReset(user))\n return PasswordStatus.PasswordReset\n }\n\n /** The user-lookup credentials, with `token`/`password` removed so they don't act as match fields. */\n private lookupOnly(credentials: Credentials): Credentials {\n const lookup: Credentials = {}\n for (const [key, value] of Object.entries(credentials)) {\n if (key !== 'token' && key !== 'password') lookup[key] = value\n }\n return lookup\n }\n}\n","/**\n * User providers - the conventional API and array/database providers.\n * {@link GenericUser} is a record-backed {@link Authenticatable}; {@link ArrayUserProvider} resolves\n * users from an in-memory list, validating passwords through an injected {@link Hasher}. A\n * database/Eloquent provider implements the same {@link UserProvider} seam against `@plinthjs/orm`.\n */\nimport { timingSafeEqual } from 'node:crypto'\n\nimport type {\n Authenticatable,\n Credentials,\n PasswordUpdatable,\n Rememberable,\n UserProvider,\n} from './contracts'\nimport type { Hasher } from '@plinthjs/encryption'\n\n/** Default column holding a user's remember-me token. */\nconst REMEMBER_TOKEN = 'remember_token'\n\n/** A simple record-backed {@link Authenticatable}. */\nexport class GenericUser implements Authenticatable, Rememberable, PasswordUpdatable {\n constructor(\n readonly attributes: Record<string, unknown>,\n private readonly identifierName = 'id',\n private readonly passwordName = 'password',\n ) {}\n\n getAuthIdentifier(): string | number {\n const id = this.attributes[this.identifierName]\n if (typeof id === 'number' || typeof id === 'string') return id\n return ''\n }\n\n getAuthIdentifierName(): string {\n return this.identifierName\n }\n\n getAuthPassword(): string {\n const password = this.attributes[this.passwordName]\n return typeof password === 'string' ? password : ''\n }\n\n setAuthPassword(hashed: string): void {\n this.attributes[this.passwordName] = hashed\n }\n\n getRememberToken(): string | null {\n const token = this.attributes[REMEMBER_TOKEN]\n return typeof token === 'string' ? token : null\n }\n\n setRememberToken(token: string): void {\n this.attributes[REMEMBER_TOKEN] = token\n }\n\n /** Read an arbitrary attribute, used by providers to match credentials. */\n getAttribute(key: string): unknown {\n return this.attributes[key]\n }\n}\n\n/** An in-memory {@link UserProvider} over a fixed list of users - ideal for tests and small apps. */\nexport class ArrayUserProvider implements UserProvider {\n constructor(\n private readonly users: GenericUser[],\n private readonly hasher: Hasher,\n ) {}\n\n retrieveById(identifier: string | number): Promise<Authenticatable | null> {\n const user = this.users.find((candidate) => candidate.getAuthIdentifier() === identifier)\n return Promise.resolve(user ?? null)\n }\n\n retrieveByToken(identifier: string | number, token: string): Promise<Authenticatable | null> {\n // Recaller ids arrive as cookie strings, so match by string form (tolerant of number ids).\n const user = this.users.find(\n (candidate) => String(candidate.getAuthIdentifier()) === String(identifier),\n )\n const stored = user?.getRememberToken()\n if (user === undefined || stored === null || stored === undefined || stored.length === 0) {\n return Promise.resolve(null)\n }\n return Promise.resolve(safeEqual(stored, token) ? user : null)\n }\n\n updateRememberToken(user: Authenticatable, token: string): Promise<void> {\n if (isRememberable(user)) user.setRememberToken(token)\n return Promise.resolve()\n }\n\n retrieveByCredentials(credentials: Credentials): Promise<Authenticatable | null> {\n const keys = Object.keys(credentials).filter((key) => !key.includes('password'))\n if (keys.length === 0) return Promise.resolve(null)\n const user = this.users.find((candidate) =>\n keys.every((key) => candidate.getAttribute(key) === credentials[key]),\n )\n return Promise.resolve(user ?? null)\n }\n\n validateCredentials(user: Authenticatable, credentials: Credentials): Promise<boolean> {\n const password = credentials['password']\n if (typeof password !== 'string') return Promise.resolve(false)\n return Promise.resolve(this.hasher.check(password, user.getAuthPassword()))\n }\n\n /**\n * Re-hash and persist the user's password when its cost parameters no longer match the hasher's\n * (or always, when `force` is set) - the `rehashPasswordIfRequired`. Persists through the\n * {@link PasswordUpdatable} seam, mirroring how remember tokens are persisted.\n */\n rehashPasswordIfRequired(\n user: Authenticatable,\n credentials: Credentials,\n force = false,\n ): Promise<void> {\n const password = credentials['password']\n if (typeof password !== 'string') return Promise.resolve()\n if (!force && !this.hasher.needsRehash(user.getAuthPassword())) return Promise.resolve()\n if (isPasswordUpdatable(user)) user.setAuthPassword(this.hasher.make(password))\n return Promise.resolve()\n }\n}\n\n/** Whether `user` supports remember-me persistence. */\nfunction isRememberable(user: Authenticatable): user is Authenticatable & Rememberable {\n return 'setRememberToken' in user && typeof user.setRememberToken === 'function'\n}\n\n/** Whether `user` supports password-hash persistence. */\nfunction isPasswordUpdatable(user: Authenticatable): user is Authenticatable & PasswordUpdatable {\n return 'setAuthPassword' in user && typeof user.setAuthPassword === 'function'\n}\n\n/** Constant-time comparison of two remember-me tokens. */\nfunction safeEqual(a: string, b: string): boolean {\n const bufferA = Buffer.from(a)\n const bufferB = Buffer.from(b)\n if (bufferA.length !== bufferB.length) return false\n return timingSafeEqual(bufferA, bufferB)\n}\n","/**\n * @plinthjs/auth - authentication.\n *\n * The {@link Authenticatable} / {@link UserProvider} / {@link Guard} contracts, an in-memory\n * {@link ArrayUserProvider} over {@link GenericUser}s (passwords verified through `@plinthjs/encryption`,\n * re-hashed on login via {@link UserProvider.rehashPasswordIfRequired}), the {@link SessionGuard}\n * (stateful, web - with `attemptWhen`, HTTP Basic, remember-me, and the logout variants), the\n * {@link TokenGuard} (stateless, API), the {@link RequestGuard} behind\n * {@link AuthManager.viaRequest}, an {@link AuthManager} that resolves named guards, the conventional\n * auth event classes dispatched through the structural {@link AuthEvents} seam, and the\n * {@link authenticateSession} / {@link authenticateToken} / {@link redirectIfAuthenticated} /\n * {@link requirePassword} HTTP middleware (with {@link getUser} to read the user off the request).\n */\n\n/** The Plinth version this build of `auth` ships with. */\nexport const VERSION = '0.1.0'\n\nexport type {\n Authenticatable,\n AuthEvents,\n Credentials,\n Guard,\n PasswordUpdatable,\n Rememberable,\n StatefulGuard,\n UserProvider,\n} from './contracts'\nexport {\n EmailVerifier,\n type EmailVerifierOptions,\n type MustVerifyEmail,\n type VerifiableUser,\n type VerificationSignature,\n} from './email-verification'\nexport {\n Attempting,\n Authenticated,\n CurrentDeviceLogout,\n Failed,\n Lockout,\n Login,\n Logout,\n OtherDeviceLogout,\n PasswordReset,\n Registered,\n Validated,\n Verified,\n} from './events'\nexport {\n type AttemptCallback,\n PASSWORD_HASH_SESSION_KEY,\n RequestGuard,\n type RequestUserResolver,\n SessionGuard,\n type SessionGuardOptions,\n TokenGuard,\n type TokenGuardOptions,\n} from './guards'\nexport { AuthManager, type GuardFactory } from './manager'\nexport {\n AuthenticationError,\n authenticateSession,\n authenticateToken,\n confirmPassword,\n getUser,\n PASSWORD_CONFIRMED_AT_SESSION_KEY,\n redirectIfAuthenticated,\n requirePassword,\n} from './middleware'\nexport {\n ArrayTokenRepository,\n type ArrayTokenRepositoryOptions,\n PasswordBroker,\n type PasswordResetCallback,\n PasswordStatus,\n type ResetCredentials,\n type ResetLinkSender,\n type TokenRepository,\n} from './passwords'\nexport { ArrayUserProvider, GenericUser } from './providers'\n"]}