@warlock.js/auth 5.20.0 → 5.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/esm/contracts/request-locals.d.mts +5 -0
  3. package/esm/contracts/request-locals.d.mts.map +1 -1
  4. package/esm/contracts/types.d.mts +13 -0
  5. package/esm/contracts/types.d.mts.map +1 -1
  6. package/esm/contracts/types.mjs.map +1 -1
  7. package/esm/index.d.mts +3 -1
  8. package/esm/index.mjs +6 -3
  9. package/esm/middleware/auth.middleware.d.mts.map +1 -1
  10. package/esm/middleware/auth.middleware.mjs +37 -114
  11. package/esm/middleware/auth.middleware.mjs.map +1 -1
  12. package/esm/services/auth-config.mjs +2 -0
  13. package/esm/services/auth-config.mjs.map +1 -1
  14. package/esm/services/auth.service.d.mts +36 -1
  15. package/esm/services/auth.service.d.mts.map +1 -1
  16. package/esm/services/auth.service.mjs +67 -0
  17. package/esm/services/auth.service.mjs.map +1 -1
  18. package/esm/services/index.d.mts +2 -1
  19. package/esm/services/index.mjs +1 -0
  20. package/esm/services/jwt.d.mts.map +1 -1
  21. package/esm/services/jwt.mjs +4 -1
  22. package/esm/services/jwt.mjs.map +1 -1
  23. package/esm/services/resolve-request-user.d.mts +49 -0
  24. package/esm/services/resolve-request-user.d.mts.map +1 -0
  25. package/esm/services/resolve-request-user.mjs +131 -0
  26. package/esm/services/resolve-request-user.mjs.map +1 -0
  27. package/esm/session/index.d.mts +1 -0
  28. package/esm/session/index.mjs +3 -0
  29. package/esm/session/page-session.d.mts +49 -0
  30. package/esm/session/page-session.d.mts.map +1 -0
  31. package/esm/session/page-session.mjs +119 -0
  32. package/esm/session/page-session.mjs.map +1 -0
  33. package/esm/utils/index.mjs +1 -1
  34. package/package.json +8 -8
  35. package/skills/handle-login-and-logout/SKILL.md +4 -0
package/CHANGELOG.md CHANGED
@@ -1,9 +1,27 @@
1
- # Changelog — @warlock.js/auth
1
+ # Changelog — @warlock.js/auth
2
2
 
3
3
  All notable changes to `@warlock.js/auth` are documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `@warlock.js/*` packages are released in lockstep — every package shares the same version number, so a version below may list only the changes that affected this package.
6
6
 
