@warlock.js/auth 5.53.1 → 5.54.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 (43) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/esm/contracts/providers.d.mts +1 -1
  3. package/esm/contracts/types.d.mts +22 -0
  4. package/esm/contracts/types.d.mts.map +1 -1
  5. package/esm/contracts/types.mjs.map +1 -1
  6. package/esm/middleware/login-throttle.middleware.d.mts +1 -1
  7. package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
  8. package/esm/middleware/login-throttle.middleware.mjs +18 -1
  9. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  10. package/esm/models/auth-token-family/auth-token-family.model.d.mts +14 -0
  11. package/esm/models/auth-token-family/auth-token-family.model.d.mts.map +1 -1
  12. package/esm/models/auth-token-family/auth-token-family.model.mjs +43 -0
  13. package/esm/models/auth-token-family/auth-token-family.model.mjs.map +1 -1
  14. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  15. package/esm/models/refresh-token/refresh-token.model.mjs +6 -1
  16. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  17. package/esm/otp/otp.d.mts +5 -4
  18. package/esm/otp/otp.d.mts.map +1 -1
  19. package/esm/otp/otp.mjs +25 -20
  20. package/esm/otp/otp.mjs.map +1 -1
  21. package/esm/services/auth-config.mjs +40 -3
  22. package/esm/services/auth-config.mjs.map +1 -1
  23. package/esm/services/auth.service.d.mts +11 -2
  24. package/esm/services/auth.service.d.mts.map +1 -1
  25. package/esm/services/auth.service.mjs +36 -9
  26. package/esm/services/auth.service.mjs.map +1 -1
  27. package/esm/services/background-work.mjs +16 -0
  28. package/esm/services/background-work.mjs.map +1 -0
  29. package/esm/services/jwt.d.mts +2 -2
  30. package/esm/services/jwt.d.mts.map +1 -1
  31. package/esm/services/jwt.mjs +51 -26
  32. package/esm/services/jwt.mjs.map +1 -1
  33. package/esm/services/password-reset.d.mts +7 -5
  34. package/esm/services/password-reset.d.mts.map +1 -1
  35. package/esm/services/password-reset.mjs +25 -19
  36. package/esm/services/password-reset.mjs.map +1 -1
  37. package/llms-full.txt +8 -6
  38. package/package.json +11 -11
  39. package/skills/auth-basics/SKILL.md +1 -1
  40. package/skills/login-with-providers/SKILL.md +2 -2
  41. package/skills/manage-tokens/SKILL.md +2 -0
  42. package/skills/throttle-login-attempts/SKILL.md +2 -2
  43. package/skills/verify-email-and-reset-password/SKILL.md +1 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,33 @@ 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.54.0 - 2026-11-16
8
+
9
+ ### Upgrading
10
+
11
+ - `authService.attemptLogin()` (so `login()`) now replaces a stored password hash made with another algorithm or cost than `encryption.password` asks for, after a correct password. Existing users catch up as they sign in. A failure to save is logged and never fails the login. Set `auth.rehashPasswords: false` to keep hashes as they are.
12
+ - `requestPasswordReset()` and `requestOtp()` now run the account lookup, the token or code writes and the delivery after the response, so a known and an unknown account answer in the same time. Code that read the new token row right after `await requestPasswordReset(...)` without `auth.passwordReset.awaitDelivery: true` should wait for it (or read it from the delivery). A failure is logged and emitted as `password.resetDeliveryFailed` / `otp.deliveryFailed`.
13
+ - A successful login no longer clears the shared IP bucket of `loginThrottleMiddleware()` when an account bucket (email, or email and IP) is tracked next to it; the IP bucket expires with its window. With `by: ["ip"]` alone a success still resets it.
14
+ - Defaults that change in 6.0, with a one-time warning now: `auth.passkeys.userVerification` (`"preferred"` becomes `"required"`) when it is not set, `loginThrottleMiddleware({ emailLock })` (`"global"` becomes `"pair"`) when it is not set and both email and IP are tracked, and a JWT secret shorter than 32 bytes (the production warning now says it becomes a boot error). Set the first two explicitly to choose now.
15
+
16
+ ### Added
17
+
18
+ - `auth.accessToken.previousSecrets` and `auth.refreshToken.previousSecrets` rotate JWT secrets without signing users out. A token whose signature the current secret rejects is checked against each retired secret; every other failure (expired, wrong issuer or audience, wrong token type, malformed) stays final, and a key passed explicitly to `jwt.verify()` ignores them. New tokens are always signed with the current secret. With no `refreshToken.secret`, the retired access secrets apply to refresh tokens too. Retired secrets get the same 32-byte production warning.
19
+ - `auth.rehashPasswords` (default `true`), see Upgrading.
20
+
21
+ ### Changed
22
+
23
+ - `authService.revokeAllTokens()` ("sign out everywhere") does its work in bulk: the distinct token families are ensured with one read and one insert, revoked with one update (`AuthTokenFamily.revokeAllFor()`), and every refresh token with one update, instead of a transaction per family. `token.familyRevoked` still fires per family, `token.revoked` for tokens outside any durable family, and `logout.all` once. `RefreshToken.revokeAllFor()` now revokes with one update instead of saving each row.
24
+ - Raised the `@mongez` dependency ranges to the 2026-11-16 releases (copper 2.1.4, events 2.2.10, reinforcements 4.1.0).
25
+
26
+ ### Fixed
27
+
28
+ - A password-reset or OTP request for a known account no longer answers slower than for an unknown one because of the token writes (see Upgrading).
29
+
30
+ ### Documentation
31
+
32
+ - The configuration, throttle, passkeys, password-reset and token pages and the `manage-tokens`, `throttle-login-attempts`, `login-with-providers`, `verify-email-and-reset-password` and `auth-basics` skills cover secret rotation, rehashing, the IP bucket rule, the background request work and the 6.0 default changes.
33
+
7
34
  ## 5.53.0 - 2026-11-11
8
35
 
9
36
  ### Upgrading
@@ -209,7 +209,7 @@ export type PasskeysConfig = {
209
209
  * - `"required"` — refuse an assertion without user verification, so a
210
210
  * passkey login is two factors (the device plus the PIN or biometric).
211
211
  * Users whose authenticator cannot verify them cannot register or sign in.
212
- * @default "preferred"
212
+ * @default "preferred" (changes to `"required"` in 6.0; set it explicitly to choose now)
213
213
  */
214
214
  userVerification?: "required" | "preferred";
215
215
  };
@@ -94,6 +94,12 @@ export type AccessTokenConfig = {
94
94
  * Secret used to sign access tokens.
95
95
  */
96
96
  secret?: string;
97
+ /**
98
+ * Retired access-token secrets, newest first. Tokens signed with one of them
99
+ * still verify; new tokens are always signed with `secret`. Remove an entry
100
+ * once every token signed with it has expired.
101
+ */
102
+ previousSecrets?: string[];
97
103
  /**
98
104
  * JWT algorithm.
99
105
  * @default "HS256"
@@ -148,6 +154,13 @@ export type RefreshTokenConfig = {
148
154
  * to the access-token secret when omitted.
149
155
  */
150
156
  secret?: string;
157
+ /**
158
+ * Retired refresh-token secrets. Tokens signed with one of them still
159
+ * verify; new tokens are always signed with `secret`. When no refresh
160
+ * `secret` is set, the retired access-token secrets apply to refresh tokens
161
+ * too.
162
+ */
163
+ previousSecrets?: string[];
151
164
  /**
152
165
  * Refresh-token lifetime — a duration string `ms` parses to a **positive**
153
166
  * number of milliseconds; an unusable value throws naming this key on issue
@@ -338,6 +351,15 @@ export type AuthConfigurations = {
338
351
  * @default false
339
352
  */
340
353
  hashTokensAtRest?: boolean;
354
+ /**
355
+ * After a successful password login, replace a stored hash made with another
356
+ * algorithm or cost than `encryption.password` now asks for (a raised bcrypt
357
+ * `salt`, or a switch to the `"scrypt"` driver) with a fresh one. A failure
358
+ * to save is logged and never fails the login. Set `false` to keep hashes as
359
+ * they are.
360
+ * @default true
361
+ */
362
+ rehashPasswords?: boolean;
341
363
  /**
342
364
  * Access-token configuration (secret, expiry, algorithm, model override).
343
365
  */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA4Ba;;;;;;YAOD;;YAGA;;iBAGK;EACf;EACA;;;iBAIe,wCAAwC;;EAEvD;;;iBAIe,8BAA8B,QAAQ;EACrD;;;;;;;;EAQA,UAAU;;EAEV,UAAU;EACV;IAAa;IAAY;;;;YAIf,mBAAmB,MAAM,mBAAmB;;YAG5C,kBAAkB;EAC5B;;;;;;YAOU,wBACV,aAAa,KAAK,iCACf,KAAK;;;;;;;YAQE;;;;;;EAMV,eAAe;;;;EAIf;;;;;EAKA,YAAY;;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;;;EAIA,cAAc;;;;EAId,eAAe;;;;;;EAMf,WAAW;;;;;;EAMX,SAAS;;;;EAIT,OAAO;;;;EAIP,eAAe;;;;EAIf,gBAAgB;;;;EAIhB,eAAe;;;;EAIf,YAAY;;;;EAIZ,WAAW;;;;EAIX,MAAM;;;;EAIN,MAAM;;YAGI;;;;EAIV;;;;EAIA;;;;;YAMU;;;;EAIV,aAAa;;;;EAIb,eAAe;;;;;YAML;;;;EAIV;;;;EAIA;;;;EAIA;;;;;EAKA;;;;EAIA,UAAU;;YAGA,YAAY,iBAAiB;EACvC,MAAM;EACN,QAAQ;;;YAIE,wBAAwB,SAAS;;;;;;;;;YAUjC;;;;;;EAMV;;;;;EAKA;;;;;EAKA;;EAEA,eAAe;;;;;;;;;;;;EAYf;;;;;;YAOU;;;;;;EAMV;;;;;;;;YASU;;EAEV;;EAEA;;EAEA;;;;;;;EAOA;;;YAIU;;EAEV;;EAEA"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"sourcesContent":["import { type ChildModel } from \"@warlock.js/cascade\";\nimport type { Request } from \"@warlock.js/core\";\nimport { type Algorithm } from \"fast-jwt\";\nimport type { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport type { OneTimeToken } from \"../models/one-time-token\";\nimport type { OtpConfig, PasskeysConfig, ProvidersConfig } from \"./providers\";\nimport type { RefreshToken } from \"../models/refresh-token\";\n\n/**\n * Symbol to indicate no expiration for tokens\n * Use this when you explicitly want tokens to never expire\n *\n * @example\n * ```typescript\n * // src/config/auth.ts\n * import { NO_EXPIRATION, type AuthConfigurations } from \"@warlock.js/auth\";\n *\n * const authConfigurations: AuthConfigurations = {\n * accessToken: {\n * secret: env(\"JWT_SECRET\"),\n * expiresIn: NO_EXPIRATION, // Token expires within 100 years\n * },\n * };\n *\n * export default authConfigurations;\n * ```\n */\nexport const NO_EXPIRATION = \"100y\";\n\n/**\n * Behavior when logout is called without a refresh token\n * - \"revoke-all\": Revoke all refresh tokens for the user (secure default)\n * - \"error\": Return an error requiring the refresh token\n */\nexport type LogoutWithoutTokenBehavior = \"revoke-all\" | \"error\";\n\n/** The single request credential source an auth middleware instance accepts. */\nexport type TokenFrom = \"header\" | `cookie:${string}`;\n\n/** One explicitly named credential location accepted by auth middleware. */\nexport interface AuthCredentialDescriptor {\n source: \"header\" | \"cookie\";\n key?: string;\n}\n\n/** Cookie credential and bounded duplicate window for automatic renewal. */\nexport interface AuthRefreshCredentialDescriptor extends AuthCredentialDescriptor {\n /** Milliseconds; the service clamps this to the 0–10 second range (default 5 seconds). */\n overlapMs?: number;\n}\n\n/** Per-route authentication behavior for the object middleware overload. */\nexport interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor> {\n optional?: boolean;\n /**\n * Accept both a header and a cookie credential (at most one of each).\n * Precedence is fixed and independent of array order: a present\n * `Authorization` header wins, an invalid header rejects and never falls back\n * to the cookie, and renewal plus the CSRF Origin check apply only when the\n * cookie is the credential actually used. Cannot be combined with `source`.\n */\n sources?: AuthCredentialDescriptor[];\n /** Opt-in automatic renewal credential. Cookie sources only. */\n refresh?: AuthRefreshCredentialDescriptor;\n redirect?: { to: string; returnUrlParam?: string };\n}\n\n/** Application policy that decides whether a resolved user may authenticate. */\nexport type CanAuthenticate = (user: Auth) => boolean | Promise<boolean>;\n\n/** Password credentials plus the application-defined identity fields. */\nexport type AuthCredentials = Record<string, unknown> & {\n password: string;\n};\n\n/**\n * Rewrites the identity fields of a login (everything except `password`)\n * before the user lookup.\n */\nexport type NormalizeCredentials = (\n identifiers: Omit<AuthCredentials, \"password\">,\n) => Omit<AuthCredentials, \"password\">;\n\n/**\n * Access-token configuration.\n *\n * `secret` may also be supplied via the deprecated `jwt.secret` (resolved by a\n * backward-compatible shim); one of the two is required at runtime.\n */\nexport type AccessTokenConfig = {\n /**\n * Override the persisted access-token model — extend {@link AccessToken} to\n * add columns (e.g. a tenant key) or rename them, then register the subclass\n * here. Defaults to the package's `AccessToken`.\n */\n model?: typeof AccessToken;\n /**\n * Secret used to sign access tokens.\n */\n secret?: string;\n /**\n * JWT algorithm.\n * @default \"HS256\"\n */\n algorithm?: Algorithm;\n /**\n * Access-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\n * first token issue: each of them would otherwise sign a token with no `exp`\n * claim at all.\n * @example \"1h\" or NO_EXPIRATION\n * @default \"1h\"\n */\n expiresIn?: string;\n /**\n * Issuer (`iss` claim) stamped on every access and refresh token this app\n * signs, and required on every token it accepts. Set it when several apps\n * or services share a signing secret, so a token minted by one is refused\n * by the others. Unset (the default) ⇒ no `iss` is stamped or checked.\n *\n * Tokens signed before it was set carry no `iss` and are refused once it is\n * set, so every signed-in user signs in again once.\n * @example \"https://api.example.com\"\n */\n issuer?: string;\n /**\n * Audience (`aud` claim) stamped on every token this app signs, and\n * required on every token it accepts (a token matches when its `aud`\n * includes one of the values). Unset (the default) ⇒ no `aud` is stamped or\n * checked. Like `issuer`, setting it signs everyone out once.\n * @example \"web-app\"\n */\n audience?: string | string[];\n};\n\n/**\n * Refresh-token configuration.\n */\nexport type RefreshTokenConfig = {\n /**\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\n * Defaults to the package's `RefreshToken`.\n */\n model?: typeof RefreshToken;\n /**\n * Enable refresh tokens.\n * @default true\n */\n enabled?: boolean;\n /**\n * Separate secret for refresh tokens (recommended for security). Falls back\n * to the access-token secret when omitted.\n */\n secret?: string;\n /**\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds; an unusable value throws naming this key on issue\n * (see {@link AccessTokenConfig.expiresIn}).\n * @example \"7d\" or \"1w\"\n * @default \"7d\"\n */\n expiresIn?: string;\n /**\n * Rotate the refresh token on each use (old token revoked, replay detected).\n * @default true\n */\n rotation?: boolean;\n /**\n * Maximum active refresh tokens per user; the oldest are revoked past it.\n * @default 5\n */\n maxPerUser?: number;\n /**\n * Behavior when logout is called without a refresh token.\n * @default \"revoke-all\"\n */\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n};\n\n/**\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\n * deprecation warning.\n *\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\n */\nexport type LegacyJwtConfig = {\n secret?: string;\n algorithm?: Algorithm;\n expiresIn?: string;\n refresh?: {\n secret?: string;\n enabled?: boolean;\n expiresIn?: string;\n rotation?: boolean;\n maxPerUser?: number;\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n };\n};\n\n/**\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\n * to a login page instead of returning the API-style JSON 401.\n *\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\n * always keep the JSON 401 contract regardless of this setting.\n */\nexport type PageAuthConfig = {\n /**\n * Login path a guarded page route redirects a logged-out browser to (e.g.\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\n * behavior is opt-in and backward-compatible.\n */\n loginPath?: string;\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed.\n * @default \"returnUrl\"\n */\n returnUrlParam?: string;\n};\n\n/**\n * Data every email-verification / password-reset notification receives.\n */\nexport type OneTimeTokenNotificationData = {\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\n token: string;\n /** When the token stops working. */\n expiresAt: Date;\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\n url?: string;\n};\n\n/**\n * Anything auth can deliver a token through — a `defineNotification(...)`\n * result satisfies it, as does any object with a compatible `send`.\n */\nexport type AuthNotification = {\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\n};\n\n/** Builds the link a token notification points at. */\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\n\n/** Persists a new plaintext password for a user during a password reset. */\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\n\n/**\n * Email-verification configuration (`auth.verification`).\n */\nexport type EmailVerificationConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"24h\"\n */\n expiresIn?: string;\n /**\n * User attribute stamped with the verification `Date`. Declare it in the\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\n * @default \"emailVerifiedAt\"\n */\n field?: string;\n /** Replace the default verification email. */\n notification?: AuthNotification;\n /** Build the verification link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n};\n\n/**\n * Password-reset configuration (`auth.passwordReset`).\n */\nexport type PasswordResetConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"60m\"\n */\n expiresIn?: string;\n /**\n * User attribute `requestPasswordReset` looks the account up by.\n * @default \"email\"\n */\n identifierField?: string;\n /** Replace the default reset email. */\n notification?: AuthNotification;\n /** Build the reset link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n /**\n * Persist the new password yourself. By default auth saves a hash made by\n * the same `hashPassword` login verifies against, and falls back to the\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\n * the stored value with `verifyPassword` either way.\n */\n setPassword?: PasswordSetter;\n /**\n * Wait for the reset notification before `requestPasswordReset` resolves,\n * so a delivery error reaches the caller. Off by default: the notification\n * is sent in the background, so the response time does not reveal whether\n * the account exists. A background failure is logged and emitted as\n * `password.resetDeliveryFailed`.\n * @default false\n */\n awaitDelivery?: boolean;\n};\n\n/**\n * One-time token storage configuration (`auth.oneTimeToken`).\n */\nexport type OneTimeTokenConfig = {\n /** Override the persisted model — extend {@link OneTimeToken}. */\n model?: typeof OneTimeToken;\n};\n\nexport type AuthConfigurations = {\n /**\n * Define all user types — maps a user-type slug to its `Auth` model class so\n * tokens and the middleware can resolve the right model.\n */\n userType: {\n [userType: string]: ChildModel<Auth>;\n };\n /** Default user type used by `authMiddleware()` and options-only overloads. */\n defaultUserType?: string;\n /**\n * Decide whether a resolved user may authenticate or receive new tokens.\n * @default () => true\n */\n canAuthenticate?: CanAuthenticate;\n /**\n * How login identifiers are normalized before the user lookup. Default:\n * string values are trimmed and the `email` field is lower-cased, so\n * `\" Sara@x.io\"` finds the account stored as `sara@x.io`. If that finds no\n * user and the normalized value differs from what was sent (trimmed), the\n * lookup is retried once with the value as sent, so rows stored with capitals\n * keep working. Pass a function to normalize your own way (the retry still\n * applies), or `false` for exact matching.\n *\n * The login throttle buckets `email` by trimmed, lower-cased value either way.\n * @default trim string values, lower-case `email`\n */\n normalizeCredentials?: false | NormalizeCredentials;\n /**\n * Store only a SHA-256 digest of each access and refresh token in the\n * database, never the token itself, so a copy of the token tables (a\n * backup, a replica, a read-only injection) cannot be replayed as a login.\n *\n * No migration is needed: the digest goes in the existing `token` column,\n * and lookups accept both forms, so rows issued before the switch keep\n * working until they expire, and turning it off again signs no one out.\n * A row loaded from storage no longer carries its raw token; a freshly\n * issued one exposes it as `row.plainToken`.\n * @default false\n */\n hashTokensAtRest?: boolean;\n /**\n * Access-token configuration (secret, expiry, algorithm, model override).\n */\n accessToken?: AccessTokenConfig;\n /**\n * Refresh-token configuration (rotation, lifetime, cap, model override).\n */\n refreshToken?: RefreshTokenConfig;\n /**\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\n */\n pageAuth?: PageAuthConfig;\n /**\n * Cookie auth session config — read by `authService.setAuthCookie` /\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\n */\n cookie?: CookieAuthConfig;\n /**\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\n */\n csrf?: CsrfConfig;\n /**\n * Email verification — token lifetime, verified field, notification override.\n */\n verification?: EmailVerificationConfig;\n /**\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\n */\n passwordReset?: PasswordResetConfig;\n /**\n * One-time token (verification / reset) storage — model override.\n */\n oneTimeToken?: OneTimeTokenConfig;\n /**\n * Redirect login providers (`google`, `custom`) and account-linking policy.\n */\n providers?: ProvidersConfig;\n /**\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\n */\n passkeys?: PasskeysConfig;\n /**\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\n */\n otp?: OtpConfig;\n /**\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\n */\n jwt?: LegacyJwtConfig;\n};\n\nexport type AccessTokenOutput = {\n /**\n * JWT Token\n */\n token: string;\n /**\n * Exprie time in ISO format UTC time\n */\n expiresAt: string;\n};\n\n/**\n * Token pair returned after login or token refresh\n */\nexport type TokenPair = {\n /**\n * JWT access token (short-lived)\n */\n accessToken: AccessTokenOutput;\n /**\n * JWT refresh token (long-lived)\n */\n refreshToken?: AccessTokenOutput;\n};\n\n/**\n * Device information for session tracking\n */\nexport type DeviceInfo = {\n /**\n * User agent string from request\n */\n userAgent?: string;\n /**\n * Client IP address\n */\n ip?: string;\n /**\n * Optional device identifier\n */\n deviceId?: string;\n /**\n * Token family ID (for rotation tracking)\n * @internal\n */\n familyId?: string;\n /**\n * Access token payload\n */\n payload?: Record<string, unknown>;\n};\n\nexport type LoginResult<UserType extends Auth> = {\n user: UserType;\n tokens: TokenPair;\n};\n\n/** Selects a cookie Domain for one request; return `undefined` for a host-only cookie. */\nexport type CookieDomainResolver = (request: Request) => string | undefined;\n\n/**\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\n * configurable here — they come from core's `secureCookieDefaults()`, the\n * same floor every `response.cookie()` call gets, so a cookie auth session can\n * never be weakened to a laxer policy than the framework default.\n */\nexport type CookieAuthConfig = {\n /**\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\n * `cookie:<name>` token source must match to read it back.\n * @default \"access_token\"\n */\n name?: string;\n /**\n * Cookie name the session helpers write and clear for the refresh token.\n * @default \"refresh_token\"\n */\n refreshName?: string;\n /**\n * Cookie `Path` attribute.\n * @default \"/\"\n */\n path?: string;\n /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */\n cookieDomain?: CookieDomainResolver;\n /**\n * Write the auth cookies under a `__Host-` name prefix (`__Host-access_token`,\n * `__Host-refresh_token`). Browsers accept such a cookie only when it is\n * Secure, has `Path=/` and no `Domain`, so a subdomain or a plain-HTTP page\n * cannot plant or overwrite the session cookie. Requires `path: \"/\"` and no\n * `cookieDomain`; a write that breaks either rule throws naming the setting.\n *\n * While switching, the unprefixed cookie is still read (so signed-in users\n * stay signed in) and both names are cleared on logout.\n * @default false\n */\n hostPrefix?: boolean;\n};\n\n/**\n * CSRF Origin-check configuration. Read via\n * `authConfig.csrf.allowedOrigins()`.\n */\nexport type CsrfConfig = {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * in addition to the request's own origin.\n * @default []\n */\n allowedOrigins?: string[];\n};\n\n/**\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\n * falls back to `auth.cookie.*` config, then the package default. Cookie\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\n * see {@link CookieAuthConfig}.\n */\nexport type SetAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\n path?: string;\n /** Cookie `Domain` attribute. Omit for a host-only cookie. */\n domain?: string;\n /**\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\n * bare token string with no `maxAge` produces a session cookie (cleared\n * when the browser closes).\n */\n maxAge?: number;\n};\n\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\nexport type ClearAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\n path?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
1
+ {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"sourcesContent":["import { type ChildModel } from \"@warlock.js/cascade\";\nimport type { Request } from \"@warlock.js/core\";\nimport { type Algorithm } from \"fast-jwt\";\nimport type { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport type { OneTimeToken } from \"../models/one-time-token\";\nimport type { OtpConfig, PasskeysConfig, ProvidersConfig } from \"./providers\";\nimport type { RefreshToken } from \"../models/refresh-token\";\n\n/**\n * Symbol to indicate no expiration for tokens\n * Use this when you explicitly want tokens to never expire\n *\n * @example\n * ```typescript\n * // src/config/auth.ts\n * import { NO_EXPIRATION, type AuthConfigurations } from \"@warlock.js/auth\";\n *\n * const authConfigurations: AuthConfigurations = {\n * accessToken: {\n * secret: env(\"JWT_SECRET\"),\n * expiresIn: NO_EXPIRATION, // Token expires within 100 years\n * },\n * };\n *\n * export default authConfigurations;\n * ```\n */\nexport const NO_EXPIRATION = \"100y\";\n\n/**\n * Behavior when logout is called without a refresh token\n * - \"revoke-all\": Revoke all refresh tokens for the user (secure default)\n * - \"error\": Return an error requiring the refresh token\n */\nexport type LogoutWithoutTokenBehavior = \"revoke-all\" | \"error\";\n\n/** The single request credential source an auth middleware instance accepts. */\nexport type TokenFrom = \"header\" | `cookie:${string}`;\n\n/** One explicitly named credential location accepted by auth middleware. */\nexport interface AuthCredentialDescriptor {\n source: \"header\" | \"cookie\";\n key?: string;\n}\n\n/** Cookie credential and bounded duplicate window for automatic renewal. */\nexport interface AuthRefreshCredentialDescriptor extends AuthCredentialDescriptor {\n /** Milliseconds; the service clamps this to the 0–10 second range (default 5 seconds). */\n overlapMs?: number;\n}\n\n/** Per-route authentication behavior for the object middleware overload. */\nexport interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor> {\n optional?: boolean;\n /**\n * Accept both a header and a cookie credential (at most one of each).\n * Precedence is fixed and independent of array order: a present\n * `Authorization` header wins, an invalid header rejects and never falls back\n * to the cookie, and renewal plus the CSRF Origin check apply only when the\n * cookie is the credential actually used. Cannot be combined with `source`.\n */\n sources?: AuthCredentialDescriptor[];\n /** Opt-in automatic renewal credential. Cookie sources only. */\n refresh?: AuthRefreshCredentialDescriptor;\n redirect?: { to: string; returnUrlParam?: string };\n}\n\n/** Application policy that decides whether a resolved user may authenticate. */\nexport type CanAuthenticate = (user: Auth) => boolean | Promise<boolean>;\n\n/** Password credentials plus the application-defined identity fields. */\nexport type AuthCredentials = Record<string, unknown> & {\n password: string;\n};\n\n/**\n * Rewrites the identity fields of a login (everything except `password`)\n * before the user lookup.\n */\nexport type NormalizeCredentials = (\n identifiers: Omit<AuthCredentials, \"password\">,\n) => Omit<AuthCredentials, \"password\">;\n\n/**\n * Access-token configuration.\n *\n * `secret` may also be supplied via the deprecated `jwt.secret` (resolved by a\n * backward-compatible shim); one of the two is required at runtime.\n */\nexport type AccessTokenConfig = {\n /**\n * Override the persisted access-token model — extend {@link AccessToken} to\n * add columns (e.g. a tenant key) or rename them, then register the subclass\n * here. Defaults to the package's `AccessToken`.\n */\n model?: typeof AccessToken;\n /**\n * Secret used to sign access tokens.\n */\n secret?: string;\n /**\n * Retired access-token secrets, newest first. Tokens signed with one of them\n * still verify; new tokens are always signed with `secret`. Remove an entry\n * once every token signed with it has expired.\n */\n previousSecrets?: string[];\n /**\n * JWT algorithm.\n * @default \"HS256\"\n */\n algorithm?: Algorithm;\n /**\n * Access-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\n * first token issue: each of them would otherwise sign a token with no `exp`\n * claim at all.\n * @example \"1h\" or NO_EXPIRATION\n * @default \"1h\"\n */\n expiresIn?: string;\n /**\n * Issuer (`iss` claim) stamped on every access and refresh token this app\n * signs, and required on every token it accepts. Set it when several apps\n * or services share a signing secret, so a token minted by one is refused\n * by the others. Unset (the default) ⇒ no `iss` is stamped or checked.\n *\n * Tokens signed before it was set carry no `iss` and are refused once it is\n * set, so every signed-in user signs in again once.\n * @example \"https://api.example.com\"\n */\n issuer?: string;\n /**\n * Audience (`aud` claim) stamped on every token this app signs, and\n * required on every token it accepts (a token matches when its `aud`\n * includes one of the values). Unset (the default) ⇒ no `aud` is stamped or\n * checked. Like `issuer`, setting it signs everyone out once.\n * @example \"web-app\"\n */\n audience?: string | string[];\n};\n\n/**\n * Refresh-token configuration.\n */\nexport type RefreshTokenConfig = {\n /**\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\n * Defaults to the package's `RefreshToken`.\n */\n model?: typeof RefreshToken;\n /**\n * Enable refresh tokens.\n * @default true\n */\n enabled?: boolean;\n /**\n * Separate secret for refresh tokens (recommended for security). Falls back\n * to the access-token secret when omitted.\n */\n secret?: string;\n /**\n * Retired refresh-token secrets. Tokens signed with one of them still\n * verify; new tokens are always signed with `secret`. When no refresh\n * `secret` is set, the retired access-token secrets apply to refresh tokens\n * too.\n */\n previousSecrets?: string[];\n /**\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds; an unusable value throws naming this key on issue\n * (see {@link AccessTokenConfig.expiresIn}).\n * @example \"7d\" or \"1w\"\n * @default \"7d\"\n */\n expiresIn?: string;\n /**\n * Rotate the refresh token on each use (old token revoked, replay detected).\n * @default true\n */\n rotation?: boolean;\n /**\n * Maximum active refresh tokens per user; the oldest are revoked past it.\n * @default 5\n */\n maxPerUser?: number;\n /**\n * Behavior when logout is called without a refresh token.\n * @default \"revoke-all\"\n */\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n};\n\n/**\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\n * deprecation warning.\n *\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\n */\nexport type LegacyJwtConfig = {\n secret?: string;\n algorithm?: Algorithm;\n expiresIn?: string;\n refresh?: {\n secret?: string;\n enabled?: boolean;\n expiresIn?: string;\n rotation?: boolean;\n maxPerUser?: number;\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n };\n};\n\n/**\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\n * to a login page instead of returning the API-style JSON 401.\n *\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\n * always keep the JSON 401 contract regardless of this setting.\n */\nexport type PageAuthConfig = {\n /**\n * Login path a guarded page route redirects a logged-out browser to (e.g.\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\n * behavior is opt-in and backward-compatible.\n */\n loginPath?: string;\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed.\n * @default \"returnUrl\"\n */\n returnUrlParam?: string;\n};\n\n/**\n * Data every email-verification / password-reset notification receives.\n */\nexport type OneTimeTokenNotificationData = {\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\n token: string;\n /** When the token stops working. */\n expiresAt: Date;\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\n url?: string;\n};\n\n/**\n * Anything auth can deliver a token through — a `defineNotification(...)`\n * result satisfies it, as does any object with a compatible `send`.\n */\nexport type AuthNotification = {\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\n};\n\n/** Builds the link a token notification points at. */\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\n\n/** Persists a new plaintext password for a user during a password reset. */\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\n\n/**\n * Email-verification configuration (`auth.verification`).\n */\nexport type EmailVerificationConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"24h\"\n */\n expiresIn?: string;\n /**\n * User attribute stamped with the verification `Date`. Declare it in the\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\n * @default \"emailVerifiedAt\"\n */\n field?: string;\n /** Replace the default verification email. */\n notification?: AuthNotification;\n /** Build the verification link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n};\n\n/**\n * Password-reset configuration (`auth.passwordReset`).\n */\nexport type PasswordResetConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"60m\"\n */\n expiresIn?: string;\n /**\n * User attribute `requestPasswordReset` looks the account up by.\n * @default \"email\"\n */\n identifierField?: string;\n /** Replace the default reset email. */\n notification?: AuthNotification;\n /** Build the reset link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n /**\n * Persist the new password yourself. By default auth saves a hash made by\n * the same `hashPassword` login verifies against, and falls back to the\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\n * the stored value with `verifyPassword` either way.\n */\n setPassword?: PasswordSetter;\n /**\n * Wait for the reset notification before `requestPasswordReset` resolves,\n * so a delivery error reaches the caller. Off by default: the notification\n * is sent in the background, so the response time does not reveal whether\n * the account exists. A background failure is logged and emitted as\n * `password.resetDeliveryFailed`.\n * @default false\n */\n awaitDelivery?: boolean;\n};\n\n/**\n * One-time token storage configuration (`auth.oneTimeToken`).\n */\nexport type OneTimeTokenConfig = {\n /** Override the persisted model — extend {@link OneTimeToken}. */\n model?: typeof OneTimeToken;\n};\n\nexport type AuthConfigurations = {\n /**\n * Define all user types — maps a user-type slug to its `Auth` model class so\n * tokens and the middleware can resolve the right model.\n */\n userType: {\n [userType: string]: ChildModel<Auth>;\n };\n /** Default user type used by `authMiddleware()` and options-only overloads. */\n defaultUserType?: string;\n /**\n * Decide whether a resolved user may authenticate or receive new tokens.\n * @default () => true\n */\n canAuthenticate?: CanAuthenticate;\n /**\n * How login identifiers are normalized before the user lookup. Default:\n * string values are trimmed and the `email` field is lower-cased, so\n * `\" Sara@x.io\"` finds the account stored as `sara@x.io`. If that finds no\n * user and the normalized value differs from what was sent (trimmed), the\n * lookup is retried once with the value as sent, so rows stored with capitals\n * keep working. Pass a function to normalize your own way (the retry still\n * applies), or `false` for exact matching.\n *\n * The login throttle buckets `email` by trimmed, lower-cased value either way.\n * @default trim string values, lower-case `email`\n */\n normalizeCredentials?: false | NormalizeCredentials;\n /**\n * Store only a SHA-256 digest of each access and refresh token in the\n * database, never the token itself, so a copy of the token tables (a\n * backup, a replica, a read-only injection) cannot be replayed as a login.\n *\n * No migration is needed: the digest goes in the existing `token` column,\n * and lookups accept both forms, so rows issued before the switch keep\n * working until they expire, and turning it off again signs no one out.\n * A row loaded from storage no longer carries its raw token; a freshly\n * issued one exposes it as `row.plainToken`.\n * @default false\n */\n hashTokensAtRest?: boolean;\n /**\n * After a successful password login, replace a stored hash made with another\n * algorithm or cost than `encryption.password` now asks for (a raised bcrypt\n * `salt`, or a switch to the `\"scrypt\"` driver) with a fresh one. A failure\n * to save is logged and never fails the login. Set `false` to keep hashes as\n * they are.\n * @default true\n */\n rehashPasswords?: boolean;\n /**\n * Access-token configuration (secret, expiry, algorithm, model override).\n */\n accessToken?: AccessTokenConfig;\n /**\n * Refresh-token configuration (rotation, lifetime, cap, model override).\n */\n refreshToken?: RefreshTokenConfig;\n /**\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\n */\n pageAuth?: PageAuthConfig;\n /**\n * Cookie auth session config — read by `authService.setAuthCookie` /\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\n */\n cookie?: CookieAuthConfig;\n /**\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\n */\n csrf?: CsrfConfig;\n /**\n * Email verification — token lifetime, verified field, notification override.\n */\n verification?: EmailVerificationConfig;\n /**\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\n */\n passwordReset?: PasswordResetConfig;\n /**\n * One-time token (verification / reset) storage — model override.\n */\n oneTimeToken?: OneTimeTokenConfig;\n /**\n * Redirect login providers (`google`, `custom`) and account-linking policy.\n */\n providers?: ProvidersConfig;\n /**\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\n */\n passkeys?: PasskeysConfig;\n /**\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\n */\n otp?: OtpConfig;\n /**\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\n */\n jwt?: LegacyJwtConfig;\n};\n\nexport type AccessTokenOutput = {\n /**\n * JWT Token\n */\n token: string;\n /**\n * Exprie time in ISO format UTC time\n */\n expiresAt: string;\n};\n\n/**\n * Token pair returned after login or token refresh\n */\nexport type TokenPair = {\n /**\n * JWT access token (short-lived)\n */\n accessToken: AccessTokenOutput;\n /**\n * JWT refresh token (long-lived)\n */\n refreshToken?: AccessTokenOutput;\n};\n\n/**\n * Device information for session tracking\n */\nexport type DeviceInfo = {\n /**\n * User agent string from request\n */\n userAgent?: string;\n /**\n * Client IP address\n */\n ip?: string;\n /**\n * Optional device identifier\n */\n deviceId?: string;\n /**\n * Token family ID (for rotation tracking)\n * @internal\n */\n familyId?: string;\n /**\n * Access token payload\n */\n payload?: Record<string, unknown>;\n};\n\nexport type LoginResult<UserType extends Auth> = {\n user: UserType;\n tokens: TokenPair;\n};\n\n/** Selects a cookie Domain for one request; return `undefined` for a host-only cookie. */\nexport type CookieDomainResolver = (request: Request) => string | undefined;\n\n/**\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\n * configurable here — they come from core's `secureCookieDefaults()`, the\n * same floor every `response.cookie()` call gets, so a cookie auth session can\n * never be weakened to a laxer policy than the framework default.\n */\nexport type CookieAuthConfig = {\n /**\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\n * `cookie:<name>` token source must match to read it back.\n * @default \"access_token\"\n */\n name?: string;\n /**\n * Cookie name the session helpers write and clear for the refresh token.\n * @default \"refresh_token\"\n */\n refreshName?: string;\n /**\n * Cookie `Path` attribute.\n * @default \"/\"\n */\n path?: string;\n /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */\n cookieDomain?: CookieDomainResolver;\n /**\n * Write the auth cookies under a `__Host-` name prefix (`__Host-access_token`,\n * `__Host-refresh_token`). Browsers accept such a cookie only when it is\n * Secure, has `Path=/` and no `Domain`, so a subdomain or a plain-HTTP page\n * cannot plant or overwrite the session cookie. Requires `path: \"/\"` and no\n * `cookieDomain`; a write that breaks either rule throws naming the setting.\n *\n * While switching, the unprefixed cookie is still read (so signed-in users\n * stay signed in) and both names are cleared on logout.\n * @default false\n */\n hostPrefix?: boolean;\n};\n\n/**\n * CSRF Origin-check configuration. Read via\n * `authConfig.csrf.allowedOrigins()`.\n */\nexport type CsrfConfig = {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * in addition to the request's own origin.\n * @default []\n */\n allowedOrigins?: string[];\n};\n\n/**\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\n * falls back to `auth.cookie.*` config, then the package default. Cookie\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\n * see {@link CookieAuthConfig}.\n */\nexport type SetAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\n path?: string;\n /** Cookie `Domain` attribute. Omit for a host-only cookie. */\n domain?: string;\n /**\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\n * bare token string with no `maxAge` produces a session cookie (cleared\n * when the browser closes).\n */\n maxAge?: number;\n};\n\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\nexport type ClearAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\n path?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
@@ -69,7 +69,7 @@ export type LoginThrottleOptions = {
69
69
  *
70
70
  * Ignored when `identify` is set or `by` does not track both.
71
71
  *
72
- * @default "global"
72
+ * @default "global" (changes to `"pair"` in 6.0; set it explicitly to choose now)
73
73
  */
74
74
  emailLock?: "pair" | "global";
75
75
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"login-throttle.middleware.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;YAmBY;;;;;;;;;;;;YAaA;;;;;;;;EAQV;;;;;;EAOA;;;;;;EAOA;;;;;;EAOA,KAAK;;;;;;;;EASL;;;;;;;;;;;;;;;EAgBA;;;;;;;EAQA;;;;EAKA;;;;;;;;EASA,aAAa,UAAU;;;;;;EAOvB,YAAY,SAAS;;;;;;;;;;;;;;;;wBAwCP,uBAAuB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAiLrC,wBAAwB,UAAS,uBAA4B"}
1
+ {"version":3,"file":"login-throttle.middleware.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;YAmBY;;;;;;;;;;;;YAaA;;;;;;;;EAQV;;;;;;EAOA;;;;;;EAOA;;;;;;EAOA,KAAK;;;;;;;;EASL;;;;;;;;;;;;;;;EAgBA;;;;;;;EAQA;;;;EAKA;;;;;;;;EASA,aAAa,UAAU;;;;;;EAOvB,YAAY,SAAS;;;;;;;;;;;;;;;;wBAwCP,uBAAuB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAuNrC,wBAAwB,UAAS,uBAA4B"}
@@ -112,7 +112,8 @@ function buildDefaultIdentifiers(request, tracked, credentialField, max, pair) {
112
112
  }
113
113
  if (ip) identifiers.push({
114
114
  key: `ip.${throttleIdentifierHash("ip", ip)}`,
115
- max
115
+ max,
116
+ resetOnSuccess: email === void 0
116
117
  });
117
118
  return identifiers;
118
119
  }
@@ -133,6 +134,20 @@ async function counterWasReset(identifier, count) {
133
134
  if (typeof current === "string" && current.trim() !== "") current = Number(current);
134
135
  return typeof current === "number" && Number.isFinite(current) && current < count;
135
136
  }
137
+ /** Whether the default-`emailLock` warning was already logged. */
138
+ let warnedEmailLock = false;
139
+ /**
140
+ * Warn (once) when `emailLock` is left unset while both the account and the
141
+ * source are tracked: the default locks an email for everyone, so one IP can
142
+ * lock a victim out, and the default becomes `"pair"` in 6.0.
143
+ */
144
+ function warnAboutDefaultEmailLock(options) {
145
+ if (warnedEmailLock || options.emailLock !== void 0 || options.identify !== void 0) return;
146
+ const tracked = options.by ?? ["email", "ip"];
147
+ if (!tracked.includes("email") || !tracked.includes("ip")) return;
148
+ warnedEmailLock = true;
149
+ log.warn("auth", "login-throttle", "loginThrottleMiddleware() locks an email for every source by default (emailLock: \"global\"), so one IP can lock a victim's account. The default changes to \"pair\" in 6.0: set emailLock explicitly to choose now.");
150
+ }
136
151
  /**
137
152
  * Failure-aware login throttle. Locks an identifier (account, IP, or both)
138
153
  * after too many failed login attempts within a window — without penalising
@@ -175,6 +190,7 @@ async function counterWasReset(identifier, count) {
175
190
  * });
176
191
  */
177
192
  function loginThrottleMiddleware(options = {}) {
193
+ warnAboutDefaultEmailLock(options);
178
194
  const max = options.max ?? 5;
179
195
  const window = options.window ?? "15m";
180
196
  const lockoutDuration = options.lockoutDuration ?? "15m";
@@ -229,6 +245,7 @@ function loginThrottleMiddleware(options = {}) {
229
245
  try {
230
246
  if (!(options.isFailure ? options.isFailure(resolvedResponse) : !resolvedResponse.isOk)) {
231
247
  for (const identifier of identifiers) {
248
+ if (identifier.resetOnSuccess === false) continue;
232
249
  await cache.set(counterKey(identifier.key), 0, { ttl: window });
233
250
  await cache.remove(lockKey(identifier.key));
234
251
  }
@@ -1 +1 @@
1
- {"version":3,"file":"login-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport { cache } from \"@warlock.js/cache\";\nimport { t, type Middleware, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport { authConfig } from \"../services/auth-config\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport { normalizeEmailIdentifier } from \"../utils/normalize-credentials\";\n\n/**\n * Built-in identifier kinds the throttle knows how to extract from a request.\n *\n * - `\"email\"` tracks per-account, so an attacker can't spray one user from\n * many IPs.\n * - `\"ip\"` tracks per-source, so an attacker can't stuff many accounts from\n * one IP.\n *\n * Lockout trips when ANY tracked identifier crosses `max` — defense-in-depth.\n */\nexport type LoginThrottleIdentifier = \"email\" | \"ip\";\n\n/**\n * Options for {@link loginThrottleMiddleware}.\n *\n * Failure-aware by design: every attempt is counted when it arrives (so a\n * burst of concurrent requests cannot outrun the limit), and a successful\n * response (2xx, or whatever `isFailure` says) resets the count, so a user who\n * types a wrong password three times then the right one is not penalised.\n *\n * @example\n * loginThrottleMiddleware({ max: 5, window: \"15m\", lockoutDuration: \"15m\" });\n */\nexport type LoginThrottleOptions = {\n /**\n * Failures allowed within the window before the identifier is locked. It\n * also caps how many attempts may be in flight at once: a request beyond it\n * is refused with `429` before the controller runs.\n *\n * @default 5\n */\n max?: number;\n\n /**\n * Counting window. `ms`-format string (`\"15m\"`, `\"1h\"`) or seconds as a number.\n *\n * @default \"15m\"\n */\n window?: string | number;\n\n /**\n * Lockout duration once the threshold is tripped. `ms`-format string or seconds.\n *\n * @default \"15m\"\n */\n lockoutDuration?: string | number;\n\n /**\n * Identifiers tracked. Each is counted and locked independently.\n *\n * @default [\"email\", \"ip\"]\n */\n by?: LoginThrottleIdentifier[];\n\n /**\n * Credential field consulted when `\"email\"` is tracked. Switch to\n * `\"username\"` (or any other input field) for systems that don't\n * authenticate by email.\n *\n * @default \"email\"\n */\n identifierKey?: string;\n\n /**\n * Who an account lock applies to when both `\"email\"` and `\"ip\"` are tracked.\n *\n * - `\"global\"` — `max` failures for an email, from any source, lock that\n * email for everyone (the account owner included).\n * - `\"pair\"` — the `max` lock applies to the (email, source IP) pair, so a\n * stranger guessing from their own IP cannot lock the owner out. The email\n * alone keeps a wider bucket (`accountMax`) that still stops guessing\n * spread across many IPs.\n *\n * Ignored when `identify` is set or `by` does not track both.\n *\n * @default \"global\"\n */\n emailLock?: \"pair\" | \"global\";\n\n /**\n * Attempts one email may take from all sources together within the window\n * before it is locked, when `emailLock` is `\"pair\"`.\n *\n * @default max * 10\n */\n accountMax?: number;\n\n /**\n * Override the default error message returned with the 429 response.\n */\n errorMessage?: string;\n\n /**\n * Decide whether the response represents a failed login. Defaults to\n * \"non-2xx is a failure\"; override if your controller signals failure\n * through a 200-style body.\n *\n * @default (response) => !response.isOk\n */\n isFailure?: (response: Response) => boolean;\n\n /**\n * Compute the identifiers tracked for this request. Override to derive the\n * account key from a header, a JWT subject, or any other shape that does\n * not match the built-in `email` / `ip` extraction.\n */\n identify?: (request: Request) => string[];\n};\n\nconst COUNTER_PREFIX = \"auth.throttle.count.\";\nconst LOCK_PREFIX = \"auth.throttle.lock.\";\n\nconst counterKey = (identifier: string): string => `${COUNTER_PREFIX}${identifier}`;\nconst lockKey = (identifier: string): string => `${LOCK_PREFIX}${identifier}`;\n\n/**\n * The key a throttle identifier is hashed with: an HMAC key derived from\n * `auth.accessToken.secret` (the same root the OTP code MAC uses), or\n * `undefined` when no secret is configured.\n */\nfunction throttleHashKey(): Buffer | undefined {\n let secret: string | undefined;\n\n try {\n secret = authConfig.accessToken.secret();\n } catch {\n return undefined;\n }\n\n return createHmac(\"sha256\", secret).update(\"@warlock.js/auth:throttle\").digest();\n}\n\n/**\n * Hash of a throttle identifier (`kind` is `\"email\"`, `\"ip\"`, ...). The value\n * is trimmed and lower-cased first, so `\" Sara@x.io\"` and `\"sara@x.io\"` share\n * one bucket.\n *\n * Identifiers become part of cache keys, and cache drivers log their keys: a\n * raw email or IP there is personal data in a log line. A plain SHA-256 of an\n * email is reversible by anyone with a list of addresses, so the hash is\n * keyed (HMAC) with a key derived from `auth.accessToken.secret`. Without a\n * configured secret it falls back to SHA-256, which still keeps the address\n * out of the key.\n *\n * Exported for tests and for apps that inspect throttle keys.\n */\nexport function throttleIdentifierHash(kind: string, value: string): string {\n const normalized = `${kind}:${normalizeEmailIdentifier(value)}`;\n const key = throttleHashKey();\n\n return key\n ? createHmac(\"sha256\", key).update(normalized).digest(\"hex\")\n : createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\nlet warnedNullDriver = false;\n\n/**\n * The `null` cache driver stores nothing: every count reads back as 1 and no\n * lock is ever found, so the throttle silently never trips. Say so once.\n */\nfunction warnIfNullDriver(): void {\n if (warnedNullDriver) return;\n\n const driverName = (cache as { currentDriver?: { name?: string } }).currentDriver?.name;\n\n if (driverName !== \"null\") return;\n\n warnedNullDriver = true;\n log.warn(\n \"auth\",\n \"login-throttle\",\n \"The cache driver is `null`, so login, token and OTP throttles never lock. Use a real cache driver (redis, pg, or memory for one process).\",\n );\n}\n\n/**\n * A lock value is the lockout deadline (epoch ms). `true`, written by 5.29\n * and earlier, still counts as locked until the key expires.\n */\nfunction isLocked(value: unknown): boolean {\n if (typeof value === \"number\") {\n return value > Date.now();\n }\n\n return Boolean(value);\n}\n\n/**\n * `ms`'s honest runtime signature (see `services/auth-config.ts`): it returns\n * `undefined` for text it cannot parse and throws for `\"\"`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * `\"15m\"` / `\"1h\"` / seconds as a number → seconds, or `undefined` when the\n * value cannot be parsed (the cache rejects such a TTL anyway).\n */\nfunction durationSeconds(duration: string | number): number | undefined {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? duration : undefined;\n }\n\n let milliseconds: number | string | undefined;\n\n try {\n milliseconds = parseMs(duration);\n } catch {\n milliseconds = undefined;\n }\n\n return typeof milliseconds === \"number\" && Number.isFinite(milliseconds) && milliseconds > 0\n ? milliseconds / 1000\n : undefined;\n}\n\n/**\n * Built-in identifier extractor — reads the configured credential field from\n * the request body for the per-account key, and `request.detectIp()` for the\n * per-source key. Untruthy values are dropped; a request that yields zero\n * identifiers is left untracked so the middleware no-ops for it.\n */\nfunction buildDefaultIdentifiers(\n request: Request,\n tracked: LoginThrottleIdentifier[],\n credentialField: string,\n max: number,\n pair: { accountMax: number } | undefined,\n): TrackedIdentifier[] {\n const identifiers: TrackedIdentifier[] = [];\n const value = tracked.includes(\"email\") ? request.input(credentialField) : undefined;\n const email = typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n const ip = tracked.includes(\"ip\") ? request.detectIp() : undefined;\n\n if (email !== undefined) {\n if (pair && ip) {\n // The hard lock belongs to this source only; the email-wide bucket is\n // wider, so a stranger cannot lock the owner out with `max` guesses.\n const pairValue = `${normalizeEmailIdentifier(email)}|${ip}`;\n\n identifiers.push({ key: `email-ip.${throttleIdentifierHash(\"email-ip\", pairValue)}`, max });\n identifiers.push({\n key: `email.${throttleIdentifierHash(\"email\", email)}`,\n max: pair.accountMax,\n });\n } else {\n identifiers.push({ key: `email.${throttleIdentifierHash(\"email\", email)}`, max });\n }\n }\n\n if (ip) {\n identifiers.push({ key: `ip.${throttleIdentifierHash(\"ip\", ip)}`, max });\n }\n\n return identifiers;\n}\n\n/** One throttle bucket: its cache-key suffix and the attempts it allows. */\ntype TrackedIdentifier = { key: string; max: number };\n\n/**\n * Whether the counter now reads a number below `count`, i.e. a success reset\n * it while this attempt ran. Fails closed: a missing value (expired, evicted,\n * a driver that stores nothing), a non-numeric one or a failed read all answer\n * `false`, so the caller locks.\n */\nasync function counterWasReset(identifier: string, count: number): Promise<boolean> {\n let current: unknown;\n\n try {\n current = await cache.get(counterKey(identifier));\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n\n return false;\n }\n\n if (typeof current === \"string\" && current.trim() !== \"\") current = Number(current);\n\n return typeof current === \"number\" && Number.isFinite(current) && current < count;\n}\n\n/**\n * Failure-aware login throttle. Locks an identifier (account, IP, or both)\n * after too many failed login attempts within a window — without penalising\n * a user who eventually types the right password.\n *\n * Mechanism (per identifier):\n *\n * 1. **Before the controller** — reject with `429` if a lock key is set,\n * skipping the DB lookup AND the bcrypt verify (this also neutralises the\n * CPU-DoS angle of brute-forcing). Otherwise count the attempt in a\n * fixed-window counter right away, and reject with `429` (setting the lock)\n * when it goes past `max`. Counting at entry is what bounds a burst of\n * concurrent requests: at most `max` attempts per window reach the\n * controller, however many arrive at once.\n * 2. **After the controller** — observe the outcome via `response.onSent`.\n * On failure (non-2xx by default), set a lock key with `lockoutDuration`\n * TTL once the attempt count has reached `max` (unless a success reset the\n * counter meanwhile). On success, reset the counter to 0 and clear the lock\n * for that identifier.\n *\n * Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,\n * transitively guaranteed via `@warlock.js/core`). Lockout state is shared\n * across replicas — correct security model, because an attacker can't bypass\n * by round-robin to a different pod. Every cache call is guarded so a\n * misconfigured driver fails open (a throttle outage must never escalate\n * into a full auth outage).\n *\n * @example\n * import { loginThrottleMiddleware } from \"@warlock.js/auth\";\n * import { router } from \"@warlock.js/core\";\n *\n * router.post(\"/auth/login\", loginController, {\n * middleware: [loginThrottleMiddleware({ max: 5, window: \"15m\" })],\n * });\n *\n * @example\n * // Per-IP only — avoid account-lockout-as-DoS on anonymous-attack vectors\n * router.post(\"/auth/refresh-token\", refreshController, {\n * middleware: [loginThrottleMiddleware({ by: [\"ip\"], max: 10, window: \"1m\" })],\n * });\n */\nexport function loginThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n const max = options.max ?? 5;\n const window = options.window ?? \"15m\";\n const lockoutDuration = options.lockoutDuration ?? \"15m\";\n const tracked = options.by ?? [\"email\", \"ip\"];\n const credentialField = options.identifierKey ?? \"email\";\n const pair =\n options.emailLock === \"pair\" && tracked.includes(\"email\") && tracked.includes(\"ip\")\n ? { accountMax: options.accountMax ?? max * 10 }\n : undefined;\n\n /**\n * Lock an identifier for `lockoutDuration`. The counter is rewritten with\n * the same TTL, so the two expire together and the identifier starts a fresh\n * window once the lockout ends. Rewriting keeps a value of at least `count`,\n * so a request that slipped past the lock check still sees \"over the limit\".\n */\n const lock = async (identifier: string, count: number): Promise<void> => {\n const lockSeconds = durationSeconds(lockoutDuration);\n\n // The lock stores its own deadline: a driver with sliding expiration\n // (`memoryExtended`) pushes the key's TTL forward on every read, but the\n // deadline in the value does not move, so a client that keeps retrying is\n // still released after `lockoutDuration`.\n await cache.set(\n lockKey(identifier),\n lockSeconds === undefined ? true : Date.now() + lockSeconds * 1000,\n { ttl: lockoutDuration },\n );\n await cache.set(counterKey(identifier), count, { ttl: lockoutDuration });\n };\n\n return async ({ request, response }) => {\n const identifiers: TrackedIdentifier[] = options.identify\n ? options.identify(request).map((key) => ({ key, max }))\n : buildDefaultIdentifiers(request, tracked, credentialField, max, pair);\n\n if (identifiers.length === 0) return;\n\n warnIfNullDriver();\n\n const tooManyRequests = () =>\n response.tooManyRequests({\n error: options.errorMessage ?? t(\"auth.errors.tooManyAttempts\"),\n errorCode: AuthErrorCodes.TooManyAttempts,\n });\n\n /** The attempt number this request took in each identifier's window. */\n const counts = new Map<string, number>();\n\n try {\n for (const identifier of identifiers) {\n if (isLocked(await cache.get(lockKey(identifier.key)))) {\n return tooManyRequests();\n }\n }\n\n for (const identifier of identifiers) {\n const key = counterKey(identifier.key);\n\n // Open the window on the first attempt: the create-only write means\n // only one of several racing servers sets the TTL, and an existing\n // window keeps its deadline (fixed window). The bump itself is an\n // atomic increment, so concurrent attempts across servers are never\n // lost (redis INCRBY / pg upsert keep the window's TTL). Passing the\n // TTL on the bump also expires a key recreated after the seed.\n await cache.set(key, 0, { ttl: window, onConflict: \"create\" });\n const count = await cache.increment(key, 1, { ttl: window });\n\n if (typeof count !== \"number\" || !Number.isFinite(count)) continue;\n\n counts.set(identifier.key, count);\n\n if (count > identifier.max) {\n if (count === identifier.max + 1) {\n await lock(identifier.key, count);\n }\n\n return tooManyRequests();\n }\n }\n } catch (error) {\n // Fail open — a cache outage (driver not initialised, network blip)\n // must never escalate into a full auth outage. Log and let the request\n // through; the onSent recorder below is independently guarded so an\n // outage there is also harmless.\n log.error(\"auth\", \"login-throttle\", error);\n\n return;\n }\n\n response.onSent(async (resolvedResponse: Response) => {\n try {\n const failed = options.isFailure\n ? options.isFailure(resolvedResponse)\n : !resolvedResponse.isOk;\n\n if (!failed) {\n for (const identifier of identifiers) {\n // Reset to 0 rather than delete: a failure still in flight reads\n // the 0 as proof that a success reset the window (see below).\n await cache.set(counterKey(identifier.key), 0, { ttl: window });\n await cache.remove(lockKey(identifier.key));\n }\n\n return;\n }\n\n // Already counted at entry; a failure that used the last allowed\n // attempt starts the lockout, unless a success that finished while it\n // ran reset the counter (a correct login racing a mistyped one must\n // not lock the account it just signed in to).\n for (const identifier of identifiers) {\n const count = counts.get(identifier.key);\n\n if (count === undefined || count < identifier.max) continue;\n\n if (await counterWasReset(identifier.key, count)) continue;\n\n await lock(identifier.key, count);\n }\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AAsHA,MAAM,iBAAiB;AACvB,MAAM,cAAc;AAEpB,MAAM,cAAc,eAA+B,GAAG,iBAAiB;AACvE,MAAM,WAAW,eAA+B,GAAG,cAAc;;;;;;AAOjE,SAAS,kBAAsC;CAC7C,IAAI;CAEJ,IAAI;EACF,SAAS,WAAW,YAAY,OAAO;CACzC,QAAQ;EACN;CACF;CAEA,OAAO,WAAW,UAAU,MAAM,CAAC,CAAC,OAAO,2BAA2B,CAAC,CAAC,OAAO;AACjF;;;;;;;;;;;;;;;AAgBA,SAAgB,uB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AAgB,IAClC,CAAC,iBAAiB,OAET;KACX,KAAK,MAAM,cAAc,aAAa;MAGpC,MAAM,MAAM,IAAI,WAAW,WAAW,GAAG,GAAG,GAAG,EAAE,KAAK,OAAO,CAAC;MAC9D,MAAM,MAAM,OAAO,QAAQ,WAAW,GAAG,CAAC;KAC5C;KAEA;IACF;IAMA,KAAK,MAAM,cAAc,aAAa;KACpC,MAAM,QAAQ,OAAO,IAAI,WAAW,GAAG;KAEvC,IAAI,UAAU,UAAa,QAAQ,WAAW,KAAK;KAEnD,IAAI,MAAM,gBAAgB,WAAW,KAAK,KAAK,GAAG;KAElD,MAAM,KAAK,WAAW,KAAK,KAAK;IAClC;GACF,SAAS,OAAO;IACd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAC3C;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"login-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport { cache } from \"@warlock.js/cache\";\nimport { t, type Middleware, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport { authConfig } from \"../services/auth-config\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport { normalizeEmailIdentifier } from \"../utils/normalize-credentials\";\n\n/**\n * Built-in identifier kinds the throttle knows how to extract from a request.\n *\n * - `\"email\"` tracks per-account, so an attacker can't spray one user from\n * many IPs.\n * - `\"ip\"` tracks per-source, so an attacker can't stuff many accounts from\n * one IP.\n *\n * Lockout trips when ANY tracked identifier crosses `max` — defense-in-depth.\n */\nexport type LoginThrottleIdentifier = \"email\" | \"ip\";\n\n/**\n * Options for {@link loginThrottleMiddleware}.\n *\n * Failure-aware by design: every attempt is counted when it arrives (so a\n * burst of concurrent requests cannot outrun the limit), and a successful\n * response (2xx, or whatever `isFailure` says) resets the count, so a user who\n * types a wrong password three times then the right one is not penalised.\n *\n * @example\n * loginThrottleMiddleware({ max: 5, window: \"15m\", lockoutDuration: \"15m\" });\n */\nexport type LoginThrottleOptions = {\n /**\n * Failures allowed within the window before the identifier is locked. It\n * also caps how many attempts may be in flight at once: a request beyond it\n * is refused with `429` before the controller runs.\n *\n * @default 5\n */\n max?: number;\n\n /**\n * Counting window. `ms`-format string (`\"15m\"`, `\"1h\"`) or seconds as a number.\n *\n * @default \"15m\"\n */\n window?: string | number;\n\n /**\n * Lockout duration once the threshold is tripped. `ms`-format string or seconds.\n *\n * @default \"15m\"\n */\n lockoutDuration?: string | number;\n\n /**\n * Identifiers tracked. Each is counted and locked independently.\n *\n * @default [\"email\", \"ip\"]\n */\n by?: LoginThrottleIdentifier[];\n\n /**\n * Credential field consulted when `\"email\"` is tracked. Switch to\n * `\"username\"` (or any other input field) for systems that don't\n * authenticate by email.\n *\n * @default \"email\"\n */\n identifierKey?: string;\n\n /**\n * Who an account lock applies to when both `\"email\"` and `\"ip\"` are tracked.\n *\n * - `\"global\"` — `max` failures for an email, from any source, lock that\n * email for everyone (the account owner included).\n * - `\"pair\"` — the `max` lock applies to the (email, source IP) pair, so a\n * stranger guessing from their own IP cannot lock the owner out. The email\n * alone keeps a wider bucket (`accountMax`) that still stops guessing\n * spread across many IPs.\n *\n * Ignored when `identify` is set or `by` does not track both.\n *\n * @default \"global\" (changes to `\"pair\"` in 6.0; set it explicitly to choose now)\n */\n emailLock?: \"pair\" | \"global\";\n\n /**\n * Attempts one email may take from all sources together within the window\n * before it is locked, when `emailLock` is `\"pair\"`.\n *\n * @default max * 10\n */\n accountMax?: number;\n\n /**\n * Override the default error message returned with the 429 response.\n */\n errorMessage?: string;\n\n /**\n * Decide whether the response represents a failed login. Defaults to\n * \"non-2xx is a failure\"; override if your controller signals failure\n * through a 200-style body.\n *\n * @default (response) => !response.isOk\n */\n isFailure?: (response: Response) => boolean;\n\n /**\n * Compute the identifiers tracked for this request. Override to derive the\n * account key from a header, a JWT subject, or any other shape that does\n * not match the built-in `email` / `ip` extraction.\n */\n identify?: (request: Request) => string[];\n};\n\nconst COUNTER_PREFIX = \"auth.throttle.count.\";\nconst LOCK_PREFIX = \"auth.throttle.lock.\";\n\nconst counterKey = (identifier: string): string => `${COUNTER_PREFIX}${identifier}`;\nconst lockKey = (identifier: string): string => `${LOCK_PREFIX}${identifier}`;\n\n/**\n * The key a throttle identifier is hashed with: an HMAC key derived from\n * `auth.accessToken.secret` (the same root the OTP code MAC uses), or\n * `undefined` when no secret is configured.\n */\nfunction throttleHashKey(): Buffer | undefined {\n let secret: string | undefined;\n\n try {\n secret = authConfig.accessToken.secret();\n } catch {\n return undefined;\n }\n\n return createHmac(\"sha256\", secret).update(\"@warlock.js/auth:throttle\").digest();\n}\n\n/**\n * Hash of a throttle identifier (`kind` is `\"email\"`, `\"ip\"`, ...). The value\n * is trimmed and lower-cased first, so `\" Sara@x.io\"` and `\"sara@x.io\"` share\n * one bucket.\n *\n * Identifiers become part of cache keys, and cache drivers log their keys: a\n * raw email or IP there is personal data in a log line. A plain SHA-256 of an\n * email is reversible by anyone with a list of addresses, so the hash is\n * keyed (HMAC) with a key derived from `auth.accessToken.secret`. Without a\n * configured secret it falls back to SHA-256, which still keeps the address\n * out of the key.\n *\n * Exported for tests and for apps that inspect throttle keys.\n */\nexport function throttleIdentifierHash(kind: string, value: string): string {\n const normalized = `${kind}:${normalizeEmailIdentifier(value)}`;\n const key = throttleHashKey();\n\n return key\n ? createHmac(\"sha256\", key).update(normalized).digest(\"hex\")\n : createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\nlet warnedNullDriver = false;\n\n/**\n * The `null` cache driver stores nothing: every count reads back as 1 and no\n * lock is ever found, so the throttle silently never trips. Say so once.\n */\nfunction warnIfNullDriver(): void {\n if (warnedNullDriver) return;\n\n const driverName = (cache as { currentDriver?: { name?: string } }).currentDriver?.name;\n\n if (driverName !== \"null\") return;\n\n warnedNullDriver = true;\n log.warn(\n \"auth\",\n \"login-throttle\",\n \"The cache driver is `null`, so login, token and OTP throttles never lock. Use a real cache driver (redis, pg, or memory for one process).\",\n );\n}\n\n/**\n * A lock value is the lockout deadline (epoch ms). `true`, written by 5.29\n * and earlier, still counts as locked until the key expires.\n */\nfunction isLocked(value: unknown): boolean {\n if (typeof value === \"number\") {\n return value > Date.now();\n }\n\n return Boolean(value);\n}\n\n/**\n * `ms`'s honest runtime signature (see `services/auth-config.ts`): it returns\n * `undefined` for text it cannot parse and throws for `\"\"`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * `\"15m\"` / `\"1h\"` / seconds as a number → seconds, or `undefined` when the\n * value cannot be parsed (the cache rejects such a TTL anyway).\n */\nfunction durationSeconds(duration: string | number): number | undefined {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? duration : undefined;\n }\n\n let milliseconds: number | string | undefined;\n\n try {\n milliseconds = parseMs(duration);\n } catch {\n milliseconds = undefined;\n }\n\n return typeof milliseconds === \"number\" && Number.isFinite(milliseconds) && milliseconds > 0\n ? milliseconds / 1000\n : undefined;\n}\n\n/**\n * Built-in identifier extractor — reads the configured credential field from\n * the request body for the per-account key, and `request.detectIp()` for the\n * per-source key. Untruthy values are dropped; a request that yields zero\n * identifiers is left untracked so the middleware no-ops for it.\n */\nfunction buildDefaultIdentifiers(\n request: Request,\n tracked: LoginThrottleIdentifier[],\n credentialField: string,\n max: number,\n pair: { accountMax: number } | undefined,\n): TrackedIdentifier[] {\n const identifiers: TrackedIdentifier[] = [];\n const value = tracked.includes(\"email\") ? request.input(credentialField) : undefined;\n const email = typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n const ip = tracked.includes(\"ip\") ? request.detectIp() : undefined;\n\n if (email !== undefined) {\n if (pair && ip) {\n // The hard lock belongs to this source only; the email-wide bucket is\n // wider, so a stranger cannot lock the owner out with `max` guesses.\n const pairValue = `${normalizeEmailIdentifier(email)}|${ip}`;\n\n identifiers.push({ key: `email-ip.${throttleIdentifierHash(\"email-ip\", pairValue)}`, max });\n identifiers.push({\n key: `email.${throttleIdentifierHash(\"email\", email)}`,\n max: pair.accountMax,\n });\n } else {\n identifiers.push({ key: `email.${throttleIdentifierHash(\"email\", email)}`, max });\n }\n }\n\n if (ip) {\n identifiers.push({\n key: `ip.${throttleIdentifierHash(\"ip\", ip)}`,\n max,\n // Alone, the source bucket is the only bound there is, so a success still clears it.\n resetOnSuccess: email === undefined,\n });\n }\n\n return identifiers;\n}\n\n/** One throttle bucket: its cache-key suffix and the attempts it allows. */\ntype TrackedIdentifier = {\n key: string;\n max: number;\n /**\n * Whether a successful login clears this bucket. `false` for the shared\n * source bucket when an account bucket is tracked next to it, so one\n * valid account behind an IP cannot keep resetting that IP's budget.\n */\n resetOnSuccess?: boolean;\n};\n\n/**\n * Whether the counter now reads a number below `count`, i.e. a success reset\n * it while this attempt ran. Fails closed: a missing value (expired, evicted,\n * a driver that stores nothing), a non-numeric one or a failed read all answer\n * `false`, so the caller locks.\n */\nasync function counterWasReset(identifier: string, count: number): Promise<boolean> {\n let current: unknown;\n\n try {\n current = await cache.get(counterKey(identifier));\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n\n return false;\n }\n\n if (typeof current === \"string\" && current.trim() !== \"\") current = Number(current);\n\n return typeof current === \"number\" && Number.isFinite(current) && current < count;\n}\n\n/** Whether the default-`emailLock` warning was already logged. */\nlet warnedEmailLock = false;\n\n/**\n * Warn (once) when `emailLock` is left unset while both the account and the\n * source are tracked: the default locks an email for everyone, so one IP can\n * lock a victim out, and the default becomes `\"pair\"` in 6.0.\n */\nfunction warnAboutDefaultEmailLock(options: LoginThrottleOptions): void {\n if (warnedEmailLock || options.emailLock !== undefined || options.identify !== undefined) return;\n\n const tracked = options.by ?? [\"email\", \"ip\"];\n\n if (!tracked.includes(\"email\") || !tracked.includes(\"ip\")) return;\n\n warnedEmailLock = true;\n\n log.warn(\n \"auth\",\n \"login-throttle\",\n 'loginThrottleMiddleware() locks an email for every source by default (emailLock: \"global\"), so one IP can lock a victim\\'s account. The default changes to \"pair\" in 6.0: set emailLock explicitly to choose now.',\n );\n}\n\n/**\n * Failure-aware login throttle. Locks an identifier (account, IP, or both)\n * after too many failed login attempts within a window — without penalising\n * a user who eventually types the right password.\n *\n * Mechanism (per identifier):\n *\n * 1. **Before the controller** — reject with `429` if a lock key is set,\n * skipping the DB lookup AND the bcrypt verify (this also neutralises the\n * CPU-DoS angle of brute-forcing). Otherwise count the attempt in a\n * fixed-window counter right away, and reject with `429` (setting the lock)\n * when it goes past `max`. Counting at entry is what bounds a burst of\n * concurrent requests: at most `max` attempts per window reach the\n * controller, however many arrive at once.\n * 2. **After the controller** — observe the outcome via `response.onSent`.\n * On failure (non-2xx by default), set a lock key with `lockoutDuration`\n * TTL once the attempt count has reached `max` (unless a success reset the\n * counter meanwhile). On success, reset the counter to 0 and clear the lock\n * for that identifier.\n *\n * Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,\n * transitively guaranteed via `@warlock.js/core`). Lockout state is shared\n * across replicas — correct security model, because an attacker can't bypass\n * by round-robin to a different pod. Every cache call is guarded so a\n * misconfigured driver fails open (a throttle outage must never escalate\n * into a full auth outage).\n *\n * @example\n * import { loginThrottleMiddleware } from \"@warlock.js/auth\";\n * import { router } from \"@warlock.js/core\";\n *\n * router.post(\"/auth/login\", loginController, {\n * middleware: [loginThrottleMiddleware({ max: 5, window: \"15m\" })],\n * });\n *\n * @example\n * // Per-IP only — avoid account-lockout-as-DoS on anonymous-attack vectors\n * router.post(\"/auth/refresh-token\", refreshController, {\n * middleware: [loginThrottleMiddleware({ by: [\"ip\"], max: 10, window: \"1m\" })],\n * });\n */\nexport function loginThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n warnAboutDefaultEmailLock(options);\n\n const max = options.max ?? 5;\n const window = options.window ?? \"15m\";\n const lockoutDuration = options.lockoutDuration ?? \"15m\";\n const tracked = options.by ?? [\"email\", \"ip\"];\n const credentialField = options.identifierKey ?? \"email\";\n const pair =\n options.emailLock === \"pair\" && tracked.includes(\"email\") && tracked.includes(\"ip\")\n ? { accountMax: options.accountMax ?? max * 10 }\n : undefined;\n\n /**\n * Lock an identifier for `lockoutDuration`. The counter is rewritten with\n * the same TTL, so the two expire together and the identifier starts a fresh\n * window once the lockout ends. Rewriting keeps a value of at least `count`,\n * so a request that slipped past the lock check still sees \"over the limit\".\n */\n const lock = async (identifier: string, count: number): Promise<void> => {\n const lockSeconds = durationSeconds(lockoutDuration);\n\n // The lock stores its own deadline: a driver with sliding expiration\n // (`memoryExtended`) pushes the key's TTL forward on every read, but the\n // deadline in the value does not move, so a client that keeps retrying is\n // still released after `lockoutDuration`.\n await cache.set(\n lockKey(identifier),\n lockSeconds === undefined ? true : Date.now() + lockSeconds * 1000,\n { ttl: lockoutDuration },\n );\n await cache.set(counterKey(identifier), count, { ttl: lockoutDuration });\n };\n\n return async ({ request, response }) => {\n const identifiers: TrackedIdentifier[] = options.identify\n ? options.identify(request).map((key) => ({ key, max }))\n : buildDefaultIdentifiers(request, tracked, credentialField, max, pair);\n\n if (identifiers.length === 0) return;\n\n warnIfNullDriver();\n\n const tooManyRequests = () =>\n response.tooManyRequests({\n error: options.errorMessage ?? t(\"auth.errors.tooManyAttempts\"),\n errorCode: AuthErrorCodes.TooManyAttempts,\n });\n\n /** The attempt number this request took in each identifier's window. */\n const counts = new Map<string, number>();\n\n try {\n for (const identifier of identifiers) {\n if (isLocked(await cache.get(lockKey(identifier.key)))) {\n return tooManyRequests();\n }\n }\n\n for (const identifier of identifiers) {\n const key = counterKey(identifier.key);\n\n // Open the window on the first attempt: the create-only write means\n // only one of several racing servers sets the TTL, and an existing\n // window keeps its deadline (fixed window). The bump itself is an\n // atomic increment, so concurrent attempts across servers are never\n // lost (redis INCRBY / pg upsert keep the window's TTL). Passing the\n // TTL on the bump also expires a key recreated after the seed.\n await cache.set(key, 0, { ttl: window, onConflict: \"create\" });\n const count = await cache.increment(key, 1, { ttl: window });\n\n if (typeof count !== \"number\" || !Number.isFinite(count)) continue;\n\n counts.set(identifier.key, count);\n\n if (count > identifier.max) {\n if (count === identifier.max + 1) {\n await lock(identifier.key, count);\n }\n\n return tooManyRequests();\n }\n }\n } catch (error) {\n // Fail open — a cache outage (driver not initialised, network blip)\n // must never escalate into a full auth outage. Log and let the request\n // through; the onSent recorder below is independently guarded so an\n // outage there is also harmless.\n log.error(\"auth\", \"login-throttle\", error);\n\n return;\n }\n\n response.onSent(async (resolvedResponse: Response) => {\n try {\n const failed = options.isFailure\n ? options.isFailure(resolvedResponse)\n : !resolvedResponse.isOk;\n\n if (!failed) {\n for (const identifier of identifiers) {\n // The source bucket just expires on its window.\n if (identifier.resetOnSuccess === false) continue;\n\n // Reset to 0 rather than delete: a failure still in flight reads\n // the 0 as proof that a success reset the window (see below).\n await cache.set(counterKey(identifier.key), 0, { ttl: window });\n await cache.remove(lockKey(identifier.key));\n }\n\n return;\n }\n\n // Already counted at entry; a failure that used the last allowed\n // attempt starts the lockout, unless a success that finished while it\n // ran reset the counter (a correct login racing a mistyped one must\n // not lock the account it just signed in to).\n for (const identifier of identifiers) {\n const count = counts.get(identifier.key);\n\n if (count === undefined || count < identifier.max) continue;\n\n if (await counterWasReset(identifier.key, count)) continue;\n\n await lock(identifier.key, count);\n }\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AAsHA,MAAM,iBAAiB;AACvB,MAAM,cAAc;AAEpB,MAAM,cAAc,eAA+B,GAAG,iBAAiB;AACvE,MAAM,WAAW,eAA+B,GAAG,cAAc;;;;;;AAOjE,SAAS,kBAAsC;CAC7C,IAAI;CAEJ,IAAI;EACF,SAAS,WAAW,YAAY,OAAO;CACzC,QAAQ;EACN;CACF;CAEA,OAAO,WAAW,UAAU,MAAM,CAAC,CAAC,OAAO,2BAA2B,CAAC,CAAC,OAAO;AACjF;;;;;;;;;;;;;;;AAgBA,SAAgB,uBAAuB,MAAc,OAAuB;CAC1E,MAAM,aAAa,GAAG,K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IAEhC,IAAI,QAAQ,WAAW,KAAK;KAC1B,IAAI,UAAU,WAAW,MAAM,GAC7B,MAAM,KAAK,WAAW,KAAK,KAAK;KAGlC,OAAO,gBAAgB;IACzB;GACF;EACF,SAAS,OAAO;GAKd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAEzC;EACF;EAEA,SAAS,OAAO,OAAO,qBAA+B;GACpD,IAAI;IAKF,IAAI,EAJW,QAAQ,YACnB,QAAQ,UAAU,gBAAgB,IAClC,CAAC,iBAAiB,OAET;KACX,KAAK,MAAM,cAAc,aAAa;MAEpC,IAAI,WAAW,mBAAmB,OAAO;MAIzC,MAAM,MAAM,IAAI,WAAW,WAAW,GAAG,GAAG,GAAG,EAAE,KAAK,OAAO,CAAC;MAC9D,MAAM,MAAM,OAAO,QAAQ,WAAW,GAAG,CAAC;KAC5C;KAEA;IACF;IAMA,KAAK,MAAM,cAAc,aAAa;KACpC,MAAM,QAAQ,OAAO,IAAI,WAAW,GAAG;KAEvC,IAAI,UAAU,UAAa,QAAQ,WAAW,KAAK;KAEnD,IAAI,MAAM,gBAAgB,WAAW,KAAK,KAAK,GAAG;KAElD,MAAM,KAAK,WAAW,KAAK,KAAK;IAClC;GACF,SAAS,OAAO;IACd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAC3C;EACF,CAAC;CACH;AACF"}
@@ -34,6 +34,20 @@ export declare class AuthTokenFamily extends Model {
34
34
  static findByFamilyId(familyId: string): Promise<AuthTokenFamily | null>;
35
35
  /** Add a durable row for an existing lineage through a driver-native upsert. */
36
36
  static ensure(user: Auth, familyId: string): Promise<AuthTokenFamily>;
37
+ /**
38
+ * Make sure a durable row exists for every given lineage: one read finds the
39
+ * existing rows, and the missing ones are inserted together. A concurrent
40
+ * insert of the same lineage (a duplicate-key failure) falls back to
41
+ * {@link ensure} per missing lineage, which tolerates the race.
42
+ */
43
+ static ensureMany(user: Auth, familyIds: string[]): Promise<void>;
44
+ /**
45
+ * Revoke every active family of a user in one update: the revision advances
46
+ * and the revoke marker is stamped together, so a rotation holding an older
47
+ * revision fails its compare-and-set and finds the family unavailable.
48
+ * Resolves to the number of families revoked.
49
+ */
50
+ static revokeAllFor(user: Auth): Promise<number>;
37
51
  /** Every non-revoked family for a user, including a rotated refresh row. */
38
52
  static activeFor(user: Auth): Promise<AuthTokenFamily[]>;
39
53
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"auth-token-family.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/auth-token-family.model.ts"],"mappings":";;;;qBAKa,kDAAqB;;;;;;;;;;;;qBASrB,wBAAwB;SACrB;SAEA,mCAAM;;;;;;;;;;;;MAGT;;SAKG,MAAM,MAAM,MAAM,mBAAgB,QAAA;SASlC,eAAe,mBAAmB,QAAQ;;SAKpC,OAAO,MAAM,MAAM,mBAAmB,QAAQ;;SAgCpD,UAAU,MAAM,OAAO,QAAQ;;;;;SAU/B,gBAAgB,kBAAkB,2BAA2B;;SAQ7D,OAAO,kBAAkB,2BAA2B"}
1
+ {"version":3,"file":"auth-token-family.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/auth-token-family.model.ts"],"mappings":";;;;qBAKa,kDAAqB;;;;;;;;;;;;qBASrB,wBAAwB;SACrB;SAEA,mCAAM;;;;;;;;;;;;MAGT;;SAKG,MAAM,MAAM,MAAM,mBAAgB,QAAA;SASlC,eAAe,mBAAmB,QAAQ;;SAKpC,OAAO,MAAM,MAAM,mBAAmB,QAAQ;;;;;;;SAqC9C,WAAW,MAAM,MAAM,sBAAsB;;;;;;;SAsCnD,aAAa,MAAM,OAAO;;SAQ1B,UAAU,MAAM,OAAO,QAAQ;;;;;SAU/B,gBAAgB,kBAAkB,2BAA2B;;SAQ7D,OAAO,kBAAkB,2BAA2B"}
@@ -51,6 +51,49 @@ var AuthTokenFamily = class extends Model {
51
51
  if (family.get("user_id") !== user.id || family.get("user_type") !== user.userType) throw new Error("Token family belongs to a different user");
52
52
  return family;
53
53
  }
54
+ /**
55
+ * Make sure a durable row exists for every given lineage: one read finds the
56
+ * existing rows, and the missing ones are inserted together. A concurrent
57
+ * insert of the same lineage (a duplicate-key failure) falls back to
58
+ * {@link ensure} per missing lineage, which tolerates the race.
59
+ */
60
+ static async ensureMany(user, familyIds) {
61
+ if (familyIds.length === 0) return;
62
+ const existing = await this.query().whereIn("family_id", familyIds).get();
63
+ const known = /* @__PURE__ */ new Set();
64
+ for (const family of existing) {
65
+ if (family.get("user_id") !== user.id || family.get("user_type") !== user.userType) throw new Error("Token family belongs to a different user");
66
+ known.add(family.get("family_id"));
67
+ }
68
+ const missing = familyIds.filter((familyId) => !known.has(familyId));
69
+ if (missing.length === 0) return;
70
+ try {
71
+ await this.createMany(missing.map((familyId) => ({
72
+ family_id: familyId,
73
+ user_id: user.id,
74
+ user_type: user.userType,
75
+ revision: 0
76
+ })));
77
+ } catch {
78
+ for (const familyId of missing) await this.ensure(user, familyId);
79
+ }
80
+ }
81
+ /**
82
+ * Revoke every active family of a user in one update: the revision advances
83
+ * and the revoke marker is stamped together, so a rotation holding an older
84
+ * revision fails its compare-and-set and finds the family unavailable.
85
+ * Resolves to the number of families revoked.
86
+ */
87
+ static revokeAllFor(user) {
88
+ return this.atomic({
89
+ user_id: user.id,
90
+ user_type: user.userType,
91
+ revoked_at: null
92
+ }, {
93
+ $inc: { revision: 1 },
94
+ $set: { revoked_at: /* @__PURE__ */ new Date() }
95
+ });
96
+ }
54
97
  /** Every non-revoked family for a user, including a rotated refresh row. */
55
98
  static activeFor(user) {
56
99
  return this.query().where({
@@ -1 +1 @@
1
- {"version":3,"file":"auth-token-family.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/auth-token-family.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { Auth } from \"../auth.model\";\n\n/** Durable revision authority for one refresh-token rotation family. */\nexport const authTokenFamilySchema = v.object({\n family_id: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n revision: v.number().default(0),\n revoked_at: v.date().optional(),\n});\n\n/** Coordinates family-wide refresh, replay containment, and logout transitions. */\nexport class AuthTokenFamily extends Model {\n public static table = \"auth_token_families\";\n\n public static schema = authTokenFamilySchema;\n\n /** Whether a family-wide revoke has made every member unusable. */\n public get isRevoked(): boolean {\n return Boolean(this.get(\"revoked_at\"));\n }\n\n /** Create the durable family record before its first token pair is issued. */\n public static issue(user: Auth, familyId: string) {\n return this.create({\n family_id: familyId,\n user_id: user.id,\n user_type: user.userType,\n revision: 0,\n });\n }\n\n public static findByFamilyId(familyId: string): Promise<AuthTokenFamily | null> {\n return this.first({ family_id: familyId });\n }\n\n /** Add a durable row for an existing lineage through a driver-native upsert. */\n public static async ensure(user: Auth, familyId: string): Promise<AuthTokenFamily> {\n const existing = await this.findByFamilyId(familyId);\n\n if (existing) {\n if (\n existing.get(\"user_id\") !== user.id ||\n existing.get<string>(\"user_type\") !== user.userType\n ) {\n throw new Error(\"Token family belongs to a different user\");\n }\n\n return existing;\n }\n\n await this.atomic(\n { family_id: familyId },\n { $setOnInsert: { user_id: user.id, user_type: user.userType, revision: 0 } },\n { upsert: true },\n );\n\n const family = await this.findByFamilyId(familyId);\n\n if (!family) throw new Error(\"Token family upsert did not return a family\");\n\n if (family.get(\"user_id\") !== user.id || family.get<string>(\"user_type\") !== user.userType) {\n throw new Error(\"Token family belongs to a different user\");\n }\n\n return family;\n }\n\n /** Every non-revoked family for a user, including a rotated refresh row. */\n public static activeFor(user: Auth): Promise<AuthTokenFamily[]> {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n }\n\n /**\n * Compare-and-set the family revision. A zero result is a concurrent family\n * transition, never a successful no-op.\n */\n public static advanceRevision(familyId: string, expectedRevision: number): Promise<number> {\n return this.atomic(\n { family_id: familyId, revision: expectedRevision, revoked_at: null },\n { $inc: { revision: 1 } },\n );\n }\n\n /** Stamp the durable family revoke marker after a successful CAS. */\n public static revoke(familyId: string, expectedRevision: number): Promise<number> {\n return this.atomic(\n { family_id: familyId, revision: expectedRevision + 1, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n }\n}\n"],"mappings":";;;;;AAKA,MAAa,wBAAwB,EAAE,OAAO;CAC5C,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,UAAU,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC;CAC9B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;AAChC,CAAC;;AAGD,IAAa,kBAAb,cAAqC,MAAM;;eACnB;;;gBAEC;;;CAGvB,IAAW,YAAqB;EAC9B,OAAO,QAAQ,KAAK,IAAI,YAAY,CAAC;CACvC;;CAGA,OAAc,MAAM,MAAY,UAAkB;EAChD,OAAO,KAAK,OAAO;GACjB,WAAW;GACX,SAAS,KAAK;GACd,WAAW,KAAK;GAChB,UAAU;EACZ,CAAC;CACH;CAEA,OAAc,eAAe,UAAmD;EAC9E,OAAO,KAAK,MAAM,EAAE,WAAW,SAAS,CAAC;CAC3C;;CAGA,aAAoB,OAAO,MAAY,UAA4C;EACjF,MAAM,WAAW,MAAM,KAAK,eAAe,QAAQ;EAEnD,IAAI,UAAU;GACZ,IACE,SAAS,IAAI,SAAS,MAAM,KAAK,MACjC,SAAS,IAAY,WAAW,MAAM,KAAK,UAE3C,MAAM,IAAI,MAAM,0CAA0C;GAG5D,OAAO;EACT;EAEA,MAAM,KAAK,OACT,EAAE,WAAW,SAAS,GACtB,EAAE,cAAc;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,UAAU;EAAE,EAAE,GAC5E,EAAE,QAAQ,KAAK,CACjB;EAEA,MAAM,SAAS,MAAM,KAAK,eAAe,QAAQ;EAEjD,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,6CAA6C;EAE1E,IAAI,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,OAAO,IAAY,WAAW,MAAM,KAAK,UAChF,MAAM,IAAI,MAAM,0CAA0C;EAG5D,OAAO;CACT;;CAGA,OAAc,UAAU,MAAwC;EAC9D,OAAO,KAAK,MAAM,CAAC,CAChB,MAAM;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,YAAY;EAAK,CAAC,CAAC,CACvE,IAAI;CACT;;;;;CAMA,OAAc,gBAAgB,UAAkB,kBAA2C;EACzF,OAAO,KAAK,OACV;GAAE,WAAW;GAAU,UAAU;GAAkB,YAAY;EAAK,GACpE,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,CAC1B;CACF;;CAGA,OAAc,OAAO,UAAkB,kBAA2C;EAChF,OAAO,KAAK,OACV;GAAE,WAAW;GAAU,UAAU,mBAAmB;GAAG,YAAY;EAAK,GACxE,EAAE,MAAM,EAAE,4BAAY,IAAI,KAAK,EAAE,EAAE,CACrC;CACF;AACF"}
1
+ {"version":3,"file":"auth-token-family.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/auth-token-family.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { Auth } from \"../auth.model\";\n\n/** Durable revision authority for one refresh-token rotation family. */\nexport const authTokenFamilySchema = v.object({\n family_id: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n revision: v.number().default(0),\n revoked_at: v.date().optional(),\n});\n\n/** Coordinates family-wide refresh, replay containment, and logout transitions. */\nexport class AuthTokenFamily extends Model {\n public static table = \"auth_token_families\";\n\n public static schema = authTokenFamilySchema;\n\n /** Whether a family-wide revoke has made every member unusable. */\n public get isRevoked(): boolean {\n return Boolean(this.get(\"revoked_at\"));\n }\n\n /** Create the durable family record before its first token pair is issued. */\n public static issue(user: Auth, familyId: string) {\n return this.create({\n family_id: familyId,\n user_id: user.id,\n user_type: user.userType,\n revision: 0,\n });\n }\n\n public static findByFamilyId(familyId: string): Promise<AuthTokenFamily | null> {\n return this.first({ family_id: familyId });\n }\n\n /** Add a durable row for an existing lineage through a driver-native upsert. */\n public static async ensure(user: Auth, familyId: string): Promise<AuthTokenFamily> {\n const existing = await this.findByFamilyId(familyId);\n\n if (existing) {\n if (\n existing.get(\"user_id\") !== user.id ||\n existing.get<string>(\"user_type\") !== user.userType\n ) {\n throw new Error(\"Token family belongs to a different user\");\n }\n\n return existing;\n }\n\n await this.atomic(\n { family_id: familyId },\n { $setOnInsert: { user_id: user.id, user_type: user.userType, revision: 0 } },\n { upsert: true },\n );\n\n const family = await this.findByFamilyId(familyId);\n\n if (!family) throw new Error(\"Token family upsert did not return a family\");\n\n if (family.get(\"user_id\") !== user.id || family.get<string>(\"user_type\") !== user.userType) {\n throw new Error(\"Token family belongs to a different user\");\n }\n\n return family;\n }\n\n /**\n * Make sure a durable row exists for every given lineage: one read finds the\n * existing rows, and the missing ones are inserted together. A concurrent\n * insert of the same lineage (a duplicate-key failure) falls back to\n * {@link ensure} per missing lineage, which tolerates the race.\n */\n public static async ensureMany(user: Auth, familyIds: string[]): Promise<void> {\n if (familyIds.length === 0) return;\n\n const existing = await this.query().whereIn(\"family_id\", familyIds).get();\n const known = new Set<string>();\n\n for (const family of existing) {\n if (family.get(\"user_id\") !== user.id || family.get<string>(\"user_type\") !== user.userType) {\n throw new Error(\"Token family belongs to a different user\");\n }\n\n known.add(family.get<string>(\"family_id\"));\n }\n\n const missing = familyIds.filter((familyId) => !known.has(familyId));\n\n if (missing.length === 0) return;\n\n try {\n await this.createMany(\n missing.map((familyId) => ({\n family_id: familyId,\n user_id: user.id,\n user_type: user.userType,\n revision: 0,\n })),\n );\n } catch {\n for (const familyId of missing) await this.ensure(user, familyId);\n }\n }\n\n /**\n * Revoke every active family of a user in one update: the revision advances\n * and the revoke marker is stamped together, so a rotation holding an older\n * revision fails its compare-and-set and finds the family unavailable.\n * Resolves to the number of families revoked.\n */\n public static revokeAllFor(user: Auth): Promise<number> {\n return this.atomic(\n { user_id: user.id, user_type: user.userType, revoked_at: null },\n { $inc: { revision: 1 }, $set: { revoked_at: new Date() } },\n );\n }\n\n /** Every non-revoked family for a user, including a rotated refresh row. */\n public static activeFor(user: Auth): Promise<AuthTokenFamily[]> {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n }\n\n /**\n * Compare-and-set the family revision. A zero result is a concurrent family\n * transition, never a successful no-op.\n */\n public static advanceRevision(familyId: string, expectedRevision: number): Promise<number> {\n return this.atomic(\n { family_id: familyId, revision: expectedRevision, revoked_at: null },\n { $inc: { revision: 1 } },\n );\n }\n\n /** Stamp the durable family revoke marker after a successful CAS. */\n public static revoke(familyId: string, expectedRevision: number): Promise<number> {\n return this.atomic(\n { family_id: familyId, revision: expectedRevision + 1, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n }\n}\n"],"mappings":";;;;;AAKA,MAAa,wBAAwB,EAAE,OAAO;CAC5C,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,UAAU,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC;CAC9B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;AAChC,CAAC;;AAGD,IAAa,kBAAb,cAAqC,MAAM;;eACnB;;;gBAEC;;;CAGvB,IAAW,YAAqB;EAC9B,OAAO,QAAQ,KAAK,IAAI,YAAY,CAAC;CACvC;;CAGA,OAAc,MAAM,MAAY,UAAkB;EAChD,OAAO,KAAK,OAAO;GACjB,WAAW;GACX,SAAS,KAAK;GACd,WAAW,KAAK;GAChB,UAAU;EACZ,CAAC;CACH;CAEA,OAAc,eAAe,UAAmD;EAC9E,OAAO,KAAK,MAAM,EAAE,WAAW,SAAS,CAAC;CAC3C;;CAGA,aAAoB,OAAO,MAAY,UAA4C;EACjF,MAAM,WAAW,MAA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;EAClE;CACF;;;;;;;CAQA,OAAc,aAAa,MAA6B;EACtD,OAAO,KAAK,OACV;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,YAAY;EAAK,GAC/D;GAAE,MAAM,EAAE,UAAU,EAAE;GAAG,MAAM,EAAE,4BAAY,IAAI,KAAK,EAAE;EAAE,CAC5D;CACF;;CAGA,OAAc,UAAU,MAAwC;EAC9D,OAAO,KAAK,MAAM,CAAC,CAChB,MAAM;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,YAAY;EAAK,CAAC,CAAC,CACvE,IAAI;CACT;;;;;CAMA,OAAc,gBAAgB,UAAkB,kBAA2C;EACzF,OAAO,KAAK,OACV;GAAE,WAAW;GAAU,UAAU;GAAkB,YAAY;EAAK,GACpE,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,CAC1B;CACF;;CAGA,OAAc,OAAO,UAAkB,kBAA2C;EAChF,OAAO,KAAK,OACV;GAAE,WAAW;GAAU,UAAU,mBAAmB;GAAG,YAAY;EAAK,GACxE,EAAE,MAAM,EAAE,4BAAY,IAAI,KAAK,EAAE,EAAE,CACrC;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"refresh-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/refresh-token.model.ts"],"mappings":";;;;;;;;;;;;;;;;qBAmBa,+CAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAiBnB;EACV;EACA;EACA,aAAa;;;;;;;;;;;;qBAaF,qBAAqB;SAClB;SAEA,mCAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAYN;;;;;;;SAQA;;MAGH;;;;;;MASA;;;;;;;;;;;MAcA;;;;;MAYA;;MAKA;;MAKA;;;;EAOE,UAAU;;;;;;;;EAWV,kBAAkB;;;;EAclB,cAAc;;;;;SAQb,MAAM,MAAM,MAAM,eAAe,SAAS,2BAAwB,QAAA;;;;;SAqBlE,YAAY,gBAAgB,QAA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BrC,gBAAgB,QAAQ;;;;;;;SAgBxB,qBAAqB,QAAQ;;;;;;;;;;SAe7B,sBAAsB,QAAQ"}
@@ -198,7 +198,12 @@ var RefreshToken = class extends Model {
198
198
  user_type: user.userType,
199
199
  revoked_at: null
200
200
  }).get();
201
- for (const token of tokens) await token.revoke();
201
+ if (tokens.length === 0) return tokens;
202
+ await this.atomic({
203
+ user_id: user.id,
204
+ user_type: user.userType,
205
+ revoked_at: null
206
+ }, { $set: { revoked_at: /* @__PURE__ */ new Date() } });
202
207
  return tokens;
203
208
  }
204
209
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"refresh-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { DeviceInfo } from \"../../contracts/types\";\nimport { plainTokenOf, storedTokenForms } from \"../../utils/token-digest\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted refresh-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape:\n *\n * @example\n * export class AppRefreshToken extends RefreshToken {\n * public static schema = refreshTokenSchema.extend({\n * organization_id: v.string().required(),\n * });\n * }\n */\nexport const refreshTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n family_id: v.string().required(),\n expires_at: v.date().required(),\n last_used_at: v.date().default(() => new Date()),\n revoked_at: v.date().optional(),\n /** The successor pair a bounded concurrent renewal may reuse. */\n successor_access_token_id: v.string().optional(),\n successor_refresh_token_id: v.string().optional(),\n device_info: v.record(v.any()).optional(),\n});\n\n/**\n * Extra attributes captured when a refresh token is issued.\n */\nexport type RefreshTokenIssueOptions = {\n familyId: string;\n expiresAt: string;\n deviceInfo?: DeviceInfo;\n};\n\n/**\n * Persisted refresh-token record + the data layer for refresh tokens.\n *\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\n * The auth service drives refresh-token state exclusively through this model's\n * named statics and instance methods, so it never hard-codes a column name —\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\n * structurally impossible and lets an override rename or add columns by\n * extending this class and registering it under `config.auth.refreshToken.model`.\n */\nexport class RefreshToken extends Model {\n public static table = \"refresh_tokens\";\n\n public static schema = refreshTokenSchema;\n\n /**\n * The raw signed refresh JWT is a bearer credential — never serialize it.\n * `hidden` only strips it from `toJSON()` / `JSON.stringify(model)` (e.g. a\n * session list returned via `response.json`); `get(\"token\")`,\n * `findByToken` / `findForUser` and every query still read the column.\n *\n * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256\n * digest instead; read the raw token of a freshly issued row through\n * {@link plainToken}.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `refresh_tokensTrash` on every `destroy()` (expiry purge,\n * never-expiring purge). A purged refresh token must not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** Token family this row belongs to (rotation / replay grouping). */\n public get familyId(): string {\n return this.get(\"family_id\");\n }\n\n /**\n * The raw refresh token, when it is known: always for a row stored\n * unhashed, and for a hashed row only in the process that just issued it\n * (e.g. the row `authService.createRefreshToken` returns).\n */\n public get plainToken(): string | undefined {\n return plainTokenOf(this, this.get(\"token\"));\n }\n\n /**\n * Whether the token's `expires_at` is in the past.\n *\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\n * counts as expired. It previously answered `false` for both — \"no expiry\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\n * that cannot say when it dies is malformed, not immortal.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date().getTime() > new Date(expiresAt).getTime();\n }\n\n /**\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /** Whether the token has been revoked. */\n public get isRevoked(): boolean {\n return !!this.get(\"revoked_at\");\n }\n\n /** Whether the token is still usable (not expired and not revoked). */\n public get isValid(): boolean {\n return !this.isExpired && !this.isRevoked;\n }\n\n /**\n * Unconditionally stamp `revoked_at` on this token.\n */\n public async revoke(): Promise<this> {\n return this.merge({ revoked_at: new Date() }).save();\n }\n\n /**\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\n * when this call performed the revoke, `false` when a concurrent request had\n * already revoked it — the win/lose signal that powers rotation replay\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\n * same token can never both succeed.\n */\n public async revokeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof RefreshToken;\n\n const revokedCount = await modelClass.atomic(\n { id: this.id, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return revokedCount > 0;\n }\n\n /**\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\n */\n public async markAsUsed(): Promise<void> {\n await this.merge({ last_used_at: new Date() }).save();\n }\n\n /**\n * Persist a freshly-signed refresh token for the user. `token` is the value\n * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.\n */\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: options.familyId,\n expires_at: options.expiresAt,\n device_info: options.deviceInfo\n ? {\n userAgent: options.deviceInfo.userAgent,\n ip: options.deviceInfo.ip,\n deviceId: options.deviceInfo.deviceId,\n }\n : undefined,\n });\n }\n\n /**\n * Find a refresh-token row by its raw token string, whether the row stores\n * the token hashed or raw (one query).\n */\n public static findByToken(token: string): Promise<RefreshToken | null> {\n return this.query().whereIn(\"token\", storedTokenForms(token)).first();\n }\n\n /**\n * Find a refresh token scoped to a user — used by logout so a caller can only\n * revoke a token that actually belongs to them.\n */\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .first();\n }\n\n /** Find any member of a family, including an already-revoked legacy member. */\n public static findInFamily(familyId: string): Promise<RefreshToken | null> {\n return this.first({ family_id: familyId });\n }\n\n /**\n * Every refresh lineage for a user, including rotated rows. Logout uses this\n * to bootstrap durable family records before it starts family revocations.\n */\n public static familiesForUser(user: Auth): Promise<RefreshToken[]> {\n return this.query().where({ user_id: user.id, user_type: user.userType }).get();\n }\n\n /**\n * Delete a specific refresh token belonging to the user, stored hashed or raw.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .delete();\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\n return this.activeQuery(user).orderBy(\"created_at\", \"desc\").get();\n }\n\n private static activeQuery(user: Auth) {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .where(\"expires_at\", \">\", new Date());\n }\n\n /**\n * Revoke every still-active refresh token for the user, returning the rows\n * that were revoked so the caller can emit a per-token event for each.\n *\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\n * `revoked_at: null` would re-query the same predicate after the update and\n * match nothing, returning an empty set.\n */\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\n const tokens = await this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke every still-active token in a family (rotation breach containment),\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\n */\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\n * small.\n */\n public static async enforceMax(user: Auth, max: number): Promise<void> {\n const activeTokens = await this.activeQuery(user).orderBy(\"created_at\", \"asc\").get();\n\n if (activeTokens.length < max) return;\n\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\n\n for (const token of tokensToRevoke) {\n await token.revoke();\n }\n }\n\n /**\n * Hard-delete every expired refresh token, returning the deleted rows so the\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\n * (a cold batch path).\n */\n public static async purgeExpired(): Promise<RefreshToken[]> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}. A full\n * scan filtered in memory, for the reason given on\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\n * missing `exp` claim is expressible as a `where`.\n */\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: RefreshToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed.\n *\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\n * table has to carry, and one of the two shapes being removed is a row whose\n * date column cannot be compared at all — leaving it in place keeps a\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\n * these rows can no longer be presented successfully either way.\n */\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,W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BAA6C;EAG/D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAwB,MAAM,YAAY;CAClE;;;;;;;;;;CAWA,aAAoB,qBAA8C;EAChE,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"refresh-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { DeviceInfo } from \"../../contracts/types\";\nimport { plainTokenOf, storedTokenForms } from \"../../utils/token-digest\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted refresh-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape:\n *\n * @example\n * export class AppRefreshToken extends RefreshToken {\n * public static schema = refreshTokenSchema.extend({\n * organization_id: v.string().required(),\n * });\n * }\n */\nexport const refreshTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n family_id: v.string().required(),\n expires_at: v.date().required(),\n last_used_at: v.date().default(() => new Date()),\n revoked_at: v.date().optional(),\n /** The successor pair a bounded concurrent renewal may reuse. */\n successor_access_token_id: v.string().optional(),\n successor_refresh_token_id: v.string().optional(),\n device_info: v.record(v.any()).optional(),\n});\n\n/**\n * Extra attributes captured when a refresh token is issued.\n */\nexport type RefreshTokenIssueOptions = {\n familyId: string;\n expiresAt: string;\n deviceInfo?: DeviceInfo;\n};\n\n/**\n * Persisted refresh-token record + the data layer for refresh tokens.\n *\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\n * The auth service drives refresh-token state exclusively through this model's\n * named statics and instance methods, so it never hard-codes a column name —\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\n * structurally impossible and lets an override rename or add columns by\n * extending this class and registering it under `config.auth.refreshToken.model`.\n */\nexport class RefreshToken extends Model {\n public static table = \"refresh_tokens\";\n\n public static schema = refreshTokenSchema;\n\n /**\n * The raw signed refresh JWT is a bearer credential — never serialize it.\n * `hidden` only strips it from `toJSON()` / `JSON.stringify(model)` (e.g. a\n * session list returned via `response.json`); `get(\"token\")`,\n * `findByToken` / `findForUser` and every query still read the column.\n *\n * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256\n * digest instead; read the raw token of a freshly issued row through\n * {@link plainToken}.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `refresh_tokensTrash` on every `destroy()` (expiry purge,\n * never-expiring purge). A purged refresh token must not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** Token family this row belongs to (rotation / replay grouping). */\n public get familyId(): string {\n return this.get(\"family_id\");\n }\n\n /**\n * The raw refresh token, when it is known: always for a row stored\n * unhashed, and for a hashed row only in the process that just issued it\n * (e.g. the row `authService.createRefreshToken` returns).\n */\n public get plainToken(): string | undefined {\n return plainTokenOf(this, this.get(\"token\"));\n }\n\n /**\n * Whether the token's `expires_at` is in the past.\n *\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\n * counts as expired. It previously answered `false` for both — \"no expiry\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\n * that cannot say when it dies is malformed, not immortal.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date().getTime() > new Date(expiresAt).getTime();\n }\n\n /**\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /** Whether the token has been revoked. */\n public get isRevoked(): boolean {\n return !!this.get(\"revoked_at\");\n }\n\n /** Whether the token is still usable (not expired and not revoked). */\n public get isValid(): boolean {\n return !this.isExpired && !this.isRevoked;\n }\n\n /**\n * Unconditionally stamp `revoked_at` on this token.\n */\n public async revoke(): Promise<this> {\n return this.merge({ revoked_at: new Date() }).save();\n }\n\n /**\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\n * when this call performed the revoke, `false` when a concurrent request had\n * already revoked it — the win/lose signal that powers rotation replay\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\n * same token can never both succeed.\n */\n public async revokeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof RefreshToken;\n\n const revokedCount = await modelClass.atomic(\n { id: this.id, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return revokedCount > 0;\n }\n\n /**\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\n */\n public async markAsUsed(): Promise<void> {\n await this.merge({ last_used_at: new Date() }).save();\n }\n\n /**\n * Persist a freshly-signed refresh token for the user. `token` is the value\n * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.\n */\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: options.familyId,\n expires_at: options.expiresAt,\n device_info: options.deviceInfo\n ? {\n userAgent: options.deviceInfo.userAgent,\n ip: options.deviceInfo.ip,\n deviceId: options.deviceInfo.deviceId,\n }\n : undefined,\n });\n }\n\n /**\n * Find a refresh-token row by its raw token string, whether the row stores\n * the token hashed or raw (one query).\n */\n public static findByToken(token: string): Promise<RefreshToken | null> {\n return this.query().whereIn(\"token\", storedTokenForms(token)).first();\n }\n\n /**\n * Find a refresh token scoped to a user — used by logout so a caller can only\n * revoke a token that actually belongs to them.\n */\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .first();\n }\n\n /** Find any member of a family, including an already-revoked legacy member. */\n public static findInFamily(familyId: string): Promise<RefreshToken | null> {\n return this.first({ family_id: familyId });\n }\n\n /**\n * Every refresh lineage for a user, including rotated rows. Logout uses this\n * to bootstrap durable family records before it starts family revocations.\n */\n public static familiesForUser(user: Auth): Promise<RefreshToken[]> {\n return this.query().where({ user_id: user.id, user_type: user.userType }).get();\n }\n\n /**\n * Delete a specific refresh token belonging to the user, stored hashed or raw.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .delete();\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\n return this.activeQuery(user).orderBy(\"created_at\", \"desc\").get();\n }\n\n private static activeQuery(user: Auth) {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .where(\"expires_at\", \">\", new Date());\n }\n\n /**\n * Revoke every still-active refresh token for the user, returning the rows\n * that were revoked so the caller can emit a per-token event for each.\n *\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\n * `revoked_at: null` would re-query the same predicate after the update and\n * match nothing, returning an empty set.\n */\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\n const tokens = await this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n\n if (tokens.length === 0) return tokens;\n\n // One conditional update for the whole user; rows a concurrent request\n // revoked in between keep their earlier stamp.\n await this.atomic(\n { user_id: user.id, user_type: user.userType, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return tokens;\n }\n\n /**\n * Revoke every still-active token in a family (rotation breach containment),\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\n */\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\n * small.\n */\n public static async enforceMax(user: Auth, max: number): Promise<void> {\n const activeTokens = await this.activeQuery(user).orderBy(\"created_at\", \"asc\").get();\n\n if (activeTokens.length < max) return;\n\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\n\n for (const token of tokensToRevoke) {\n await token.revoke();\n }\n }\n\n /**\n * Hard-delete every expired refresh token, returning the deleted rows so the\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\n * (a cold batch path).\n */\n public static async purgeExpired(): Promise<RefreshToken[]> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}. A full\n * scan filtered in memory, for the reason given on\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\n * missing `exp` claim is expressible as a `where`.\n */\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: RefreshToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed.\n *\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\n * table has to carry, and one of the two shapes being removed is a row whose\n * date column cannot be compared at all — leaving it in place keeps a\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\n * these rows can no longer be presented successfully either way.\n */\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,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