7
+ ## 5.21.0 - 2026-09-25
8
+
9
+ ### Added
10
+
11
+ - Page sessions: `pageSession` / `sessionMiddleware` give pages a renewing session (renewal on by default). `session.maxAge` bounds the token family from its creation (default `"30d"`); a family past it is revoked and renewal returns `null`.
12
+ - `setSessionCookies` / `clearSessionCookies` write HttpOnly, SameSite=Lax, `Path=/` cookies, ignoring `auth.cookie.path`. `authService.loginWithSessionCookies()` logs in and sets them.
13
+ - `resolveRequestUser` memoizes on `request.locals.session`: repeat or concurrent callers in one request share a single verify, DB lookup and renewal (the first caller's options win).
14
+
15
+ ### Changed
16
+
17
+ - **BREAKING:** `loginWithSessionCookies()` requires a same-origin `Origin`/`Referer` even with no cookies, otherwise it throws `CsrfOriginMismatchError`. Send the header from non-browser clients.
18
+ - **BREAKING:** `authMiddleware` takes an ordered header/cookie `sources` list; a present Authorization header always wins and never falls back to the cookie, so an invalid header now returns `401`.
19
+ - JWTs carry a random `jti`, so tokens issued in the same second differ.
20
+
21
+
22
+ ### Changed
23
+
24
+ - Lockstep release maintenance and dependency refresh.
7
25
  ## 5.20.0 - 2026-09-24
8
26
 
9
27
  ### Changed
@@ -36,6 +36,11 @@ interface RequestUser {}
36
36
  declare module "@warlock.js/core" {
37
37
  interface RequestLocals {
38
38
  user?: RequestUser;
39
+ /**
40
+ * The in-flight or settled result of `resolveRequestUser`, memoised per
41
+ * request so every caller shares one verify, one lookup and one renewal.
42
+ */
43
+ session?: Promise<any>;
39
44
  }
40
45
  } //# sourceMappingURL=request-locals.d.ts.map
41
46
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"request-locals.d.mts","names":[],"sources":["../../../../../../../auth/src/contracts/request-locals.ts"],"mappings":";;AAyBA;;;;AAA4B;AAAG;;;;;;;;;AAYT;;;;;;;;;;UAZL,WAAA;;;;;;;;;;YAWL,aAAA;IACR,IAAA,GAAO,WAAW;EAAA;AAAA"}
1
+ {"version":3,"file":"request-locals.d.mts","names":[],"sources":["../../../../../../../auth/src/contracts/request-locals.ts"],"mappings":";;AAyBA;;;;AAA4B;AAAG;;;;;;;;;;;AAiBV;;;;;;;;UAjBJ,WAAA;;;;;;;;;;YAWL,aAAA;IACR,IAAA,GAAO,WAAA;;;;;IAKP,OAAA,GAAU,OAAO;EAAA;AAAA"}
@@ -48,6 +48,14 @@ interface AuthRefreshCredentialDescriptor extends AuthCredentialDescriptor {
48
48
  /** Per-route authentication behavior for the object middleware overload. */
49
49
  interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor> {
50
50
  optional?: boolean;
51
+ /**
52
+ * Accept both a header and a cookie credential (at most one of each).
53
+ * Precedence is fixed and independent of array order: a present
54
+ * `Authorization` header wins, an invalid header rejects and never falls back
55
+ * to the cookie, and renewal plus the CSRF Origin check apply only when the
56
+ * cookie is the credential actually used. Cannot be combined with `source`.
57
+ */
58
+ sources?: AuthCredentialDescriptor[];
51
59
  /** Opt-in automatic renewal credential. Cookie sources only. */
52
60
  refresh?: AuthRefreshCredentialDescriptor;
53
61
  redirect?: {
@@ -380,6 +388,11 @@ type CookieAuthConfig = {
380
388
  * @default "access_token"
381
389
  */
382
390
  name?: string;
391
+ /**
392
+ * Cookie name the session helpers write and clear for the refresh token.
393
+ * @default "refresh_token"
394
+ */
395
+ refreshName?: string;
383
396
  /**
384
397
  * Cookie `Path` attribute.
385
398
  * @default "/"
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../auth/src/contracts/types.ts"],"mappings":";;;;;;;;;;;;;;AA2BA;;;;AAA0B;AAO1B;;;;AAAsC;AAGtC;;;;cAVa,aAAA;AAab;;;;AAEK;AAFL,KANY,0BAAA;;KAGA,SAAA;;UAGK,wBAAA;EAC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ChildModel } from \"@warlock.js/cascade\";\r\nimport { type Algorithm } from \"fast-jwt\";\r\nimport type { AccessToken } from \"../models/access-token\";\r\nimport type { Auth } from \"../models/auth.model\";\r\nimport type { OneTimeToken } from \"../models/one-time-token\";\r\nimport type { OtpConfig, PasskeysConfig, ProvidersConfig } from \"./providers\";\r\nimport type { RefreshToken } from \"../models/refresh-token\";\r\n\r\n/**\r\n * Symbol to indicate no expiration for tokens\r\n * Use this when you explicitly want tokens to never expire\r\n *\r\n * @example\r\n * ```typescript\r\n * // src/config/auth.ts\r\n * import { NO_EXPIRATION, type AuthConfigurations } from \"@warlock.js/auth\";\r\n *\r\n * const authConfigurations: AuthConfigurations = {\r\n * accessToken: {\r\n * secret: env(\"JWT_SECRET\"),\r\n * expiresIn: NO_EXPIRATION, // Token expires within 100 years\r\n * },\r\n * };\r\n *\r\n * export default authConfigurations;\r\n * ```\r\n */\r\nexport const NO_EXPIRATION = \"100y\";\r\n\r\n/**\r\n * Behavior when logout is called without a refresh token\r\n * - \"revoke-all\": Revoke all refresh tokens for the user (secure default)\r\n * - \"error\": Return an error requiring the refresh token\r\n */\r\nexport type LogoutWithoutTokenBehavior = \"revoke-all\" | \"error\";\r\n\r\n/** The single request credential source an auth middleware instance accepts. */\r\nexport type TokenFrom = \"header\" | `cookie:${string}`;\r\n\r\n/** One explicitly named credential location accepted by auth middleware. */\r\nexport interface AuthCredentialDescriptor {\r\n source: \"header\" | \"cookie\";\r\n key?: string;\r\n}\r\n\r\n/** Cookie credential and bounded duplicate window for automatic renewal. */\r\nexport interface AuthRefreshCredentialDescriptor extends AuthCredentialDescriptor {\r\n /** Milliseconds; the service clamps this to the 0–10 second range (default 5 seconds). */\r\n overlapMs?: number;\r\n}\r\n\r\n/** Per-route authentication behavior for the object middleware overload. */\r\nexport interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor> {\r\n optional?: boolean;\r\n /** Opt-in automatic renewal credential. Cookie sources only. */\r\n refresh?: AuthRefreshCredentialDescriptor;\r\n redirect?: { to: string; returnUrlParam?: string };\r\n}\r\n\r\n/** Application policy that decides whether a resolved user may authenticate. */\r\nexport type CanAuthenticate = (user: Auth) => boolean | Promise<boolean>;\r\n\r\n/** Password credentials plus the application-defined identity fields. */\r\nexport type AuthCredentials = Record<string, unknown> & {\r\n password: string;\r\n};\r\n\r\n/**\r\n * Access-token configuration.\r\n *\r\n * `secret` may also be supplied via the deprecated `jwt.secret` (resolved by a\r\n * backward-compatible shim); one of the two is required at runtime.\r\n */\r\nexport type AccessTokenConfig = {\r\n /**\r\n * Override the persisted access-token model — extend {@link AccessToken} to\r\n * add columns (e.g. a tenant key) or rename them, then register the subclass\r\n * here. Defaults to the package's `AccessToken`.\r\n */\r\n model?: typeof AccessToken;\r\n /**\r\n * Secret used to sign access tokens.\r\n */\r\n secret?: string;\r\n /**\r\n * JWT algorithm.\r\n * @default \"HS256\"\r\n */\r\n algorithm?: Algorithm;\r\n /**\r\n * Access-token lifetime — a duration string `ms` parses to a **positive**\r\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\r\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\r\n * first token issue: each of them would otherwise sign a token with no `exp`\r\n * claim at all.\r\n * @example \"1h\" or NO_EXPIRATION\r\n * @default \"1h\"\r\n */\r\n expiresIn?: string;\r\n};\r\n\r\n/**\r\n * Refresh-token configuration.\r\n */\r\nexport type RefreshTokenConfig = {\r\n /**\r\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\r\n * Defaults to the package's `RefreshToken`.\r\n */\r\n model?: typeof RefreshToken;\r\n /**\r\n * Enable refresh tokens.\r\n * @default true\r\n */\r\n enabled?: boolean;\r\n /**\r\n * Separate secret for refresh tokens (recommended for security). Falls back\r\n * to the access-token secret when omitted.\r\n */\r\n secret?: string;\r\n /**\r\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\r\n * number of milliseconds; an unusable value throws naming this key on issue\r\n * (see {@link AccessTokenConfig.expiresIn}).\r\n * @example \"7d\" or \"1w\"\r\n * @default \"7d\"\r\n */\r\n expiresIn?: string;\r\n /**\r\n * Rotate the refresh token on each use (old token revoked, replay detected).\r\n * @default true\r\n */\r\n rotation?: boolean;\r\n /**\r\n * Maximum active refresh tokens per user; the oldest are revoked past it.\r\n * @default 5\r\n */\r\n maxPerUser?: number;\r\n /**\r\n * Behavior when logout is called without a refresh token.\r\n * @default \"revoke-all\"\r\n */\r\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\r\n};\r\n\r\n/**\r\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\r\n * deprecation warning.\r\n *\r\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\r\n */\r\nexport type LegacyJwtConfig = {\r\n secret?: string;\r\n algorithm?: Algorithm;\r\n expiresIn?: string;\r\n refresh?: {\r\n secret?: string;\r\n enabled?: boolean;\r\n expiresIn?: string;\r\n rotation?: boolean;\r\n maxPerUser?: number;\r\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\r\n };\r\n};\r\n\r\n/**\r\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\r\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\r\n * to a login page instead of returning the API-style JSON 401.\r\n *\r\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\r\n * always keep the JSON 401 contract regardless of this setting.\r\n */\r\nexport type PageAuthConfig = {\r\n /**\r\n * Login path a guarded page route redirects a logged-out browser to (e.g.\r\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\r\n * behavior is opt-in and backward-compatible.\r\n */\r\n loginPath?: string;\r\n /**\r\n * Query parameter the redirect carries the originally-requested path in, so\r\n * the login flow can send the user back where they were headed.\r\n * @default \"returnUrl\"\r\n */\r\n returnUrlParam?: string;\r\n};\r\n\r\n/**\r\n * Data every email-verification / password-reset notification receives.\r\n */\r\nexport type OneTimeTokenNotificationData = {\r\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\r\n token: string;\r\n /** When the token stops working. */\r\n expiresAt: Date;\r\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\r\n url?: string;\r\n};\r\n\r\n/**\r\n * Anything auth can deliver a token through — a `defineNotification(...)`\r\n * result satisfies it, as does any object with a compatible `send`.\r\n */\r\nexport type AuthNotification = {\r\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\r\n};\r\n\r\n/** Builds the link a token notification points at. */\r\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\r\n\r\n/** Persists a new plaintext password for a user during a password reset. */\r\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\r\n\r\n/**\r\n * Email-verification configuration (`auth.verification`).\r\n */\r\nexport type EmailVerificationConfig = {\r\n /**\r\n * Token lifetime — a positive `ms` duration string.\r\n * @default \"24h\"\r\n */\r\n expiresIn?: string;\r\n /**\r\n * User attribute stamped with the verification `Date`. Declare it in the\r\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\r\n * @default \"emailVerifiedAt\"\r\n */\r\n field?: string;\r\n /** Replace the default verification email. */\r\n notification?: AuthNotification;\r\n /** Build the verification link passed to the notification as `url`. */\r\n url?: OneTimeTokenUrlBuilder;\r\n};\r\n\r\n/**\r\n * Password-reset configuration (`auth.passwordReset`).\r\n */\r\nexport type PasswordResetConfig = {\r\n /**\r\n * Token lifetime — a positive `ms` duration string.\r\n * @default \"60m\"\r\n */\r\n expiresIn?: string;\r\n /**\r\n * User attribute `requestPasswordReset` looks the account up by.\r\n * @default \"email\"\r\n */\r\n identifierField?: string;\r\n /** Replace the default reset email. */\r\n notification?: AuthNotification;\r\n /** Build the reset link passed to the notification as `url`. */\r\n url?: OneTimeTokenUrlBuilder;\r\n /**\r\n * Persist the new password yourself. By default auth saves a hash made by\r\n * the same `hashPassword` login verifies against, and falls back to the\r\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\r\n * the stored value with `verifyPassword` either way.\r\n */\r\n setPassword?: PasswordSetter;\r\n};\r\n\r\n/**\r\n * One-time token storage configuration (`auth.oneTimeToken`).\r\n */\r\nexport type OneTimeTokenConfig = {\r\n /** Override the persisted model — extend {@link OneTimeToken}. */\r\n model?: typeof OneTimeToken;\r\n};\r\n\r\nexport type AuthConfigurations = {\r\n /**\r\n * Define all user types — maps a user-type slug to its `Auth` model class so\r\n * tokens and the middleware can resolve the right model.\r\n */\r\n userType: {\r\n [userType: string]: ChildModel<Auth>;\r\n };\r\n /** Default user type used by `authMiddleware()` and options-only overloads. */\r\n defaultUserType?: string;\r\n /**\r\n * Decide whether a resolved user may authenticate or receive new tokens.\r\n * @default () => true\r\n */\r\n canAuthenticate?: CanAuthenticate;\r\n /**\r\n * Access-token configuration (secret, expiry, algorithm, model override).\r\n */\r\n accessToken?: AccessTokenConfig;\r\n /**\r\n * Refresh-token configuration (rotation, lifetime, cap, model override).\r\n */\r\n refreshToken?: RefreshTokenConfig;\r\n /**\r\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\r\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\r\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\r\n */\r\n pageAuth?: PageAuthConfig;\r\n /**\r\n * Cookie auth session config — read by `authService.setAuthCookie` /\r\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\r\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\r\n */\r\n cookie?: CookieAuthConfig;\r\n /**\r\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\r\n */\r\n csrf?: CsrfConfig;\r\n /**\r\n * Email verification — token lifetime, verified field, notification override.\r\n */\r\n verification?: EmailVerificationConfig;\r\n /**\r\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\r\n */\r\n passwordReset?: PasswordResetConfig;\r\n /**\r\n * One-time token (verification / reset) storage — model override.\r\n */\r\n oneTimeToken?: OneTimeTokenConfig;\r\n /**\r\n * Redirect login providers (`google`, `custom`) and account-linking policy.\r\n */\r\n providers?: ProvidersConfig;\r\n /**\r\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\r\n */\r\n passkeys?: PasskeysConfig;\r\n /**\r\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\r\n */\r\n otp?: OtpConfig;\r\n /**\r\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\r\n */\r\n jwt?: LegacyJwtConfig;\r\n};\r\n\r\nexport type AccessTokenOutput = {\r\n /**\r\n * JWT Token\r\n */\r\n token: string;\r\n /**\r\n * Exprie time in ISO format UTC time\r\n */\r\n expiresAt: string;\r\n};\r\n\r\n/**\r\n * Token pair returned after login or token refresh\r\n */\r\nexport type TokenPair = {\r\n /**\r\n * JWT access token (short-lived)\r\n */\r\n accessToken: AccessTokenOutput;\r\n /**\r\n * JWT refresh token (long-lived)\r\n */\r\n refreshToken?: AccessTokenOutput;\r\n};\r\n\r\n/**\r\n * Device information for session tracking\r\n */\r\nexport type DeviceInfo = {\r\n /**\r\n * User agent string from request\r\n */\r\n userAgent?: string;\r\n /**\r\n * Client IP address\r\n */\r\n ip?: string;\r\n /**\r\n * Optional device identifier\r\n */\r\n deviceId?: string;\r\n /**\r\n * Token family ID (for rotation tracking)\r\n * @internal\r\n */\r\n familyId?: string;\r\n /**\r\n * Access token payload\r\n */\r\n payload?: Record<string, unknown>;\r\n};\r\n\r\nexport type LoginResult<UserType extends Auth> = {\r\n user: UserType;\r\n tokens: TokenPair;\r\n};\r\n\r\n/**\r\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\r\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\r\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\r\n * configurable here — they come from core's `secureCookieDefaults()`, the\r\n * same floor every `response.cookie()` call gets, so a cookie auth session can\r\n * never be weakened to a laxer policy than the framework default.\r\n */\r\nexport type CookieAuthConfig = {\r\n /**\r\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\r\n * `cookie:<name>` token source must match to read it back.\r\n * @default \"access_token\"\r\n */\r\n name?: string;\r\n /**\r\n * Cookie `Path` attribute.\r\n * @default \"/\"\r\n */\r\n path?: string;\r\n};\r\n\r\n/**\r\n * CSRF Origin-check configuration. Read via\r\n * `authConfig.csrf.allowedOrigins()`.\r\n */\r\nexport type CsrfConfig = {\r\n /**\r\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\r\n * in addition to the request's own origin.\r\n * @default []\r\n */\r\n allowedOrigins?: string[];\r\n};\r\n\r\n/**\r\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\r\n * falls back to `auth.cookie.*` config, then the package default. Cookie\r\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\r\n * see {@link CookieAuthConfig}.\r\n */\r\nexport type SetAuthCookieOptions = {\r\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\r\n name?: string;\r\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\r\n path?: string;\r\n /**\r\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\r\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\r\n * bare token string with no `maxAge` produces a session cookie (cleared\r\n * when the browser closes).\r\n */\r\n maxAge?: number;\r\n};\r\n\r\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\r\nexport type ClearAuthCookieOptions = {\r\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\r\n name?: string;\r\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\r\n path?: string;\r\n};\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,gBAAgB"}
1
+ {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../auth/src/contracts/types.ts"],"sourcesContent":["import { type ChildModel } from \"@warlock.js/cascade\";\r\nimport { type Algorithm } from \"fast-jwt\";\r\nimport type { AccessToken } from \"../models/access-token\";\r\nimport type { Auth } from \"../models/auth.model\";\r\nimport type { OneTimeToken } from \"../models/one-time-token\";\r\nimport type { OtpConfig, PasskeysConfig, ProvidersConfig } from \"./providers\";\r\nimport type { RefreshToken } from \"../models/refresh-token\";\r\n\r\n/**\r\n * Symbol to indicate no expiration for tokens\r\n * Use this when you explicitly want tokens to never expire\r\n *\r\n * @example\r\n * ```typescript\r\n * // src/config/auth.ts\r\n * import { NO_EXPIRATION, type AuthConfigurations } from \"@warlock.js/auth\";\r\n *\r\n * const authConfigurations: AuthConfigurations = {\r\n * accessToken: {\r\n * secret: env(\"JWT_SECRET\"),\r\n * expiresIn: NO_EXPIRATION, // Token expires within 100 years\r\n * },\r\n * };\r\n *\r\n * export default authConfigurations;\r\n * ```\r\n */\r\nexport const NO_EXPIRATION = \"100y\";\r\n\r\n/**\r\n * Behavior when logout is called without a refresh token\r\n * - \"revoke-all\": Revoke all refresh tokens for the user (secure default)\r\n * - \"error\": Return an error requiring the refresh token\r\n */\r\nexport type LogoutWithoutTokenBehavior = \"revoke-all\" | \"error\";\r\n\r\n/** The single request credential source an auth middleware instance accepts. */\r\nexport type TokenFrom = \"header\" | `cookie:${string}`;\r\n\r\n/** One explicitly named credential location accepted by auth middleware. */\r\nexport interface AuthCredentialDescriptor {\r\n source: \"header\" | \"cookie\";\r\n key?: string;\r\n}\r\n\r\n/** Cookie credential and bounded duplicate window for automatic renewal. */\r\nexport interface AuthRefreshCredentialDescriptor extends AuthCredentialDescriptor {\r\n /** Milliseconds; the service clamps this to the 0–10 second range (default 5 seconds). */\r\n overlapMs?: number;\r\n}\r\n\r\n/** Per-route authentication behavior for the object middleware overload. */\r\nexport interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor> {\r\n optional?: boolean;\r\n /**\r\n * Accept both a header and a cookie credential (at most one of each).\r\n * Precedence is fixed and independent of array order: a present\r\n * `Authorization` header wins, an invalid header rejects and never falls back\r\n * to the cookie, and renewal plus the CSRF Origin check apply only when the\r\n * cookie is the credential actually used. Cannot be combined with `source`.\r\n */\r\n sources?: AuthCredentialDescriptor[];\r\n /** Opt-in automatic renewal credential. Cookie sources only. */\r\n refresh?: AuthRefreshCredentialDescriptor;\r\n redirect?: { to: string; returnUrlParam?: string };\r\n}\r\n\r\n/** Application policy that decides whether a resolved user may authenticate. */\r\nexport type CanAuthenticate = (user: Auth) => boolean | Promise<boolean>;\r\n\r\n/** Password credentials plus the application-defined identity fields. */\r\nexport type AuthCredentials = Record<string, unknown> & {\r\n password: string;\r\n};\r\n\r\n/**\r\n * Access-token configuration.\r\n *\r\n * `secret` may also be supplied via the deprecated `jwt.secret` (resolved by a\r\n * backward-compatible shim); one of the two is required at runtime.\r\n */\r\nexport type AccessTokenConfig = {\r\n /**\r\n * Override the persisted access-token model — extend {@link AccessToken} to\r\n * add columns (e.g. a tenant key) or rename them, then register the subclass\r\n * here. Defaults to the package's `AccessToken`.\r\n */\r\n model?: typeof AccessToken;\r\n /**\r\n * Secret used to sign access tokens.\r\n */\r\n secret?: string;\r\n /**\r\n * JWT algorithm.\r\n * @default \"HS256\"\r\n */\r\n algorithm?: Algorithm;\r\n /**\r\n * Access-token lifetime — a duration string `ms` parses to a **positive**\r\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\r\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\r\n * first token issue: each of them would otherwise sign a token with no `exp`\r\n * claim at all.\r\n * @example \"1h\" or NO_EXPIRATION\r\n * @default \"1h\"\r\n */\r\n expiresIn?: string;\r\n};\r\n\r\n/**\r\n * Refresh-token configuration.\r\n */\r\nexport type RefreshTokenConfig = {\r\n /**\r\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\r\n * Defaults to the package's `RefreshToken`.\r\n */\r\n model?: typeof RefreshToken;\r\n /**\r\n * Enable refresh tokens.\r\n * @default true\r\n */\r\n enabled?: boolean;\r\n /**\r\n * Separate secret for refresh tokens (recommended for security). Falls back\r\n * to the access-token secret when omitted.\r\n */\r\n secret?: string;\r\n /**\r\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\r\n * number of milliseconds; an unusable value throws naming this key on issue\r\n * (see {@link AccessTokenConfig.expiresIn}).\r\n * @example \"7d\" or \"1w\"\r\n * @default \"7d\"\r\n */\r\n expiresIn?: string;\r\n /**\r\n * Rotate the refresh token on each use (old token revoked, replay detected).\r\n * @default true\r\n */\r\n rotation?: boolean;\r\n /**\r\n * Maximum active refresh tokens per user; the oldest are revoked past it.\r\n * @default 5\r\n */\r\n maxPerUser?: number;\r\n /**\r\n * Behavior when logout is called without a refresh token.\r\n * @default \"revoke-all\"\r\n */\r\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\r\n};\r\n\r\n/**\r\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\r\n * deprecation warning.\r\n *\r\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\r\n */\r\nexport type LegacyJwtConfig = {\r\n secret?: string;\r\n algorithm?: Algorithm;\r\n expiresIn?: string;\r\n refresh?: {\r\n secret?: string;\r\n enabled?: boolean;\r\n expiresIn?: string;\r\n rotation?: boolean;\r\n maxPerUser?: number;\r\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\r\n };\r\n};\r\n\r\n/**\r\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\r\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\r\n * to a login page instead of returning the API-style JSON 401.\r\n *\r\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\r\n * always keep the JSON 401 contract regardless of this setting.\r\n */\r\nexport type PageAuthConfig = {\r\n /**\r\n * Login path a guarded page route redirects a logged-out browser to (e.g.\r\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\r\n * behavior is opt-in and backward-compatible.\r\n */\r\n loginPath?: string;\r\n /**\r\n * Query parameter the redirect carries the originally-requested path in, so\r\n * the login flow can send the user back where they were headed.\r\n * @default \"returnUrl\"\r\n */\r\n returnUrlParam?: string;\r\n};\r\n\r\n/**\r\n * Data every email-verification / password-reset notification receives.\r\n */\r\nexport type OneTimeTokenNotificationData = {\r\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\r\n token: string;\r\n /** When the token stops working. */\r\n expiresAt: Date;\r\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\r\n url?: string;\r\n};\r\n\r\n/**\r\n * Anything auth can deliver a token through — a `defineNotification(...)`\r\n * result satisfies it, as does any object with a compatible `send`.\r\n */\r\nexport type AuthNotification = {\r\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\r\n};\r\n\r\n/** Builds the link a token notification points at. */\r\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\r\n\r\n/** Persists a new plaintext password for a user during a password reset. */\r\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\r\n\r\n/**\r\n * Email-verification configuration (`auth.verification`).\r\n */\r\nexport type EmailVerificationConfig = {\r\n /**\r\n * Token lifetime — a positive `ms` duration string.\r\n * @default \"24h\"\r\n */\r\n expiresIn?: string;\r\n /**\r\n * User attribute stamped with the verification `Date`. Declare it in the\r\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\r\n * @default \"emailVerifiedAt\"\r\n */\r\n field?: string;\r\n /** Replace the default verification email. */\r\n notification?: AuthNotification;\r\n /** Build the verification link passed to the notification as `url`. */\r\n url?: OneTimeTokenUrlBuilder;\r\n};\r\n\r\n/**\r\n * Password-reset configuration (`auth.passwordReset`).\r\n */\r\nexport type PasswordResetConfig = {\r\n /**\r\n * Token lifetime — a positive `ms` duration string.\r\n * @default \"60m\"\r\n */\r\n expiresIn?: string;\r\n /**\r\n * User attribute `requestPasswordReset` looks the account up by.\r\n * @default \"email\"\r\n */\r\n identifierField?: string;\r\n /** Replace the default reset email. */\r\n notification?: AuthNotification;\r\n /** Build the reset link passed to the notification as `url`. */\r\n url?: OneTimeTokenUrlBuilder;\r\n /**\r\n * Persist the new password yourself. By default auth saves a hash made by\r\n * the same `hashPassword` login verifies against, and falls back to the\r\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\r\n * the stored value with `verifyPassword` either way.\r\n */\r\n setPassword?: PasswordSetter;\r\n};\r\n\r\n/**\r\n * One-time token storage configuration (`auth.oneTimeToken`).\r\n */\r\nexport type OneTimeTokenConfig = {\r\n /** Override the persisted model — extend {@link OneTimeToken}. */\r\n model?: typeof OneTimeToken;\r\n};\r\n\r\nexport type AuthConfigurations = {\r\n /**\r\n * Define all user types — maps a user-type slug to its `Auth` model class so\r\n * tokens and the middleware can resolve the right model.\r\n */\r\n userType: {\r\n [userType: string]: ChildModel<Auth>;\r\n };\r\n /** Default user type used by `authMiddleware()` and options-only overloads. */\r\n defaultUserType?: string;\r\n /**\r\n * Decide whether a resolved user may authenticate or receive new tokens.\r\n * @default () => true\r\n */\r\n canAuthenticate?: CanAuthenticate;\r\n /**\r\n * Access-token configuration (secret, expiry, algorithm, model override).\r\n */\r\n accessToken?: AccessTokenConfig;\r\n /**\r\n * Refresh-token configuration (rotation, lifetime, cap, model override).\r\n */\r\n refreshToken?: RefreshTokenConfig;\r\n /**\r\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\r\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\r\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\r\n */\r\n pageAuth?: PageAuthConfig;\r\n /**\r\n * Cookie auth session config — read by `authService.setAuthCookie` /\r\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\r\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\r\n */\r\n cookie?: CookieAuthConfig;\r\n /**\r\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\r\n */\r\n csrf?: CsrfConfig;\r\n /**\r\n * Email verification — token lifetime, verified field, notification override.\r\n */\r\n verification?: EmailVerificationConfig;\r\n /**\r\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\r\n */\r\n passwordReset?: PasswordResetConfig;\r\n /**\r\n * One-time token (verification / reset) storage — model override.\r\n */\r\n oneTimeToken?: OneTimeTokenConfig;\r\n /**\r\n * Redirect login providers (`google`, `custom`) and account-linking policy.\r\n */\r\n providers?: ProvidersConfig;\r\n /**\r\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\r\n */\r\n passkeys?: PasskeysConfig;\r\n /**\r\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\r\n */\r\n otp?: OtpConfig;\r\n /**\r\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\r\n */\r\n jwt?: LegacyJwtConfig;\r\n};\r\n\r\nexport type AccessTokenOutput = {\r\n /**\r\n * JWT Token\r\n */\r\n token: string;\r\n /**\r\n * Exprie time in ISO format UTC time\r\n */\r\n expiresAt: string;\r\n};\r\n\r\n/**\r\n * Token pair returned after login or token refresh\r\n */\r\nexport type TokenPair = {\r\n /**\r\n * JWT access token (short-lived)\r\n */\r\n accessToken: AccessTokenOutput;\r\n /**\r\n * JWT refresh token (long-lived)\r\n */\r\n refreshToken?: AccessTokenOutput;\r\n};\r\n\r\n/**\r\n * Device information for session tracking\r\n */\r\nexport type DeviceInfo = {\r\n /**\r\n * User agent string from request\r\n */\r\n userAgent?: string;\r\n /**\r\n * Client IP address\r\n */\r\n ip?: string;\r\n /**\r\n * Optional device identifier\r\n */\r\n deviceId?: string;\r\n /**\r\n * Token family ID (for rotation tracking)\r\n * @internal\r\n */\r\n familyId?: string;\r\n /**\r\n * Access token payload\r\n */\r\n payload?: Record<string, unknown>;\r\n};\r\n\r\nexport type LoginResult<UserType extends Auth> = {\r\n user: UserType;\r\n tokens: TokenPair;\r\n};\r\n\r\n/**\r\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\r\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\r\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\r\n * configurable here — they come from core's `secureCookieDefaults()`, the\r\n * same floor every `response.cookie()` call gets, so a cookie auth session can\r\n * never be weakened to a laxer policy than the framework default.\r\n */\r\nexport type CookieAuthConfig = {\r\n /**\r\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\r\n * `cookie:<name>` token source must match to read it back.\r\n * @default \"access_token\"\r\n */\r\n name?: string;\r\n /**\r\n * Cookie name the session helpers write and clear for the refresh token.\r\n * @default \"refresh_token\"\r\n */\r\n refreshName?: string;\r\n /**\r\n * Cookie `Path` attribute.\r\n * @default \"/\"\r\n */\r\n path?: string;\r\n};\r\n\r\n/**\r\n * CSRF Origin-check configuration. Read via\r\n * `authConfig.csrf.allowedOrigins()`.\r\n */\r\nexport type CsrfConfig = {\r\n /**\r\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\r\n * in addition to the request's own origin.\r\n * @default []\r\n */\r\n allowedOrigins?: string[];\r\n};\r\n\r\n/**\r\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\r\n * falls back to `auth.cookie.*` config, then the package default. Cookie\r\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\r\n * see {@link CookieAuthConfig}.\r\n */\r\nexport type SetAuthCookieOptions = {\r\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\r\n name?: string;\r\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\r\n path?: string;\r\n /**\r\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\r\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\r\n * bare token string with no `maxAge` produces a session cookie (cleared\r\n * when the browser closes).\r\n */\r\n maxAge?: number;\r\n};\r\n\r\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\r\nexport type ClearAuthCookieOptions = {\r\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\r\n name?: string;\r\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\r\n path?: string;\r\n};\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,gBAAgB"}
package/esm/index.d.mts CHANGED
@@ -50,7 +50,9 @@ import { TokenType, TokenTypeError, isInvalidCredentialError, jwt } from "./serv
50
50
  import { isEmailVerified, sendEmailVerification, verifyEmail } from "./services/email-verification.mjs";
51
51
  import { IssuedOneTimeToken, consumeOneTimeToken, hashOneTimeToken, issueOneTimeToken, oneTimeTokenModel } from "./services/one-time-tokens.mjs";
52
52
  import { requestPasswordReset, resetPassword } from "./services/password-reset.mjs";
53
+ import { RequestUserFailure, RequestUserOutcome, ResolveRequestUserOptions, readCredential, resolveRequestUser, resolveRequestUserOutcome } from "./services/resolve-request-user.mjs";
54
+ import { PageSessionOptions, PageSessionResolver, SessionMiddlewareOptions, SessionResolverOptions, SessionSource, pageSession, sessionMiddleware } from "./session/page-session.mjs";
53
55
  import { safeEqual } from "./utils/safe-equal.mjs";
54
56
  import { isNeverExpiring, isUsableExpiry, tokenHasExpClaim } from "./utils/token-expiry.mjs";
55
- export { APPLE_AUTH_FEATURE, AccessToken, AccessTokenConfig, AccessTokenOutput, AppleJoseModule, AppleProvider, AppleProviderConfig, Auth, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthErrorCodes, AuthErrorTranslations, AuthEventCallback, AuthEventName, AuthEventPayloads, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthProviderSdkMissingError, AuthRefreshCredentialDescriptor, AuthTokenFamily, AuthTranslations, Authenticable, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CsrfConfig, CsrfOriginMismatchError, CsrfOriginMismatchReason, DeviceInfo, DiscordProvider, DiscordProviderConfig, EmailNotVerifiedError, EmailVerificationConfig, FacebookProvider, FacebookProviderConfig, GOOGLE_AUTH_FEATURE, GitHubProvider, GitHubProviderConfig, GoogleProvider, GoogleProviderConfig, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, IssuedOneTimeToken, JoseModule, LINKEDIN_AUTH_FEATURE, LegacyJwtConfig, LinkedInProvider, LinkedInProviderConfig, LoginResult, LoginThrottleIdentifier, LoginThrottleOptions, LogoutWithoutTokenBehavior, NO_EXPIRATION, NotificationsUnavailableError, OneTimeToken, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenPurpose, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PasskeyCredential, type PasskeyOptionsJSON, type PasskeyResponseJSON, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAccount, ProviderAuthorizationState, ProviderCallbackParams, ProviderEmailNotVerifiedError, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshToken, RefreshTokenConfig, RefreshTokenIssueOptions, RequestUser, SetAuthCookieOptions, TokenFrom, TokenPair, TokenType, TokenTypeError, XProvider, XProviderConfig, accessTokenSchema, assertCsrfOriginAllowed, authDefaultTranslations, authEvents, authMiddleware, authMigrations, authService, authTokenFamilySchema, completeProviderLogin, consumeOneTimeToken, currentUser, generateJWTSecret, generatePasskeyAuthenticationOptions, generatePasskeyRegistrationOptions, hashOneTimeToken, isEmailVerified, isInvalidCredentialError, isNeverExpiring, isUsableExpiry, issueOneTimeToken, jwt, loginThrottleMiddleware, oneTimeTokenModel, oneTimeTokenSchema, otpRequestThrottleMiddleware, otpVerifyThrottleMiddleware, passkeyCredentialSchema, pkceChallenge, providerAccountSchema, refreshTokenSchema, registerAuthCleanupCommand, registerAuthPurgeNeverExpiringCommand, registerAuthTranslations, registerJWTSecretGeneratorCommand, requestOtp, requestPasswordReset, requireVerifiedEmail, requiresCsrfOriginCheck, resetPassword, resolveAuthProvider, safeEqual, sendEmailVerification, startProviderLogin, tokenConsumeThrottleMiddleware, tokenHasExpClaim, tokenIssueThrottleMiddleware, verifyEmail, verifyOtp, verifyPasskeyAuthentication, verifyPasskeyRegistration };
57
+ export { APPLE_AUTH_FEATURE, AccessToken, AccessTokenConfig, AccessTokenOutput, AppleJoseModule, AppleProvider, AppleProviderConfig, Auth, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthErrorCodes, AuthErrorTranslations, AuthEventCallback, AuthEventName, AuthEventPayloads, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthProviderSdkMissingError, AuthRefreshCredentialDescriptor, AuthTokenFamily, AuthTranslations, Authenticable, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CsrfConfig, CsrfOriginMismatchError, CsrfOriginMismatchReason, DeviceInfo, DiscordProvider, DiscordProviderConfig, EmailNotVerifiedError, EmailVerificationConfig, FacebookProvider, FacebookProviderConfig, GOOGLE_AUTH_FEATURE, GitHubProvider, GitHubProviderConfig, GoogleProvider, GoogleProviderConfig, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, IssuedOneTimeToken, JoseModule, LINKEDIN_AUTH_FEATURE, LegacyJwtConfig, LinkedInProvider, LinkedInProviderConfig, LoginResult, LoginThrottleIdentifier, LoginThrottleOptions, LogoutWithoutTokenBehavior, NO_EXPIRATION, NotificationsUnavailableError, OneTimeToken, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenPurpose, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PageSessionOptions, PageSessionResolver, PasskeyCredential, type PasskeyOptionsJSON, type PasskeyResponseJSON, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAccount, ProviderAuthorizationState, ProviderCallbackParams, ProviderEmailNotVerifiedError, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshToken, RefreshTokenConfig, RefreshTokenIssueOptions, RequestUser, RequestUserFailure, RequestUserOutcome, ResolveRequestUserOptions, SessionMiddlewareOptions, SessionResolverOptions, SessionSource, SetAuthCookieOptions, TokenFrom, TokenPair, TokenType, TokenTypeError, XProvider, XProviderConfig, accessTokenSchema, assertCsrfOriginAllowed, authDefaultTranslations, authEvents, authMiddleware, authMigrations, authService, authTokenFamilySchema, completeProviderLogin, consumeOneTimeToken, currentUser, generateJWTSecret, generatePasskeyAuthenticationOptions, generatePasskeyRegistrationOptions, hashOneTimeToken, isEmailVerified, isInvalidCredentialError, isNeverExpiring, isUsableExpiry, issueOneTimeToken, jwt, loginThrottleMiddleware, oneTimeTokenModel, oneTimeTokenSchema, otpRequestThrottleMiddleware, otpVerifyThrottleMiddleware, pageSession, passkeyCredentialSchema, pkceChallenge, providerAccountSchema, readCredential, refreshTokenSchema, registerAuthCleanupCommand, registerAuthPurgeNeverExpiringCommand, registerAuthTranslations, registerJWTSecretGeneratorCommand, requestOtp, requestPasswordReset, requireVerifiedEmail, requiresCsrfOriginCheck, resetPassword, resolveAuthProvider, resolveRequestUser, resolveRequestUserOutcome, safeEqual, sendEmailVerification, sessionMiddleware, startProviderLogin, tokenConsumeThrottleMiddleware, tokenHasExpClaim, tokenIssueThrottleMiddleware, verifyEmail, verifyOtp, verifyPasskeyAuthentication, verifyPasskeyRegistration };
56
58
  import "./contracts/request-locals.mjs";
package/esm/index.mjs CHANGED
@@ -1,13 +1,14 @@
1
1
  import { authDefaultTranslations } from "./localization/auth-default-translations.mjs";
2
2
  import { registerAuthTranslations } from "./localization/register-auth-translations.mjs";
3
3
  import "./localization/init.mjs";
4
+ import { AuthErrorCodes } from "./utils/auth-error-codes.mjs";
5
+ import { CsrfOriginMismatchError, assertCsrfOriginAllowed, requiresCsrfOriginCheck } from "./middleware/csrf-origin-check.mjs";
4
6
  import { isNeverExpiring, isUsableExpiry, tokenHasExpClaim } from "./utils/token-expiry.mjs";
5
7
  import { AccessToken, accessTokenSchema } from "./models/access-token/access-token.model.mjs";
6
8
  import { AuthTokenFamily, authTokenFamilySchema } from "./models/auth-token-family/auth-token-family.model.mjs";
7
9
  import { OneTimeToken, oneTimeTokenSchema } from "./models/one-time-token/one-time-token.model.mjs";
8
10
  import { RefreshToken, refreshTokenSchema } from "./models/refresh-token/refresh-token.model.mjs";
9
11
  import { authEvents } from "./services/auth-events.mjs";
10
- import { AuthErrorCodes } from "./utils/auth-error-codes.mjs";
11
12
  import { TokenTypeError, isInvalidCredentialError, jwt } from "./services/jwt.mjs";
12
13
  import { authService } from "./services/auth.service.mjs";
13
14
  import { registerAuthCleanupCommand } from "./commands/auth-cleanup-command.mjs";
@@ -24,7 +25,7 @@ import { NotificationsUnavailableError } from "./errors/notifications-unavailabl
24
25
  import { ProviderEmailNotVerifiedError } from "./errors/provider-email-not-verified.error.mjs";
25
26
  import "./errors/index.mjs";
26
27
  import "./localization/index.mjs";
27
- import { CsrfOriginMismatchError, assertCsrfOriginAllowed, requiresCsrfOriginCheck } from "./middleware/csrf-origin-check.mjs";
28
+ import { readCredential, resolveRequestUser, resolveRequestUserOutcome } from "./services/resolve-request-user.mjs";
28
29
  import { authMiddleware } from "./middleware/auth.middleware.mjs";
29
30
  import { loginThrottleMiddleware } from "./middleware/login-throttle.middleware.mjs";
30
31
  import { tokenConsumeThrottleMiddleware, tokenIssueThrottleMiddleware } from "./middleware/one-time-token-throttle.middleware.mjs";
@@ -55,6 +56,8 @@ import { LINKEDIN_AUTH_FEATURE, LinkedInProvider } from "./providers/linkedin-pr
55
56
  import { XProvider } from "./providers/x-provider.mjs";
56
57
  import { completeProviderLogin, resolveAuthProvider, startProviderLogin } from "./providers/provider-login.mjs";
57
58
  import "./providers/index.mjs";
59
+ import { pageSession, sessionMiddleware } from "./session/page-session.mjs";
60
+ import "./session/index.mjs";
58
61
  import "./utils/index.mjs";
59
62
 
60
- export { APPLE_AUTH_FEATURE, AccessToken, AppleProvider, Auth, AuthErrorCodes, AuthProviderSdkMissingError, AuthTokenFamily, CsrfOriginMismatchError, DiscordProvider, EmailNotVerifiedError, FacebookProvider, GOOGLE_AUTH_FEATURE, GitHubProvider, GoogleProvider, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, LINKEDIN_AUTH_FEATURE, LinkedInProvider, NO_EXPIRATION, NotificationsUnavailableError, OneTimeToken, PasskeyCredential, ProviderAccount, ProviderEmailNotVerifiedError, RefreshToken, TokenTypeError, XProvider, accessTokenSchema, assertCsrfOriginAllowed, authDefaultTranslations, authEvents, authMiddleware, authMigrations, authService, authTokenFamilySchema, completeProviderLogin, consumeOneTimeToken, currentUser, generateJWTSecret, generatePasskeyAuthenticationOptions, generatePasskeyRegistrationOptions, hashOneTimeToken, isEmailVerified, isInvalidCredentialError, isNeverExpiring, isUsableExpiry, issueOneTimeToken, jwt, loginThrottleMiddleware, oneTimeTokenModel, oneTimeTokenSchema, otpRequestThrottleMiddleware, otpVerifyThrottleMiddleware, passkeyCredentialSchema, pkceChallenge, providerAccountSchema, refreshTokenSchema, registerAuthCleanupCommand, registerAuthPurgeNeverExpiringCommand, registerAuthTranslations, registerJWTSecretGeneratorCommand, requestOtp, requestPasswordReset, requireVerifiedEmail, requiresCsrfOriginCheck, resetPassword, resolveAuthProvider, safeEqual, sendEmailVerification, startProviderLogin, tokenConsumeThrottleMiddleware, tokenHasExpClaim, tokenIssueThrottleMiddleware, verifyEmail, verifyOtp, verifyPasskeyAuthentication, verifyPasskeyRegistration };
63
+ export { APPLE_AUTH_FEATURE, AccessToken, AppleProvider, Auth, AuthErrorCodes, AuthProviderSdkMissingError, AuthTokenFamily, CsrfOriginMismatchError, DiscordProvider, EmailNotVerifiedError, FacebookProvider, GOOGLE_AUTH_FEATURE, GitHubProvider, GoogleProvider, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, LINKEDIN_AUTH_FEATURE, LinkedInProvider, NO_EXPIRATION, NotificationsUnavailableError, OneTimeToken, PasskeyCredential, ProviderAccount, ProviderEmailNotVerifiedError, RefreshToken, TokenTypeError, XProvider, accessTokenSchema, assertCsrfOriginAllowed, authDefaultTranslations, authEvents, authMiddleware, authMigrations, authService, authTokenFamilySchema, completeProviderLogin, consumeOneTimeToken, currentUser, generateJWTSecret, generatePasskeyAuthenticationOptions, generatePasskeyRegistrationOptions, hashOneTimeToken, isEmailVerified, isInvalidCredentialError, isNeverExpiring, isUsableExpiry, issueOneTimeToken, jwt, loginThrottleMiddleware, oneTimeTokenModel, oneTimeTokenSchema, otpRequestThrottleMiddleware, otpVerifyThrottleMiddleware, pageSession, passkeyCredentialSchema, pkceChallenge, providerAccountSchema, readCredential, refreshTokenSchema, registerAuthCleanupCommand, registerAuthPurgeNeverExpiringCommand, registerAuthTranslations, registerJWTSecretGeneratorCommand, requestOtp, requestPasswordReset, requireVerifiedEmail, requiresCsrfOriginCheck, resetPassword, resolveAuthProvider, resolveRequestUser, resolveRequestUserOutcome, safeEqual, sendEmailVerification, sessionMiddleware, startProviderLogin, tokenConsumeThrottleMiddleware, tokenHasExpClaim, tokenIssueThrottleMiddleware, verifyEmail, verifyOtp, verifyPasskeyAuthentication, verifyPasskeyRegistration };
@@ -1 +1 @@
1
- {"version":3,"file":"auth.middleware.d.mts","names":[],"sources":["../../../../../../../auth/src/middleware/auth.middleware.ts"],"mappings":";;;;;;AAsJA;;;;AAA4C;AAC5C;;;;;;;;AAA0E;AAC1E;;;;;iBAFgB,cAAA,IAAkB,UAAU;AAAA,iBAC5B,cAAA,CAAe,OAAA,EAAS,qBAAA,GAAwB,UAAU;AAAA,iBAC1D,cAAA,CACd,eAAA,qBACA,OAAA,GAAU,qBAAA,GACT,UAAU;AAAA,iBACG,cAAA,CACd,eAAA,qBACA,SAAA,GAAY,SAAA,GACX,UAAU"}
1
+ {"version":3,"file":"auth.middleware.d.mts","names":[],"sources":["../../../../../../../auth/src/middleware/auth.middleware.ts"],"mappings":";;;;;;AA8GA;;;;AAA4C;AAC5C;;;;;;;;AAA0E;AAC1E;;;;;iBAFgB,cAAA,IAAkB,UAAU;AAAA,iBAC5B,cAAA,CAAe,OAAA,EAAS,qBAAA,GAAwB,UAAU;AAAA,iBAC1D,cAAA,CACd,eAAA,qBACA,OAAA,GAAU,qBAAA,GACT,UAAU;AAAA,iBACG,cAAA,CACd,eAAA,qBACA,SAAA,GAAY,SAAA,GACX,UAAU"}
@@ -1,10 +1,7 @@
1
- import { AccessToken } from "../models/access-token/access-token.model.mjs";
2
- import "../models/access-token/index.mjs";
3
- import { authConfig } from "../services/auth-config.mjs";
4
1
  import { AuthErrorCodes } from "../utils/auth-error-codes.mjs";
5
- import { isInvalidCredentialError, jwt } from "../services/jwt.mjs";
6
- import { authService } from "../services/auth.service.mjs";
7
2
  import { CsrfOriginMismatchError, assertCsrfOriginAllowed, requiresCsrfOriginCheck } from "./csrf-origin-check.mjs";
3
+ import { authConfig } from "../services/auth-config.mjs";
4
+ import { readCredential, resolveRequestUserOutcome } from "../services/resolve-request-user.mjs";
8
5
  import { localizedLoginPath } from "./localized-login-path.mjs";
9
6
  import { config, t } from "@warlock.js/core";
10
7
  import { log } from "@warlock.js/logger";
@@ -39,29 +36,6 @@ function rejectUnauthorized({ request, response }, payload, redirect) {
39
36
  }
40
37
  return response.unauthorized(payload);
41
38
  }
42
- /**
43
- * Whether the persisted row says the token is dead.
44
- *
45
- * The answer belongs to the model (`AccessToken.isExpired`), so a registered
46
- * override that renames or reshapes its expiry column stays authoritative and
47
- * the middleware never touches a column name. A row that cannot answer at all —
48
- * an override that dropped the getter — is treated as **expired**: the failure
49
- * mode of this whole defect class was a check that quietly answered "fine" when
50
- * it had nothing to check, and that is not repeated here.
51
- *
52
- * This is independent of the `exp` claim required by `jwt.verify`. That guard
53
- * catches a token whose *claims* carry no deadline; this one catches a token
54
- * whose *row* says the deadline has passed — a logged-out or expired session
55
- * whose JWT is still within its own lifetime. Neither subsumes the other.
56
- */
57
- function accessTokenRowIsExpired(accessToken) {
58
- return typeof accessToken.isExpired === "boolean" ? accessToken.isExpired : true;
59
- }
60
- function readCredential(request, tokenFrom) {
61
- if (tokenFrom === "header") return request.authorizationValue;
62
- const value = request.cookie(tokenFrom.slice(7));
63
- return value ? String(value) : "";
64
- }
65
39
  function tokenFromDescriptor(descriptor) {
66
40
  if (!descriptor.source || descriptor.source === "header") return "header";
67
41
  if (!descriptor.key) throw new Error("authMiddleware cookie credentials require a cookie key.");
@@ -79,7 +53,13 @@ function resolveAllowedTypes(value) {
79
53
  function authMiddleware(userTypeOrOptions, legacyTokenFromOrOptions) {
80
54
  const options = typeof userTypeOrOptions === "object" && !Array.isArray(userTypeOrOptions) ? userTypeOrOptions : typeof legacyTokenFromOrOptions === "object" ? legacyTokenFromOrOptions : void 0;
81
55
  const allowedTypes = resolveAllowedTypes(typeof userTypeOrOptions === "string" || Array.isArray(userTypeOrOptions) ? userTypeOrOptions : void 0);
82
- const tokenFrom = options ? tokenFromDescriptor(options) : (typeof legacyTokenFromOrOptions === "string" ? legacyTokenFromOrOptions : void 0) ?? "header";
56
+ const legacyTokenFrom = typeof legacyTokenFromOrOptions === "string" ? legacyTokenFromOrOptions : void 0;
57
+ const dualSources = options?.sources?.length ? options.sources.map(tokenFromDescriptor) : void 0;
58
+ if (dualSources && options?.source) throw new Error("authMiddleware accepts either `source` or `sources`, not both.");
59
+ const dualHeader = dualSources?.includes("header") ?? false;
60
+ const dualCookies = dualSources?.filter((source) => source !== "header") ?? [];
61
+ if (dualSources && (dualCookies.length > 1 || dualSources.length - dualCookies.length > 1)) throw new Error("authMiddleware `sources` accepts at most one header and one cookie.");
62
+ const tokenFrom = dualSources ? dualCookies[0] ?? "header" : options ? tokenFromDescriptor(options) : legacyTokenFrom ?? "header";
83
63
  const refreshCredential = options?.refresh ? tokenFromDescriptor(options.refresh) : void 0;
84
64
  const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : void 0;
85
65
  if (refreshCredential && (tokenFrom === "header" || refreshCredential === "header" || !renewalUserType)) throw new Error("authMiddleware automatic renewal requires one allowed user type and cookie access and refresh credentials.");
@@ -89,9 +69,10 @@ function authMiddleware(userTypeOrOptions, legacyTokenFromOrOptions) {
89
69
  request,
90
70
  response
91
71
  }, payload, options?.redirect);
92
- let authorizationValue = readCredential(request, tokenFrom);
93
- let renewalAttempted = false;
94
- if ((authorizationValue || refreshCredential) && requiresCsrfOriginCheck(tokenFrom, request.method)) try {
72
+ const headerWins = dualHeader && Boolean(request.authorizationValue);
73
+ const usedTokenFrom = headerWins ? "header" : tokenFrom;
74
+ const usedRefresh = headerWins ? void 0 : refreshCredential;
75
+ if ((readCredential(request, usedTokenFrom) || usedRefresh) && requiresCsrfOriginCheck(usedTokenFrom, request.method)) try {
95
76
  assertCsrfOriginAllowed(request);
96
77
  } catch (error) {
97
78
  if (!(error instanceof CsrfOriginMismatchError)) throw error;
@@ -101,92 +82,34 @@ function authMiddleware(userTypeOrOptions, legacyTokenFromOrOptions) {
101
82
  errorCode: "EC006"
102
83
  });
103
84
  }
104
- const renew = async () => {
105
- if (!refreshCredential || renewalAttempted) return false;
106
- renewalAttempted = true;
107
- const refreshToken = readCredential(request, refreshCredential);
108
- if (!refreshToken) return false;
109
- const pair = await authService.renewAutomaticSession(refreshToken, renewalUserType, { overlapMs: options?.refresh?.overlapMs });
110
- if (!pair?.refreshToken) return false;
111
- authService.setAuthCookie(response, pair.accessToken, { name: tokenFrom.slice(7) });
112
- authService.setAuthCookie(response, pair.refreshToken, { name: refreshCredential.slice(7) });
113
- authorizationValue = pair.accessToken.token;
114
- return true;
115
- };
116
- let decoded;
117
- let accessToken;
118
- while (true) {
119
- if (!authorizationValue) {
120
- request.locals.user = void 0;
121
- if (await renew()) continue;
122
- if (optional) return;
123
- return reject({
124
- error: t("auth.errors.missingAccessToken"),
125
- errorCode: "EC001"
126
- });
127
- }
128
- try {
129
- decoded = await jwt.verify(authorizationValue);
130
- } catch (error) {
131
- if (!isInvalidCredentialError(error)) throw error;
132
- log.error("http", "auth", error);
133
- request.locals.user = void 0;
134
- if (await renew()) continue;
135
- if (optional) return;
136
- return reject({
137
- error: t("auth.errors.invalidAccessToken"),
138
- errorCode: "EC002"
139
- });
140
- }
141
- request.decodedAccessToken = decoded;
142
- accessToken = await config.key("auth.accessToken.model", AccessToken).findByToken(authorizationValue);
143
- if (!accessToken) {
144
- request.locals.user = void 0;
145
- if (await renew()) continue;
146
- if (optional) return;
147
- return reject({
148
- error: t("auth.errors.invalidAccessToken"),
149
- errorCode: "EC002"
150
- });
151
- }
152
- if (accessTokenRowIsExpired(accessToken)) {
153
- await accessToken.destroy();
154
- request.locals.user = void 0;
155
- if (await renew()) continue;
156
- if (optional) return;
157
- return reject({
158
- error: t("auth.errors.invalidAccessToken"),
159
- errorCode: "EC002"
160
- });
161
- }
162
- break;
85
+ const outcome = await resolveRequestUserOutcome(request, response, {
86
+ tokenFrom: usedTokenFrom,
87
+ refreshCredential: usedRefresh,
88
+ overlapMs: options?.refresh?.overlapMs,
89
+ allowedTypes,
90
+ renewalUserType
91
+ });
92
+ if (outcome.user) {
93
+ request.locals.user = outcome.user;
94
+ return;
163
95
  }
164
- const userType = decoded.userType ?? accessToken.userType;
165
- if (allowedTypes.length && !allowedTypes.includes(userType)) return response.forbidden({
96
+ if (outcome.failure === "forbidden") return response.forbidden({
166
97
  error: t("auth.errors.unauthorized"),
167
98
  errorCode: "EC003"
168
99
  });
169
- const UserModel = config.key(`auth.userType.${userType}`);
170
- if (!UserModel) throw new Error(`User type ${userType} is unknown type.`);
171
- const currentUser = await UserModel.find(decoded.id);
172
- if (!currentUser) {
173
- await accessToken.destroy();
174
- request.locals.user = void 0;
175
- if (optional) return;
176
- return reject({
177
- error: t("auth.errors.invalidAccessToken"),
178
- errorCode: "EC002"
179
- });
180
- }
181
- if (!await authService.canAuthenticate(currentUser)) {
182
- request.locals.user = void 0;
183
- if (optional) return;
184
- return reject({
185
- error: t("auth.errors.unauthorized"),
186
- errorCode: "EC003"
187
- });
188
- }
189
- request.locals.user = currentUser;
100
+ if (optional) return;
101
+ if (outcome.failure === "missing") return reject({
102
+ error: t("auth.errors.missingAccessToken"),
103
+ errorCode: "EC001"
104
+ });
105
+ if (outcome.failure === "unauthorized") return reject({
106
+ error: t("auth.errors.unauthorized"),
107
+ errorCode: "EC003"
108
+ });
109
+ return reject({
110
+ error: t("auth.errors.invalidAccessToken"),
111
+ errorCode: "EC002"
112
+ });
190
113
  };
191
114
  return auth;
192
115
  }
@@ -1 +1 @@
1
- {"version":3,"file":"auth.middleware.mjs","names":[],"sources":["../../../../../../../auth/src/middleware/auth.middleware.ts"],"sourcesContent":["import { config, type HttpContext, t, type Middleware, type Request } from \"@warlock.js/core\";\r\nimport { log } from \"@warlock.js/logger\";\r\nimport type {\r\n AuthCredentialDescriptor,\r\n AuthMiddlewareOptions,\r\n TokenFrom,\r\n} from \"../contracts/types\";\r\nimport { AccessToken } from \"../models/access-token\";\r\nimport { authConfig } from \"../services/auth-config\";\r\nimport { authService } from \"../services/auth.service\";\r\nimport { isInvalidCredentialError, jwt } from \"../services/jwt\";\r\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\r\nimport {\r\n assertCsrfOriginAllowed,\r\n CsrfOriginMismatchError,\r\n requiresCsrfOriginCheck,\r\n} from \"./csrf-origin-check\";\r\nimport { localizedLoginPath } from \"./localized-login-path\";\r\n\r\n/** The 401 body shape every rejection in this middleware carries. */\r\ntype UnauthorizedPayload = { error: string; errorCode: string };\r\n\r\n/**\r\n * Reject an unauthenticated request, choosing the representation by ROUTE KIND.\r\n *\r\n * An API route always gets the JSON 401 it has always gotten. A PAGE route\r\n * (`request.route.isPage` — the React-SSR pages) instead redirects a logged-out\r\n * browser to the configured login path with a `returnUrl`, so a human\r\n * navigating to a guarded page lands on the login screen rather than reading a\r\n * raw JSON error blob — the defect in finding b9ab9804.\r\n *\r\n * The redirect is OPT-IN and backward-compatible: with no `auth.pageAuth.loginPath`\r\n * configured, even a page route falls back to the JSON 401, so an app that has\r\n * not asked for page-login UX keeps exactly its current behavior. The API 401\r\n * contract is never changed for API routes.\r\n *\r\n * `returnUrl` carries `request.url` — the relative path + query the browser was\r\n * on — never the absolute URL: a relative target cannot be turned into an\r\n * open-redirect off this app's origin.\r\n */\r\nfunction rejectUnauthorized(\r\n { request, response }: HttpContext,\r\n payload: UnauthorizedPayload,\r\n redirect?: AuthMiddlewareOptions[\"redirect\"],\r\n) {\r\n const loginPath = redirect?.to ?? authConfig.pageAuth.loginPath();\r\n const returnUrlParam = redirect?.returnUrlParam ?? authConfig.pageAuth.returnUrlParam();\r\n\r\n if (loginPath && request.route?.isPage) {\r\n // Under an active `web.localeRouting` strategy, the login destination\r\n // itself must carry the request's locale prefix — otherwise an anonymous\r\n // `/ar/admin` bounces to the DEFAULT locale's `/login` rather than\r\n // `/ar/login`, even though `returnUrl` below correctly points back at\r\n // `/ar/admin`. See `./localized-login-path.ts`.\r\n const destination = localizedLoginPath(loginPath, request.locale);\r\n const separator = destination.includes(\"?\") ? \"&\" : \"?\";\r\n const returnUrl = encodeURIComponent(request.url);\r\n\r\n return response.redirect(`${destination}${separator}${returnUrlParam}=${returnUrl}`);\r\n }\r\n\r\n return response.unauthorized(payload);\r\n}\r\n\r\n/**\r\n * Decoded access-token claims the middleware reads. The full payload carries\r\n * more (`created_at`, `tokenType`, `iat`, `exp`) but only these drive routing.\r\n */\r\ntype DecodedAccessToken = {\r\n id: string | number;\r\n userType?: string;\r\n};\r\n\r\n/**\r\n * Whether the persisted row says the token is dead.\r\n *\r\n * The answer belongs to the model (`AccessToken.isExpired`), so a registered\r\n * override that renames or reshapes its expiry column stays authoritative and\r\n * the middleware never touches a column name. A row that cannot answer at all —\r\n * an override that dropped the getter — is treated as **expired**: the failure\r\n * mode of this whole defect class was a check that quietly answered \"fine\" when\r\n * it had nothing to check, and that is not repeated here.\r\n *\r\n * This is independent of the `exp` claim required by `jwt.verify`. That guard\r\n * catches a token whose *claims* carry no deadline; this one catches a token\r\n * whose *row* says the deadline has passed — a logged-out or expired session\r\n * whose JWT is still within its own lifetime. Neither subsumes the other.\r\n */\r\nfunction accessTokenRowIsExpired(accessToken: AccessToken): boolean {\r\n return typeof accessToken.isExpired === \"boolean\" ? accessToken.isExpired : true;\r\n}\r\n\r\nfunction readCredential(request: Request, tokenFrom: TokenFrom): string {\r\n if (tokenFrom === \"header\") {\r\n return request.authorizationValue;\r\n }\r\n\r\n const value = request.cookie(tokenFrom.slice(\"cookie:\".length));\r\n\r\n return value ? String(value) : \"\";\r\n}\r\n\r\nfunction tokenFromDescriptor(descriptor: Partial<AuthCredentialDescriptor>): TokenFrom {\r\n if (!descriptor.source || descriptor.source === \"header\") return \"header\";\r\n\r\n if (!descriptor.key) {\r\n throw new Error(\"authMiddleware cookie credentials require a cookie key.\");\r\n }\r\n\r\n return `cookie:${descriptor.key}`;\r\n}\r\n\r\nfunction resolveAllowedTypes(value: string | string[] | undefined): string[] {\r\n if (value !== undefined) return Array.isArray(value) ? value : [value];\r\n\r\n const configuredDefault = config.key(\"auth.defaultUserType\") as string | undefined;\r\n\r\n if (configuredDefault) return [configuredDefault];\r\n\r\n const userTypes = config.key(\"auth.userType\", {}) as Record<string, unknown>;\r\n const configuredTypes = Object.keys(userTypes);\r\n\r\n if (configuredTypes.length === 1) return configuredTypes;\r\n\r\n throw new Error(\r\n \"authMiddleware requires a user type when auth.defaultUserType is unset and multiple user types exist.\",\r\n );\r\n}\r\n\r\n/**\r\n * Build a route gate. Authentication is required unless optional is explicit.\r\n *\r\n * An omitted user type selects the configured default; an explicit argument\r\n * selects which user types may pass:\r\n * - `[]` — any authenticated user (token required, type not checked).\r\n * - `\"admin\"` / `[\"admin\", \"staff\"]` — token required AND the user's\r\n * `userType` must be one of the listed types.\r\n *\r\n * `{ optional: true }` allows anonymous requests. All other forms reject\r\n * missing or invalid credentials with 401, or a configured page redirect.\r\n *\r\n * `tokenFrom` selects one credential source and defaults to `\"header\"`.\r\n * A single source avoids making credential precedence depend on array order.\r\n *\r\n * @example\r\n * router.get(\"/account\", authMiddleware([]), accountController);\r\n * router.get(\"/admin\", authMiddleware(\"admin\"), adminController);\r\n * router.get(\"/back-office\", authMiddleware([\"admin\", \"staff\"]), backOfficeController);\r\n * router.get(\"/browser-account\", authMiddleware([], \"cookie:token\"), accountController);\r\n */\r\nexport function authMiddleware(): Middleware;\r\nexport function authMiddleware(options: AuthMiddlewareOptions): Middleware;\r\nexport function authMiddleware(\r\n allowedUserType: string | string[],\r\n options?: AuthMiddlewareOptions,\r\n): Middleware;\r\nexport function authMiddleware(\r\n allowedUserType: string | string[],\r\n tokenFrom?: TokenFrom,\r\n): Middleware;\r\nexport function authMiddleware(\r\n userTypeOrOptions?: string | string[] | AuthMiddlewareOptions,\r\n legacyTokenFromOrOptions?: TokenFrom | AuthMiddlewareOptions,\r\n): Middleware {\r\n const options =\r\n typeof userTypeOrOptions === \"object\" && !Array.isArray(userTypeOrOptions)\r\n ? userTypeOrOptions\r\n : typeof legacyTokenFromOrOptions === \"object\"\r\n ? legacyTokenFromOrOptions\r\n : undefined;\r\n const selectedUserType =\r\n typeof userTypeOrOptions === \"string\" || Array.isArray(userTypeOrOptions)\r\n ? userTypeOrOptions\r\n : undefined;\r\n const allowedTypes = resolveAllowedTypes(selectedUserType);\r\n const legacyTokenFrom =\r\n typeof legacyTokenFromOrOptions === \"string\" ? legacyTokenFromOrOptions : undefined;\r\n const tokenFrom = options ? tokenFromDescriptor(options) : (legacyTokenFrom ?? \"header\");\r\n const refreshCredential = options?.refresh ? tokenFromDescriptor(options.refresh) : undefined;\r\n const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : undefined;\r\n\r\n if (\r\n refreshCredential &&\r\n (tokenFrom === \"header\" || refreshCredential === \"header\" || !renewalUserType)\r\n ) {\r\n throw new Error(\r\n \"authMiddleware automatic renewal requires one allowed user type and cookie access and refresh credentials.\",\r\n );\r\n }\r\n\r\n const optional = options?.optional === true;\r\n\r\n const auth: Middleware = async ({ request, response }) => {\r\n const reject = (payload: UnauthorizedPayload) =>\r\n rejectUnauthorized({ request, response }, payload, options?.redirect);\r\n let authorizationValue = readCredential(request, tokenFrom);\r\n let renewalAttempted = false;\r\n\r\n // Renewal can mint cookies, so a cookie-authenticated unsafe request must\r\n // pass the same CSRF check even when its access cookie is missing.\r\n if (\r\n (authorizationValue || refreshCredential) &&\r\n requiresCsrfOriginCheck(tokenFrom, request.method)\r\n ) {\r\n try {\r\n assertCsrfOriginAllowed(request);\r\n } catch (error) {\r\n if (!(error instanceof CsrfOriginMismatchError)) throw error;\r\n\r\n log.error(\"http\", \"auth\", error);\r\n return response.forbidden({\r\n error: t(\"auth.errors.csrfOriginMismatch\"),\r\n errorCode: AuthErrorCodes.CsrfOriginMismatch,\r\n });\r\n }\r\n }\r\n\r\n const renew = async (): Promise<boolean> => {\r\n if (!refreshCredential || renewalAttempted) return false;\r\n\r\n renewalAttempted = true;\r\n const refreshToken = readCredential(request, refreshCredential);\r\n if (!refreshToken) return false;\r\n\r\n const pair = await authService.renewAutomaticSession(refreshToken, renewalUserType!, {\r\n overlapMs: options?.refresh?.overlapMs,\r\n });\r\n if (!pair?.refreshToken) return false;\r\n\r\n authService.setAuthCookie(response, pair.accessToken, {\r\n name: tokenFrom.slice(\"cookie:\".length),\r\n });\r\n authService.setAuthCookie(response, pair.refreshToken, {\r\n name: refreshCredential.slice(\"cookie:\".length),\r\n });\r\n authorizationValue = pair.accessToken.token;\r\n\r\n return true;\r\n };\r\n\r\n let decoded: DecodedAccessToken;\r\n let accessToken: AccessToken | null;\r\n\r\n // At most one renewal is attempted per request. The renewed access token\r\n // is checked through this normal path; no handler or unsafe request replay\r\n // is performed.\r\n while (true) {\r\n if (!authorizationValue) {\r\n request.locals.user = undefined;\r\n if (await renew()) continue;\r\n if (optional) return;\r\n return reject({\r\n error: t(\"auth.errors.missingAccessToken\"),\r\n errorCode: AuthErrorCodes.MissingAccessToken,\r\n });\r\n }\r\n\r\n try {\r\n decoded = await jwt.verify<DecodedAccessToken>(authorizationValue);\r\n } catch (error) {\r\n if (!isInvalidCredentialError(error)) throw error;\r\n log.error(\"http\", \"auth\", error);\r\n request.locals.user = undefined;\r\n if (await renew()) continue;\r\n if (optional) return;\r\n return reject({\r\n error: t(\"auth.errors.invalidAccessToken\"),\r\n errorCode: AuthErrorCodes.InvalidAccessToken,\r\n });\r\n }\r\n\r\n request.decodedAccessToken = decoded;\r\n const AccessTokenModel = config.key(\"auth.accessToken.model\", AccessToken);\r\n accessToken = await AccessTokenModel.findByToken(authorizationValue);\r\n\r\n if (!accessToken) {\r\n request.locals.user = undefined;\r\n if (await renew()) continue;\r\n if (optional) return;\r\n return reject({\r\n error: t(\"auth.errors.invalidAccessToken\"),\r\n errorCode: AuthErrorCodes.InvalidAccessToken,\r\n });\r\n }\r\n\r\n if (accessTokenRowIsExpired(accessToken)) {\r\n await accessToken.destroy();\r\n request.locals.user = undefined;\r\n if (await renew()) continue;\r\n if (optional) return;\r\n return reject({\r\n error: t(\"auth.errors.invalidAccessToken\"),\r\n errorCode: AuthErrorCodes.InvalidAccessToken,\r\n });\r\n }\r\n\r\n break;\r\n }\r\n const userType = decoded.userType ?? accessToken.userType;\r\n\r\n if (allowedTypes.length && !allowedTypes.includes(userType)) {\r\n return response.forbidden({\r\n error: t(\"auth.errors.unauthorized\"),\r\n errorCode: AuthErrorCodes.Unauthorized,\r\n });\r\n }\r\n\r\n const UserModel = config.key(`auth.userType.${userType}`);\r\n\r\n if (!UserModel) {\r\n // Configuration, not credentials. Throwing keeps a mis-registered app\r\n // loudly broken instead of quietly rejecting every request of this type.\r\n throw new Error(`User type ${userType} is unknown type.`);\r\n }\r\n\r\n const currentUser = await UserModel.find(decoded.id);\r\n\r\n if (!currentUser) {\r\n await accessToken.destroy();\r\n request.locals.user = undefined;\r\n if (optional) return;\r\n\r\n return reject({\r\n error: t(\"auth.errors.invalidAccessToken\"),\r\n errorCode: AuthErrorCodes.InvalidAccessToken,\r\n });\r\n }\r\n\r\n if (!(await authService.canAuthenticate(currentUser))) {\r\n request.locals.user = undefined;\r\n if (optional) return;\r\n\r\n return reject({\r\n error: t(\"auth.errors.unauthorized\"),\r\n errorCode: AuthErrorCodes.Unauthorized,\r\n });\r\n }\r\n\r\n request.locals.user = currentUser;\r\n };\r\n\r\n return auth;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,mBACP,EAAE,SAAS,YACX,SACA,UACA;CACA,MAAM,YAAY,UAAU,MAAM,WAAW,SAAS,UAAU;CAChE,MAAM,iBAAiB,UAAU,kBAA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AAiB,UAAU;EAExD,IAAI,CAAC,WAGH,MAAM,IAAI,MAAM,aAAa,SAAS,kBAAkB;EAG1D,MAAM,cAAc,MAAM,UAAU,KAAK,QAAQ,EAAE;EAEnD,IAAI,CAAC,aAAa;GAChB,MAAM,YAAY,QAAQ;GAC1B,QAAQ,OAAO,OAAO;GACtB,IAAI,UAAU;GAEd,OAAO,OAAO;IACZ,OAAO,EAAE,gCAAgC;IACzC;GACF,CAAC;EACH;EAEA,IAAI,CAAE,MAAM,YAAY,gBAAgB,WAAW,GAAI;GACrD,QAAQ,OAAO,OAAO;GACtB,IAAI,UAAU;GAEd,OAAO,OAAO;IACZ,OAAO,EAAE,0BAA0B;IACnC;GACF,CAAC;EACH;EAEA,QAAQ,OAAO,OAAO;CACxB;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"auth.middleware.mjs","names":[],"sources":["../../../../../../../auth/src/middleware/auth.middleware.ts"],"sourcesContent":["import { config, type HttpContext, t, type Middleware } from \"@warlock.js/core\";\r\nimport { log } from \"@warlock.js/logger\";\r\nimport type {\r\n AuthCredentialDescriptor,\r\n AuthMiddlewareOptions,\r\n TokenFrom,\r\n} from \"../contracts/types\";\r\nimport { authConfig } from \"../services/auth-config\";\r\nimport { readCredential, resolveRequestUserOutcome } from \"../services/resolve-request-user\";\r\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\r\nimport {\r\n assertCsrfOriginAllowed,\r\n CsrfOriginMismatchError,\r\n requiresCsrfOriginCheck,\r\n} from \"./csrf-origin-check\";\r\nimport { localizedLoginPath } from \"./localized-login-path\";\r\n\r\n/** The 401 body shape every rejection in this middleware carries. */\r\ntype UnauthorizedPayload = { error: string; errorCode: string };\r\n\r\n/**\r\n * Reject an unauthenticated request, choosing the representation by ROUTE KIND.\r\n *\r\n * An API route always gets the JSON 401 it has always gotten. A PAGE route\r\n * (`request.route.isPage` — the React-SSR pages) instead redirects a logged-out\r\n * browser to the configured login path with a `returnUrl`, so a human\r\n * navigating to a guarded page lands on the login screen rather than reading a\r\n * raw JSON error blob — the defect in finding b9ab9804.\r\n *\r\n * The redirect is OPT-IN and backward-compatible: with no `auth.pageAuth.loginPath`\r\n * configured, even a page route falls back to the JSON 401, so an app that has\r\n * not asked for page-login UX keeps exactly its current behavior. The API 401\r\n * contract is never changed for API routes.\r\n *\r\n * `returnUrl` carries `request.url` — the relative path + query the browser was\r\n * on — never the absolute URL: a relative target cannot be turned into an\r\n * open-redirect off this app's origin.\r\n */\r\nfunction rejectUnauthorized(\r\n { request, response }: HttpContext,\r\n payload: UnauthorizedPayload,\r\n redirect?: AuthMiddlewareOptions[\"redirect\"],\r\n) {\r\n const loginPath = redirect?.to ?? authConfig.pageAuth.loginPath();\r\n const returnUrlParam = redirect?.returnUrlParam ?? authConfig.pageAuth.returnUrlParam();\r\n\r\n if (loginPath && request.route?.isPage) {\r\n // Under an active `web.localeRouting` strategy, the login destination\r\n // itself must carry the request's locale prefix — otherwise an anonymous\r\n // `/ar/admin` bounces to the DEFAULT locale's `/login` rather than\r\n // `/ar/login`, even though `returnUrl` below correctly points back at\r\n // `/ar/admin`. See `./localized-login-path.ts`.\r\n const destination = localizedLoginPath(loginPath, request.locale);\r\n const separator = destination.includes(\"?\") ? \"&\" : \"?\";\r\n const returnUrl = encodeURIComponent(request.url);\r\n\r\n return response.redirect(`${destination}${separator}${returnUrlParam}=${returnUrl}`);\r\n }\r\n\r\n return response.unauthorized(payload);\r\n}\r\n\r\nfunction tokenFromDescriptor(descriptor: Partial<AuthCredentialDescriptor>): TokenFrom {\r\n if (!descriptor.source || descriptor.source === \"header\") return \"header\";\r\n\r\n if (!descriptor.key) {\r\n throw new Error(\"authMiddleware cookie credentials require a cookie key.\");\r\n }\r\n\r\n return `cookie:${descriptor.key}`;\r\n}\r\n\r\nfunction resolveAllowedTypes(value: string | string[] | undefined): string[] {\r\n if (value !== undefined) return Array.isArray(value) ? value : [value];\r\n\r\n const configuredDefault = config.key(\"auth.defaultUserType\") as string | undefined;\r\n\r\n if (configuredDefault) return [configuredDefault];\r\n\r\n const userTypes = config.key(\"auth.userType\", {}) as Record<string, unknown>;\r\n const configuredTypes = Object.keys(userTypes);\r\n\r\n if (configuredTypes.length === 1) return configuredTypes;\r\n\r\n throw new Error(\r\n \"authMiddleware requires a user type when auth.defaultUserType is unset and multiple user types exist.\",\r\n );\r\n}\r\n\r\n/**\r\n * Build a route gate. Authentication is required unless optional is explicit.\r\n *\r\n * An omitted user type selects the configured default; an explicit argument\r\n * selects which user types may pass:\r\n * - `[]` — any authenticated user (token required, type not checked).\r\n * - `\"admin\"` / `[\"admin\", \"staff\"]` — token required AND the user's\r\n * `userType` must be one of the listed types.\r\n *\r\n * `{ optional: true }` allows anonymous requests. All other forms reject\r\n * missing or invalid credentials with 401, or a configured page redirect.\r\n *\r\n * `tokenFrom` selects one credential source and defaults to `\"header\"`.\r\n * A single source avoids making credential precedence depend on array order.\r\n *\r\n * @example\r\n * router.get(\"/account\", authMiddleware([]), accountController);\r\n * router.get(\"/admin\", authMiddleware(\"admin\"), adminController);\r\n * router.get(\"/back-office\", authMiddleware([\"admin\", \"staff\"]), backOfficeController);\r\n * router.get(\"/browser-account\", authMiddleware([], \"cookie:token\"), accountController);\r\n */\r\nexport function authMiddleware(): Middleware;\r\nexport function authMiddleware(options: AuthMiddlewareOptions): Middleware;\r\nexport function authMiddleware(\r\n allowedUserType: string | string[],\r\n options?: AuthMiddlewareOptions,\r\n): Middleware;\r\nexport function authMiddleware(\r\n allowedUserType: string | string[],\r\n tokenFrom?: TokenFrom,\r\n): Middleware;\r\nexport function authMiddleware(\r\n userTypeOrOptions?: string | string[] | AuthMiddlewareOptions,\r\n legacyTokenFromOrOptions?: TokenFrom | AuthMiddlewareOptions,\r\n): Middleware {\r\n const options =\r\n typeof userTypeOrOptions === \"object\" && !Array.isArray(userTypeOrOptions)\r\n ? userTypeOrOptions\r\n : typeof legacyTokenFromOrOptions === \"object\"\r\n ? legacyTokenFromOrOptions\r\n : undefined;\r\n const selectedUserType =\r\n typeof userTypeOrOptions === \"string\" || Array.isArray(userTypeOrOptions)\r\n ? userTypeOrOptions\r\n : undefined;\r\n const allowedTypes = resolveAllowedTypes(selectedUserType);\r\n const legacyTokenFrom =\r\n typeof legacyTokenFromOrOptions === \"string\" ? legacyTokenFromOrOptions : undefined;\r\n const dualSources = options?.sources?.length ? options.sources.map(tokenFromDescriptor) : undefined;\r\n\r\n if (dualSources && options?.source) {\r\n throw new Error(\"authMiddleware accepts either `source` or `sources`, not both.\");\r\n }\r\n\r\n const dualHeader = dualSources?.includes(\"header\") ?? false;\r\n const dualCookies = dualSources?.filter(source => source !== \"header\") ?? [];\r\n\r\n if (dualSources && (dualCookies.length > 1 || dualSources.length - dualCookies.length > 1)) {\r\n throw new Error(\"authMiddleware `sources` accepts at most one header and one cookie.\");\r\n }\r\n\r\n // With dual sources the configured cookie is the base credential; the header\r\n // is chosen per request, ahead of it.\r\n const cookieTokenFrom: TokenFrom = dualSources\r\n ? (dualCookies[0] ?? \"header\")\r\n : options\r\n ? tokenFromDescriptor(options)\r\n : (legacyTokenFrom ?? \"header\");\r\n const tokenFrom = cookieTokenFrom;\r\n const refreshCredential = options?.refresh ? tokenFromDescriptor(options.refresh) : undefined;\r\n const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : undefined;\r\n\r\n if (\r\n refreshCredential &&\r\n (tokenFrom === \"header\" || refreshCredential === \"header\" || !renewalUserType)\r\n ) {\r\n throw new Error(\r\n \"authMiddleware automatic renewal requires one allowed user type and cookie access and refresh credentials.\",\r\n );\r\n }\r\n\r\n const optional = options?.optional === true;\r\n\r\n const auth: Middleware = async ({ request, response }) => {\r\n const reject = (payload: UnauthorizedPayload) =>\r\n rejectUnauthorized({ request, response }, payload, options?.redirect);\r\n\r\n // A present Authorization header always wins and never falls back to the\r\n // cookie: the credential used is the header, so no renewal and no CSRF check.\r\n const headerWins = dualHeader && Boolean(request.authorizationValue);\r\n const usedTokenFrom: TokenFrom = headerWins ? \"header\" : tokenFrom;\r\n const usedRefresh = headerWins ? undefined : refreshCredential;\r\n\r\n // Renewal can mint cookies, so a cookie-authenticated unsafe request must\r\n // pass the same CSRF check even when its access cookie is missing.\r\n if (\r\n (readCredential(request, usedTokenFrom) || usedRefresh) &&\r\n requiresCsrfOriginCheck(usedTokenFrom, request.method)\r\n ) {\r\n try {\r\n assertCsrfOriginAllowed(request);\r\n } catch (error) {\r\n if (!(error instanceof CsrfOriginMismatchError)) throw error;\r\n\r\n log.error(\"http\", \"auth\", error);\r\n return response.forbidden({\r\n error: t(\"auth.errors.csrfOriginMismatch\"),\r\n errorCode: AuthErrorCodes.CsrfOriginMismatch,\r\n });\r\n }\r\n }\r\n\r\n const outcome = await resolveRequestUserOutcome(request, response, {\r\n tokenFrom: usedTokenFrom,\r\n refreshCredential: usedRefresh,\r\n overlapMs: options?.refresh?.overlapMs,\r\n allowedTypes,\r\n renewalUserType,\r\n });\r\n\r\n if (outcome.user) {\r\n request.locals.user = outcome.user;\r\n return;\r\n }\r\n\r\n if (outcome.failure === \"forbidden\") {\r\n return response.forbidden({\r\n error: t(\"auth.errors.unauthorized\"),\r\n errorCode: AuthErrorCodes.Unauthorized,\r\n });\r\n }\r\n\r\n if (optional) return;\r\n\r\n if (outcome.failure === \"missing\") {\r\n return reject({\r\n error: t(\"auth.errors.missingAccessToken\"),\r\n errorCode: AuthErrorCodes.MissingAccessToken,\r\n });\r\n }\r\n\r\n if (outcome.failure === \"unauthorized\") {\r\n return reject({\r\n error: t(\"auth.errors.unauthorized\"),\r\n errorCode: AuthErrorCodes.Unauthorized,\r\n });\r\n }\r\n\r\n return reject({\r\n error: t(\"auth.errors.invalidAccessToken\"),\r\n errorCode: AuthErrorCodes.InvalidAccessToken,\r\n });\r\n };\r\n\r\n return auth;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAS,mBACP,EAAE,SAAS,YACX,SACA,UACA;CACA,MAAM,YAAY,UAAU,MAAM,WAAW,SAAS,UA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,QAAQ,YAAY,aACtB,OAAO,SAAS,UAAU;GACxB,OAAO,EAAE,0BAA0B;GACnC;EACF,CAAC;EAGH,IAAI,UAAU;EAEd,IAAI,QAAQ,YAAY,WACtB,OAAO,OAAO;GACZ,OAAO,EAAE,gCAAgC;GACzC;EACF,CAAC;EAGH,IAAI,QAAQ,YAAY,gBACtB,OAAO,OAAO;GACZ,OAAO,EAAE,0BAA0B;GACnC;EACF,CAAC;EAGH,OAAO,OAAO;GACZ,OAAO,EAAE,gCAAgC;GACzC;EACF,CAAC;CACH;CAEA,OAAO;AACT"}
@@ -121,6 +121,8 @@ const authConfig = {
121
121
  cookie: {
122
122
  /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default "access_token" */
123
123
  name: () => config.key("auth.cookie.name", "access_token"),
124
+ /** Refresh-token cookie name the session cookie helpers use. @default "refresh_token" */
125
+ refreshName: () => config.key("auth.cookie.refreshName", "refresh_token"),
124
126
  /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default "/" */
125
127
  path: () => config.key("auth.cookie.path", "/")
126
128
  },