@warlock.js/auth 5.52.0 → 5.53.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 (164) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/esm/commands/auth-cleanup-command.mjs.map +1 -1
  3. package/esm/commands/auth-purge-never-expiring-command.mjs.map +1 -1
  4. package/esm/commands/jwt-secret-generator-command.mjs.map +1 -1
  5. package/esm/contracts/index.d.mts +2 -2
  6. package/esm/contracts/providers.d.mts +53 -0
  7. package/esm/contracts/providers.d.mts.map +1 -1
  8. package/esm/contracts/types.d.mts +53 -0
  9. package/esm/contracts/types.d.mts.map +1 -1
  10. package/esm/contracts/types.mjs.map +1 -1
  11. package/esm/errors/auth-provider-sdk-missing.error.mjs.map +1 -1
  12. package/esm/errors/email-not-verified.error.mjs.map +1 -1
  13. package/esm/errors/index.d.mts +2 -1
  14. package/esm/errors/index.mjs +2 -1
  15. package/esm/errors/invalid-one-time-token.error.mjs.map +1 -1
  16. package/esm/errors/invalid-passkey.error.mjs.map +1 -1
  17. package/esm/errors/invalid-provider-callback.error.mjs.map +1 -1
  18. package/esm/errors/notifications-unavailable.error.mjs.map +1 -1
  19. package/esm/errors/provider-account-link-blocked.error.d.mts +16 -0
  20. package/esm/errors/provider-account-link-blocked.error.d.mts.map +1 -0
  21. package/esm/errors/provider-account-link-blocked.error.mjs +22 -0
  22. package/esm/errors/provider-account-link-blocked.error.mjs.map +1 -0
  23. package/esm/errors/provider-email-not-verified.error.mjs.map +1 -1
  24. package/esm/index.d.mts +3 -2
  25. package/esm/index.mjs +2 -1
  26. package/esm/localization/ar.translations.mjs.map +1 -1
  27. package/esm/localization/auth-default-translations.mjs.map +1 -1
  28. package/esm/localization/en.translations.mjs.map +1 -1
  29. package/esm/localization/init.mjs.map +1 -1
  30. package/esm/localization/register-auth-translations.mjs.map +1 -1
  31. package/esm/middleware/auth.middleware.mjs +1 -1
  32. package/esm/middleware/auth.middleware.mjs.map +1 -1
  33. package/esm/middleware/csrf-origin-check.mjs.map +1 -1
  34. package/esm/middleware/localized-login-path.mjs.map +1 -1
  35. package/esm/middleware/login-throttle.middleware.d.mts +38 -8
  36. package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
  37. package/esm/middleware/login-throttle.middleware.mjs +93 -29
  38. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  39. package/esm/middleware/one-time-token-throttle.middleware.mjs.map +1 -1
  40. package/esm/middleware/otp-throttle.middleware.mjs.map +1 -1
  41. package/esm/middleware/require-verified-email.middleware.mjs.map +1 -1
  42. package/esm/models/access-token/access-token.model.d.mts +14 -3
  43. package/esm/models/access-token/access-token.model.d.mts.map +1 -1
  44. package/esm/models/access-token/access-token.model.mjs +15 -8
  45. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  46. package/esm/models/access-token/family-association.migration.mjs.map +1 -1
  47. package/esm/models/access-token/migration.mjs.map +1 -1
  48. package/esm/models/auth-token-family/auth-token-family.model.mjs.map +1 -1
  49. package/esm/models/auth-token-family/migration.mjs.map +1 -1
  50. package/esm/models/auth.model.d.mts +8 -0
  51. package/esm/models/auth.model.d.mts.map +1 -1
  52. package/esm/models/auth.model.mjs +3 -0
  53. package/esm/models/auth.model.mjs.map +1 -1
  54. package/esm/models/index.mjs.map +1 -1
  55. package/esm/models/one-time-token/migration.mjs.map +1 -1
  56. package/esm/models/one-time-token/one-time-token.model.d.mts +7 -2
  57. package/esm/models/one-time-token/one-time-token.model.d.mts.map +1 -1
  58. package/esm/models/one-time-token/one-time-token.model.mjs +8 -7
  59. package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -1
  60. package/esm/models/passkey-credential/migration.mjs.map +1 -1
  61. package/esm/models/passkey-credential/passkey-credential.model.mjs.map +1 -1
  62. package/esm/models/provider-account/migration.mjs.map +1 -1
  63. package/esm/models/provider-account/provider-account.model.mjs.map +1 -1
  64. package/esm/models/refresh-token/migration.mjs.map +1 -1
  65. package/esm/models/refresh-token/refresh-token.model.d.mts +15 -3
  66. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  67. package/esm/models/refresh-token/refresh-token.model.mjs +17 -12
  68. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  69. package/esm/models/refresh-token/successor-association.migration.mjs.map +1 -1
  70. package/esm/otp/otp.d.mts +5 -1
  71. package/esm/otp/otp.d.mts.map +1 -1
  72. package/esm/otp/otp.mjs +18 -3
  73. package/esm/otp/otp.mjs.map +1 -1
  74. package/esm/passkeys/passkey-authentication.mjs +2 -2
  75. package/esm/passkeys/passkey-authentication.mjs.map +1 -1
  76. package/esm/passkeys/passkey-challenges.mjs.map +1 -1
  77. package/esm/passkeys/passkey-registration.d.mts.map +1 -1
  78. package/esm/passkeys/passkey-registration.mjs +2 -2
  79. package/esm/passkeys/passkey-registration.mjs.map +1 -1
  80. package/esm/passkeys/simplewebauthn.mjs.map +1 -1
  81. package/esm/providers/apple-provider.d.mts +2 -0
  82. package/esm/providers/apple-provider.d.mts.map +1 -1
  83. package/esm/providers/apple-provider.mjs +4 -1
  84. package/esm/providers/apple-provider.mjs.map +1 -1
  85. package/esm/providers/discord-provider.d.mts +2 -0
  86. package/esm/providers/discord-provider.d.mts.map +1 -1
  87. package/esm/providers/discord-provider.mjs +7 -1
  88. package/esm/providers/discord-provider.mjs.map +1 -1
  89. package/esm/providers/facebook-provider.d.mts +2 -0
  90. package/esm/providers/facebook-provider.d.mts.map +1 -1
  91. package/esm/providers/facebook-provider.mjs +10 -2
  92. package/esm/providers/facebook-provider.mjs.map +1 -1
  93. package/esm/providers/github-provider.d.mts +2 -0
  94. package/esm/providers/github-provider.d.mts.map +1 -1
  95. package/esm/providers/github-provider.mjs +19 -10
  96. package/esm/providers/github-provider.mjs.map +1 -1
  97. package/esm/providers/google-provider.mjs.map +1 -1
  98. package/esm/providers/linkedin-provider.d.mts +2 -0
  99. package/esm/providers/linkedin-provider.d.mts.map +1 -1
  100. package/esm/providers/linkedin-provider.mjs +4 -1
  101. package/esm/providers/linkedin-provider.mjs.map +1 -1
  102. package/esm/providers/provider-login.mjs.map +1 -1
  103. package/esm/providers/provider-state-cookie.mjs.map +1 -1
  104. package/esm/providers/provider-timeout.mjs +17 -0
  105. package/esm/providers/provider-timeout.mjs.map +1 -0
  106. package/esm/providers/resolve-provider-user.mjs +21 -1
  107. package/esm/providers/resolve-provider-user.mjs.map +1 -1
  108. package/esm/providers/x-provider.d.mts +2 -0
  109. package/esm/providers/x-provider.d.mts.map +1 -1
  110. package/esm/providers/x-provider.mjs +7 -1
  111. package/esm/providers/x-provider.mjs.map +1 -1
  112. package/esm/services/auth-config.mjs +65 -6
  113. package/esm/services/auth-config.mjs.map +1 -1
  114. package/esm/services/auth-cookie-names.mjs +49 -0
  115. package/esm/services/auth-cookie-names.mjs.map +1 -0
  116. package/esm/services/auth-events.d.mts +4 -0
  117. package/esm/services/auth-events.d.mts.map +1 -1
  118. package/esm/services/auth-events.mjs.map +1 -1
  119. package/esm/services/auth.service.d.mts +8 -0
  120. package/esm/services/auth.service.d.mts.map +1 -1
  121. package/esm/services/auth.service.mjs +146 -20
  122. package/esm/services/auth.service.mjs.map +1 -1
  123. package/esm/services/current-user.mjs.map +1 -1
  124. package/esm/services/email-verification.mjs.map +1 -1
  125. package/esm/services/generate-jwt-secret.mjs.map +1 -1
  126. package/esm/services/jwt.d.mts.map +1 -1
  127. package/esm/services/jwt.mjs +92 -10
  128. package/esm/services/jwt.mjs.map +1 -1
  129. package/esm/services/one-time-tokens.mjs.map +1 -1
  130. package/esm/services/optional-peer.mjs.map +1 -1
  131. package/esm/services/password-reset.d.mts +5 -0
  132. package/esm/services/password-reset.d.mts.map +1 -1
  133. package/esm/services/password-reset.mjs +15 -1
  134. package/esm/services/password-reset.mjs.map +1 -1
  135. package/esm/services/resolve-request-user.d.mts.map +1 -1
  136. package/esm/services/resolve-request-user.mjs +17 -3
  137. package/esm/services/resolve-request-user.mjs.map +1 -1
  138. package/esm/services/token-family-operation.mjs.map +1 -1
  139. package/esm/services/token-notifications.mjs.map +1 -1
  140. package/esm/session/page-session.d.mts.map +1 -1
  141. package/esm/session/page-session.mjs +5 -3
  142. package/esm/session/page-session.mjs.map +1 -1
  143. package/esm/utils/auth-error-codes.d.mts +8 -1
  144. package/esm/utils/auth-error-codes.d.mts.map +1 -1
  145. package/esm/utils/auth-error-codes.mjs +7 -0
  146. package/esm/utils/auth-error-codes.mjs.map +1 -1
  147. package/esm/utils/normalize-credentials.mjs.map +1 -1
  148. package/esm/utils/safe-equal.mjs.map +1 -1
  149. package/esm/utils/token-digest.mjs +47 -0
  150. package/esm/utils/token-digest.mjs.map +1 -0
  151. package/esm/utils/token-expiry.d.mts +3 -1
  152. package/esm/utils/token-expiry.d.mts.map +1 -1
  153. package/esm/utils/token-expiry.mjs +7 -2
  154. package/esm/utils/token-expiry.mjs.map +1 -1
  155. package/llms-full.txt +70 -30
  156. package/llms.txt +2 -2
  157. package/package.json +9 -9
  158. package/skills/auth-basics/SKILL.md +9 -0
  159. package/skills/customize-token-storage/SKILL.md +10 -10
  160. package/skills/login-with-providers/SKILL.md +14 -3
  161. package/skills/manage-tokens/SKILL.md +6 -0
  162. package/skills/protect-routes/SKILL.md +5 -0
  163. package/skills/throttle-login-attempts/SKILL.md +23 -17
  164. package/skills/verify-email-and-reset-password/SKILL.md +3 -0
@@ -1 +1 @@
1
- {"version":3,"file":"auth.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/auth.middleware.ts"],"sourcesContent":["import { config, type HttpContext, markAuthGuard, t, type Middleware } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport type {\n AuthCredentialDescriptor,\n AuthMiddlewareOptions,\n TokenFrom,\n} from \"../contracts/types\";\nimport { authConfig } from \"../services/auth-config\";\nimport { readCredential, resolveRequestUserOutcome } from \"../services/resolve-request-user\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport {\n assertCsrfOriginAllowed,\n CsrfOriginMismatchError,\n requiresCsrfOriginCheck,\n} from \"./csrf-origin-check\";\nimport { localizedLoginPath } from \"./localized-login-path\";\n\n/**\n * Well-known symbol under which `authMiddleware()` tags the middleware it\n * returns. Shared via the global symbol registry so other packages can read the\n * descriptor structurally (`Symbol.for(\"warlock.auth\")`) without importing auth.\n */\nexport const AUTH_MIDDLEWARE_DESCRIPTOR = Symbol.for(\"warlock.auth\");\n\n/** A credential source an auth middleware reads: the Authorization header or a named cookie. */\nexport type AuthMiddlewareDescriptorSource = \"header\" | { cookie: string };\n\n/**\n * Frozen, JSON-safe description of how an `authMiddleware()` instance\n * authenticates, stored (non-enumerably) under {@link AUTH_MIDDLEWARE_DESCRIPTOR}.\n */\nexport type AuthMiddlewareDescriptor = {\n /** Resolved credential sources; with dual sources the header comes first. */\n sources: AuthMiddlewareDescriptorSource[];\n required?: boolean;\n /** Resolved allowed user types; an empty array means any authenticated user. */\n userTypes: string[];\n};\n\n/** The 401 body shape every rejection in this middleware carries. */\ntype UnauthorizedPayload = { error: string; errorCode: string };\n\n/**\n * Reject an unauthenticated request, choosing the representation by ROUTE KIND.\n *\n * An API route always gets the JSON 401 it has always gotten. A PAGE route\n * (`request.route.isPage` — the React-SSR pages) instead redirects a logged-out\n * browser to the configured login path with a `returnUrl`, so a human\n * navigating to a guarded page lands on the login screen rather than reading a\n * raw JSON error blob — the defect in finding b9ab9804.\n *\n * The redirect is OPT-IN and backward-compatible: with no `auth.pageAuth.loginPath`\n * configured, even a page route falls back to the JSON 401, so an app that has\n * not asked for page-login UX keeps exactly its current behavior. The API 401\n * contract is never changed for API routes.\n *\n * `returnUrl` carries `request.url` — the relative path + query the browser was\n * on — never the absolute URL: a relative target cannot be turned into an\n * open-redirect off this app's origin.\n */\nfunction rejectUnauthorized(\n { request, response }: HttpContext,\n payload: UnauthorizedPayload,\n redirect?: AuthMiddlewareOptions[\"redirect\"],\n) {\n const loginPath = redirect?.to ?? authConfig.pageAuth.loginPath();\n const returnUrlParam = redirect?.returnUrlParam ?? authConfig.pageAuth.returnUrlParam();\n\n if (loginPath && request.route?.isPage) {\n // Under an active `web.localeRouting` strategy, the login destination\n // itself must carry the request's locale prefix — otherwise an anonymous\n // `/ar/admin` bounces to the DEFAULT locale's `/login` rather than\n // `/ar/login`, even though `returnUrl` below correctly points back at\n // `/ar/admin`. See `./localized-login-path.ts`.\n const destination = localizedLoginPath(loginPath, request.locale);\n const separator = destination.includes(\"?\") ? \"&\" : \"?\";\n const returnUrl = encodeURIComponent(request.url);\n\n return response.redirect(`${destination}${separator}${returnUrlParam}=${returnUrl}`);\n }\n\n return response.unauthorized(payload);\n}\n\nfunction tokenFromDescriptor(descriptor: Partial<AuthCredentialDescriptor>): TokenFrom {\n if (!descriptor.source || descriptor.source === \"header\") return \"header\";\n\n if (!descriptor.key) {\n throw new Error(\"authMiddleware cookie credentials require a cookie key.\");\n }\n\n return `cookie:${descriptor.key}`;\n}\n\nfunction descriptorSource(tokenFrom: TokenFrom): AuthMiddlewareDescriptorSource {\n return tokenFrom === \"header\" ? \"header\" : { cookie: tokenFrom.slice(\"cookie:\".length) };\n}\n\nfunction resolveAllowedTypes(value: string | string[] | undefined): string[] {\n if (value !== undefined) return Array.isArray(value) ? value : [value];\n\n const configuredDefault = config.key(\"auth.defaultUserType\") as string | undefined;\n\n if (configuredDefault) return [configuredDefault];\n\n const userTypes = config.key(\"auth.userType\", {}) as Record<string, unknown>;\n const configuredTypes = Object.keys(userTypes);\n\n if (configuredTypes.length === 1) return configuredTypes;\n\n throw new Error(\n \"authMiddleware requires a user type when auth.defaultUserType is unset and multiple user types exist.\",\n );\n}\n\n/**\n * Build a route gate. Authentication is required unless optional is explicit.\n *\n * An omitted user type selects the configured default; an explicit argument\n * selects which user types may pass:\n * - `[]` — any authenticated user (token required, type not checked).\n * - `\"admin\"` / `[\"admin\", \"staff\"]` — token required AND the user's\n * `userType` must be one of the listed types.\n *\n * `{ optional: true }` allows anonymous requests. All other forms reject\n * missing or invalid credentials with 401, or a configured page redirect.\n *\n * `tokenFrom` selects one credential source and defaults to `\"header\"`.\n * A single source avoids making credential precedence depend on array order.\n *\n * @example\n * router.get(\"/account\", authMiddleware([]), accountController);\n * router.get(\"/admin\", authMiddleware(\"admin\"), adminController);\n * router.get(\"/back-office\", authMiddleware([\"admin\", \"staff\"]), backOfficeController);\n * router.get(\"/browser-account\", authMiddleware([], \"cookie:token\"), accountController);\n */\nexport function authMiddleware(): Middleware;\nexport function authMiddleware(options: AuthMiddlewareOptions): Middleware;\nexport function authMiddleware(\n allowedUserType: string | string[],\n options?: AuthMiddlewareOptions,\n): Middleware;\nexport function authMiddleware(\n allowedUserType: string | string[],\n tokenFrom?: TokenFrom,\n): Middleware;\nexport function authMiddleware(\n userTypeOrOptions?: string | string[] | AuthMiddlewareOptions,\n legacyTokenFromOrOptions?: TokenFrom | AuthMiddlewareOptions,\n): Middleware {\n const options =\n typeof userTypeOrOptions === \"object\" && !Array.isArray(userTypeOrOptions)\n ? userTypeOrOptions\n : typeof legacyTokenFromOrOptions === \"object\"\n ? legacyTokenFromOrOptions\n : undefined;\n const selectedUserType =\n typeof userTypeOrOptions === \"string\" || Array.isArray(userTypeOrOptions)\n ? userTypeOrOptions\n : undefined;\n const allowedTypes = resolveAllowedTypes(selectedUserType);\n const legacyTokenFrom =\n typeof legacyTokenFromOrOptions === \"string\" ? legacyTokenFromOrOptions : undefined;\n const dualSources = options?.sources?.length\n ? options.sources.map(tokenFromDescriptor)\n : undefined;\n\n if (dualSources && options?.source) {\n throw new Error(\"authMiddleware accepts either `source` or `sources`, not both.\");\n }\n\n const dualHeader = dualSources?.includes(\"header\") ?? false;\n const dualCookies = dualSources?.filter((source) => source !== \"header\") ?? [];\n\n if (dualSources && (dualCookies.length > 1 || dualSources.length - dualCookies.length > 1)) {\n throw new Error(\"authMiddleware `sources` accepts at most one header and one cookie.\");\n }\n\n // With dual sources the configured cookie is the base credential; the header\n // is chosen per request, ahead of it.\n const cookieTokenFrom: TokenFrom = dualSources\n ? (dualCookies[0] ?? \"header\")\n : options\n ? tokenFromDescriptor(options)\n : (legacyTokenFrom ?? \"header\");\n const tokenFrom = cookieTokenFrom;\n const refreshCredential = options?.refresh ? tokenFromDescriptor(options.refresh) : undefined;\n const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : undefined;\n\n if (\n refreshCredential &&\n (tokenFrom === \"header\" || refreshCredential === \"header\" || !renewalUserType)\n ) {\n throw new Error(\n \"authMiddleware automatic renewal requires one allowed user type and cookie access and refresh credentials.\",\n );\n }\n\n const optional = options?.optional === true;\n\n const auth: Middleware = async ({ request, response }) => {\n const reject = (payload: UnauthorizedPayload) =>\n rejectUnauthorized({ request, response }, payload, options?.redirect);\n\n // A present Authorization header always wins and never falls back to the\n // cookie: the credential used is the header, so no renewal and no CSRF check.\n const headerWins = dualHeader && Boolean(request.authorizationValue);\n const usedTokenFrom: TokenFrom = headerWins ? \"header\" : tokenFrom;\n const usedRefresh = headerWins ? undefined : refreshCredential;\n\n // Renewal can mint cookies, so a cookie-authenticated unsafe request must\n // pass the same CSRF check even when its access cookie is missing.\n if (\n (readCredential(request, usedTokenFrom) ||\n (usedRefresh && readCredential(request, usedRefresh))) &&\n requiresCsrfOriginCheck(usedTokenFrom, request.method)\n ) {\n try {\n assertCsrfOriginAllowed(request);\n } catch (error) {\n if (!(error instanceof CsrfOriginMismatchError)) throw error;\n\n log.error(\"http\", \"auth\", error);\n return response.forbidden({\n error: t(\"auth.errors.csrfOriginMismatch\"),\n errorCode: AuthErrorCodes.CsrfOriginMismatch,\n });\n }\n }\n\n const outcome = await resolveRequestUserOutcome(request, response, {\n tokenFrom: usedTokenFrom,\n refreshCredential: usedRefresh,\n overlapMs: options?.refresh?.overlapMs,\n allowedTypes,\n renewalUserType,\n });\n\n if (outcome.user) {\n request.locals.user = outcome.user;\n return;\n }\n\n if (outcome.failure === \"forbidden\") {\n return response.forbidden({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n }\n\n if (optional) return;\n\n if (outcome.failure === \"missing\") {\n return reject({\n error: t(\"auth.errors.missingAccessToken\"),\n errorCode: AuthErrorCodes.MissingAccessToken,\n });\n }\n\n if (outcome.failure === \"unauthorized\") {\n return reject({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n }\n\n return reject({\n error: t(\"auth.errors.invalidAccessToken\"),\n errorCode: AuthErrorCodes.InvalidAccessToken,\n });\n };\n\n const descriptorSources: AuthMiddlewareDescriptorSource[] = dualSources\n ? [...(dualHeader ? ([\"header\"] as const) : []), ...dualCookies.map(descriptorSource)]\n : [descriptorSource(tokenFrom)];\n const descriptor: AuthMiddlewareDescriptor = Object.freeze({\n ...(optional ? { required: false } : {}),\n sources: Object.freeze(\n descriptorSources.map((source) =>\n typeof source === \"string\" ? source : Object.freeze({ ...source }),\n ),\n ) as AuthMiddlewareDescriptorSource[],\n userTypes: Object.freeze([...allowedTypes]) as string[],\n });\n\n // Non-enumerable so the tag never shows up in logs, spreads or JSON.\n Object.defineProperty(auth, AUTH_MIDDLEWARE_DESCRIPTOR, { value: descriptor, enumerable: false });\n\n // Tells `warlock dev` and `warlock inspect` that routes behind this\n // middleware are authenticated. `{ optional: true }`\n // lets anonymous requests through, so it does not count as a guard.\n return markAuthGuard(auth, !optional);\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,6BAA6B,OAAO,IAAI,cAAc;;;;;;;;;;;;;;;;;;;AAsCnE,SAAS,mBACP,EAAE,SAAS,YACX,SACA,UACA;CACA,MAAM,YAAY,UAAU,MAAM,WAAW,SAAS,UAAU;CAChE,MAAM,iBAAiB,UAAU,kBAAkB,WAAW,SAAS,eAAe;CAEtF,IAAI,aAAa,QAAQ,OAAO,QAAQ;EAMtC,MAAM,cAAc,mBAAmB,WAAW,QAAQ,MAAM;EAChE,MAAM,YAAY,YAAY,SAAS,GAAG,IAAI,MAAM;EACpD,MAAM,YAAY,mBAAmB,QAAQ,GAAG;EAEhD,OAAO,SAAS,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,WACtB,OAAO,OAAO;GACZ,OAAO,EAAE,gCAAgC;GACzC;EACF,CAAC;EAGH,IAAI,QAAQ,YAAY,gBACtB,OAAO,OAAO;GACZ,OAAO,EAAE,0BAA0B;GACnC;EACF,CAAC;EAGH,OAAO,OAAO;GACZ,OAAO,EAAE,gCAAgC;GACzC;EACF,CAAC;CACH;CAEA,MAAM,oBAAsD,cACxD,CAAC,GAAI,aAAc,CAAC,QAAQ,IAAc,CAAC,GAAI,GAAG,YAAY,IAAI,gBAAgB,CAAC,IACnF,CAAC,iBAAiB,SAAS,CAAC;CAChC,MAAM,aAAuC,OAAO,OAAO;EACzD,GAAI,WAAW,EAAE,UAAU,MAAM,IAAI,CAAC;EACtC,SAAS,OAAO,OACd,kBAAkB,KAAK,WACrB,OAAO,WAAW,WAAW,SAAS,OAAO,OAAO,EAAE,GAAG,OAAO,CAAC,CACnE,CACF;EACA,WAAW,OAAO,OAAO,CAAC,GAAG,YAAY,CAAC;CAC5C,CAAC;CAGD,OAAO,eAAe,MAAM,4BAA4B;EAAE,OAAO;EAAY,YAAY;CAAM,CAAC;CAKhG,OAAO,cAAc,MAAM,CAAC,QAAQ;AACtC"}
1
+ {"version":3,"file":"auth.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/auth.middleware.ts"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,6BAA6B,OAAO,IAAI,cAAc;;;;;;;;;;;;;;;;;;;AAsCnE,SAAS,mBACP,EAAE,SAAS,YACX,SACA,UACA;CACA,MAAM,YAAY,UAAU,MAAM,WAAW,SAAS,UAAU;CAChE,MAAM,iBAAiB,UAAU,kBAAkB,WAAW,SAAS,eAAe;CAEtF,IAAI,aAAa,QAAQ,OAAO,QAAQ;EAMtC,MAAM,cAAc,mBAAmB,WAAW,QAAQ,MAAM;EAChE,MAAM,YAAY,YAAY,SAAS,GAAG,IAAI,MAAM;EACpD,MAAM,YAAY,mBAAmB,QAAQ,GAAG;EAEhD,OAAO,SAAS,SA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ACtB,OAAO,OAAO;GACZ,OAAO,EAAE,gCAAgC;GACzC;EACF,CAAC;EAGH,IAAI,QAAQ,YAAY,gBACtB,OAAO,OAAO;GACZ,OAAO,EAAE,0BAA0B;GACnC;EACF,CAAC;EAGH,OAAO,OAAO;GACZ,OAAO,EAAE,gCAAgC;GACzC;EACF,CAAC;CACH;CAEA,MAAM,oBAAsD,cACxD,CAAC,GAAI,aAAc,CAAC,QAAQ,IAAc,CAAC,GAAI,GAAG,YAAY,IAAI,gBAAgB,CAAC,IACnF,CAAC,iBAAiB,SAAS,CAAC;CAChC,MAAM,aAAuC,OAAO,OAAO;EACzD,GAAI,WAAW,EAAE,UAAU,MAAM,IAAI,CAAC;EACtC,SAAS,OAAO,OACd,kBAAkB,KAAK,WACrB,OAAO,WAAW,WAAW,SAAS,OAAO,OAAO,EAAE,GAAG,OAAO,CAAC,CACnE,CACF;EACA,WAAW,OAAO,OAAO,CAAC,GAAG,YAAY,CAAC;CAC5C,CAAC;CAGD,OAAO,eAAe,MAAM,4BAA4B;EAAE,OAAO;EAAY,YAAY;CAAM,CAAC;CAKhG,OAAO,cAAc,MAAM,CAAC,QAAQ;AACtC"}
@@ -1 +1 @@
1
- {"version":3,"file":"csrf-origin-check.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/csrf-origin-check.ts"],"sourcesContent":["import { resolveCsrfOriginVerdict, type Request } from \"@warlock.js/core\";\nimport type { TokenFrom } from \"../contracts/types\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/** HTTP methods the CSRF Origin check exempts — reads, never state changes. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** Why {@link assertCsrfOriginAllowed} refused a request. */\nexport type CsrfOriginMismatchReason =\n | \"origin-mismatch\"\n | \"referer-mismatch\"\n | \"missing-origin-and-referer\";\n\n/**\n * A cookie-authenticated, unsafe-method request whose `Origin`/`Referer`\n * failed the check. `reason` names exactly why,\n * so an error transformer or an incident log never has to string-match the\n * message.\n */\nexport class CsrfOriginMismatchError extends Error {\n readonly code = AuthErrorCodes.CsrfOriginMismatch;\n\n constructor(public readonly reason: CsrfOriginMismatchReason) {\n super(`CSRF Origin check failed: ${reason}`);\n this.name = \"CsrfOriginMismatchError\";\n }\n}\n\n/**\n * Whether a request is in scope for the CSRF Origin check at all — only a\n * `cookie:`-sourced credential on an unsafe method (POST/PUT/PATCH/DELETE) is.\n * Header-token auth and safe methods (GET/HEAD/OPTIONS) are always exempt:\n * only a cookie-sourced credential can be silently replayed cross-site by a\n * browser, so only it needs the check.\n */\nexport function requiresCsrfOriginCheck(tokenFrom: TokenFrom, method: string): boolean {\n return tokenFrom.startsWith(\"cookie:\") && !SAFE_METHODS.has(method.toUpperCase());\n}\n\n/**\n * CSRF Origin check for a cookie-authenticated unsafe-method request (lead\n * decision 3). Allowed when `Origin` — or, when `Origin` is absent, `Referer`\n * — names the request's own origin or an entry in `auth.csrf.allowedOrigins`.\n * Throws {@link CsrfOriginMismatchError} otherwise, including when BOTH\n * headers are absent.\n *\n * Delegates the actual same-origin/allowedOrigins/trustProxy-aware\n * comparison to `@warlock.js/core`'s `resolveCsrfOriginVerdict`\n * (`core/src/http/csrf-origin-policy.ts`) — SECURITY card 8a752ab2 moved that\n * logic down into `core` so this middleware's check and core's own default\n * CSRF-Origin guard (`core/src/http/csrf-default-guard.ts`, which now runs\n * even earlier, ahead of this middleware, for cookie-carrying unsafe-method\n * requests generally) share one implementation instead of two copies that\n * could drift apart.\n *\n * Callers gate this behind {@link requiresCsrfOriginCheck} — this function\n * itself does not re-check the token source or the method.\n */\nexport function assertCsrfOriginAllowed(request: Request): void {\n const verdict = resolveCsrfOriginVerdict(request);\n\n if (!verdict.allowed) {\n throw new CsrfOriginMismatchError(verdict.reason);\n }\n}\n"],"mappings":";;;;;AAKA,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;;;;;;AAcvD,IAAa,0BAAb,cAA6C,MAAM;CAGjD,YAAY,AAAgB,QAAkC;EAC5D,MAAM,6BAA6B,QAAQ;EADjB;;EAE1B,KAAK,OAAO;CACd;AACF;;;;;;;;AASA,SAAgB,wBAAwB,WAAsB,QAAyB;CACrF,OAAO,UAAU,WAAW,SAAS,KAAK,CAAC,aAAa,IAAI,OAAO,YAAY,CAAC;AAClF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,wBAAwB,SAAwB;CAC9D,MAAM,UAAU,yBAAyB,OAAO;CAEhD,IAAI,CAAC,QAAQ,SACX,MAAM,IAAI,wBAAwB,QAAQ,MAAM;AAEpD"}
1
+ {"version":3,"file":"csrf-origin-check.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/csrf-origin-check.ts"],"mappings":";;;;;AAKA,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;;;;;;AAcvD,IAAa,0BAAb,cAA6C,MAAM;CAGjD,YAAY,AAAgB,QAAkC;EAC5D,MAAM,6BAA6B,QAAQ;EADjB;;EAE1B,KAAK,OAAO;CACd;AACF;;;;;;;;AASA,SAAgB,wBAAwB,WAAsB,QAAyB;CACrF,OAAO,UAAU,WAAW,SAAS,KAAK,CAAC,aAAa,IAAI,OAAO,YAAY,CAAC;AAClF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,wBAAwB,SAAwB;CAC9D,MAAM,UAAU,yBAAyB,OAAO;CAEhD,IAAI,CAAC,QAAQ,SACX,MAAM,IAAI,wBAAwB,QAAQ,MAAM;AAEpD"}
@@ -1 +1 @@
1
- {"version":3,"file":"localized-login-path.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/localized-login-path.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\n\n/**\n * Prefixes `loginPath` with `locale` when `web`'s locale-URL routing is\n * active for that locale — so a guarded `/ar/admin` page redirects an\n * anonymous request to `/ar/login`, not the bare `/login` (finding: the\n * `returnUrl` carried the locale, the login destination itself did not).\n *\n * `auth` is not on `web`'s dependency graph, and `web` is not on `auth`'s\n * (neither package declares the other, in either `dependencies` or\n * `peerDependencies`) — so this cannot import `web`'s\n * `resolveLocaleRouting()` / `withLocalePrefix()` / `isPrefixedLocale()`\n * (`web/src/routing/locale-routing.ts`, `web/src/routing/locale-prefixed-paths.ts`).\n * Instead it reads the SAME config keys those read — `web.localeRouting.strategy`,\n * `app.localeCodes`, `app.localeCode` — by convention rather than by import,\n * the same pattern `web/src/server/auth-cookie-name.ts` uses in the other\n * direction for `auth.cookie.name`.\n *\n * Left alone (returned unchanged) when:\n * - `loginPath` is absolute (`http://…`, `https://…`) — a redirect target\n * outside this app has no \"locale prefix\" to add.\n * - `loginPath` is already prefixed with a known locale code (an app that\n * configured `auth.pageAuth.loginPath` as `/ar/login` itself).\n * - `web.localeRouting.strategy` is `\"none\"` (the default) or unset.\n * - `locale` is not one of `app.localeCodes`, or — under\n * `\"prefix-except-default\"` — `locale` is the default locale.\n */\nexport function localizedLoginPath(loginPath: string, locale: string): string {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(loginPath)) return loginPath;\n\n const strategy = config.key<string>(\"web.localeRouting.strategy\", \"none\");\n\n if (strategy !== \"prefix\" && strategy !== \"prefix-except-default\") return loginPath;\n\n const codes = config.key<string[]>(\"app.localeCodes\", []) ?? [];\n\n if (isAlreadyPrefixed(loginPath, codes)) return loginPath;\n\n if (!codes.includes(locale)) return loginPath;\n\n if (strategy === \"prefix-except-default\") {\n const defaultLocale = config.key<string>(\"app.localeCode\", \"\");\n\n if (locale === defaultLocale) return loginPath;\n }\n\n return loginPath === \"/\" ? `/${locale}` : `/${locale}${loginPath}`;\n}\n\n/** `true` when `path` already starts with one of `codes` as its own URL segment. */\nfunction isAlreadyPrefixed(path: string, codes: readonly string[]): boolean {\n return codes.some((code) => path === `/${code}` || path.startsWith(`/${code}/`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,mBAAmB,WAAmB,QAAwB;CAC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UAAU,KAAK,WAAW,IAAI,KAAK,EAAE,CAAC;AACjF"}
@@ -14,16 +14,19 @@ export type LoginThrottleIdentifier = "email" | "ip";
14
14
  /**
15
15
  * Options for {@link loginThrottleMiddleware}.
16
16
  *
17
- * Failure-aware by design: only counts requests whose response is non-2xx
18
- * (or whatever `isFailure` says) and resets on success, so a user who types
19
- * a wrong password three times then the right one is not penalised.
17
+ * Failure-aware by design: every attempt is counted when it arrives (so a
18
+ * burst of concurrent requests cannot outrun the limit), and a successful
19
+ * response (2xx, or whatever `isFailure` says) resets the count, so a user who
20
+ * types a wrong password three times then the right one is not penalised.
20
21
  *
21
22
  * @example
22
23
  * loginThrottleMiddleware({ max: 5, window: "15m", lockoutDuration: "15m" });
23
24
  */
24
25
  export type LoginThrottleOptions = {
25
26
  /**
26
- * Failures allowed within the window before the identifier is locked.
27
+ * Failures allowed within the window before the identifier is locked. It
28
+ * also caps how many attempts may be in flight at once: a request beyond it
29
+ * is refused with `429` before the controller runs.
27
30
  *
28
31
  * @default 5
29
32
  */
@@ -54,6 +57,28 @@ export type LoginThrottleOptions = {
54
57
  * @default "email"
55
58
  */
56
59
  identifierKey?: string;
60
+ /**
61
+ * Who an account lock applies to when both `"email"` and `"ip"` are tracked.
62
+ *
63
+ * - `"global"` — `max` failures for an email, from any source, lock that
64
+ * email for everyone (the account owner included).
65
+ * - `"pair"` — the `max` lock applies to the (email, source IP) pair, so a
66
+ * stranger guessing from their own IP cannot lock the owner out. The email
67
+ * alone keeps a wider bucket (`accountMax`) that still stops guessing
68
+ * spread across many IPs.
69
+ *
70
+ * Ignored when `identify` is set or `by` does not track both.
71
+ *
72
+ * @default "global"
73
+ */
74
+ emailLock?: "pair" | "global";
75
+ /**
76
+ * Attempts one email may take from all sources together within the window
77
+ * before it is locked, when `emailLock` is `"pair"`.
78
+ *
79
+ * @default max * 10
80
+ */
81
+ accountMax?: number;
57
82
  /**
58
83
  * Override the default error message returned with the 429 response.
59
84
  */
@@ -97,11 +122,16 @@ export declare function throttleIdentifierHash(kind: string, value: string): str
97
122
  *
98
123
  * 1. **Before the controller** — reject with `429` if a lock key is set,
99
124
  * skipping the DB lookup AND the bcrypt verify (this also neutralises the
100
- * CPU-DoS angle of brute-forcing).
125
+ * CPU-DoS angle of brute-forcing). Otherwise count the attempt in a
126
+ * fixed-window counter right away, and reject with `429` (setting the lock)
127
+ * when it goes past `max`. Counting at entry is what bounds a burst of
128
+ * concurrent requests: at most `max` attempts per window reach the
129
+ * controller, however many arrive at once.
101
130
  * 2. **After the controller** — observe the outcome via `response.onSent`.
102
- * On failure (non-2xx by default), bump a fixed-window counter; once it
103
- * reaches `max`, set a lock key with `lockoutDuration` TTL. On success,
104
- * clear both the counter and the lock for that identifier.
131
+ * On failure (non-2xx by default), set a lock key with `lockoutDuration`
132
+ * TTL once the attempt count has reached `max` (unless a success reset the
133
+ * counter meanwhile). On success, reset the counter to 0 and clear the lock
134
+ * for that identifier.
105
135
  *
106
136
  * Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,
107
137
  * transitively guaranteed via `@warlock.js/core`). Lockout state is shared
@@ -1 +1 @@
1
- {"version":3,"file":"login-throttle.middleware.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;YAmBY;;;;;;;;;;;YAYA;;;;;;EAMV;;;;;;EAOA;;;;;;EAOA;;;;;;EAOA,KAAK;;;;;;;;EASL;;;;EAKA;;;;;;;;EASA,aAAa,UAAU;;;;;;EAOvB,YAAY,SAAS;;;;;;;;;;;;;;;;wBAwCP,uBAAuB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA0IrC,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAiLrC,wBAAwB,UAAS,uBAA4B"}
@@ -3,9 +3,9 @@ import { normalizeEmailIdentifier } from "../utils/normalize-credentials.mjs";
3
3
  import { authConfig } from "../services/auth-config.mjs";
4
4
  import { t } from "@warlock.js/core";
5
5
  import { createHash, createHmac } from "node:crypto";
6
+ import { cache } from "@warlock.js/cache";
6
7
  import { log } from "@warlock.js/logger";
7
8
  import ms from "ms";
8
- import { cache } from "@warlock.js/cache";
9
9
 
10
10
  //#region ../../packages/auth/src/middleware/login-throttle.middleware.ts
11
11
  const COUNTER_PREFIX = "auth.throttle.count.";
@@ -89,19 +89,51 @@ function durationSeconds(duration) {
89
89
  * per-source key. Untruthy values are dropped; a request that yields zero
90
90
  * identifiers is left untracked so the middleware no-ops for it.
91
91
  */
92
- function buildDefaultIdentifiers(request, tracked, credentialField) {
92
+ function buildDefaultIdentifiers(request, tracked, credentialField, max, pair) {
93
93
  const identifiers = [];
94
- if (tracked.includes("email")) {
95
- const value = request.input(credentialField);
96
- if (typeof value === "string" && value.trim().length > 0) identifiers.push(`email.${throttleIdentifierHash("email", value)}`);
97
- }
98
- if (tracked.includes("ip")) {
99
- const ip = request.detectIp();
100
- if (ip) identifiers.push(`ip.${throttleIdentifierHash("ip", ip)}`);
94
+ const value = tracked.includes("email") ? request.input(credentialField) : void 0;
95
+ const email = typeof value === "string" && value.trim().length > 0 ? value : void 0;
96
+ const ip = tracked.includes("ip") ? request.detectIp() : void 0;
97
+ if (email !== void 0) {
98
+ if (pair && ip) {
99
+ const pairValue = `${normalizeEmailIdentifier(email)}|${ip}`;
100
+ identifiers.push({
101
+ key: `email-ip.${throttleIdentifierHash("email-ip", pairValue)}`,
102
+ max
103
+ });
104
+ identifiers.push({
105
+ key: `email.${throttleIdentifierHash("email", email)}`,
106
+ max: pair.accountMax
107
+ });
108
+ } else identifiers.push({
109
+ key: `email.${throttleIdentifierHash("email", email)}`,
110
+ max
111
+ });
101
112
  }
113
+ if (ip) identifiers.push({
114
+ key: `ip.${throttleIdentifierHash("ip", ip)}`,
115
+ max
116
+ });
102
117
  return identifiers;
103
118
  }
104
119
  /**
120
+ * Whether the counter now reads a number below `count`, i.e. a success reset
121
+ * it while this attempt ran. Fails closed: a missing value (expired, evicted,
122
+ * a driver that stores nothing), a non-numeric one or a failed read all answer
123
+ * `false`, so the caller locks.
124
+ */
125
+ async function counterWasReset(identifier, count) {
126
+ let current;
127
+ try {
128
+ current = await cache.get(counterKey(identifier));
129
+ } catch (error) {
130
+ log.error("auth", "login-throttle", error);
131
+ return false;
132
+ }
133
+ if (typeof current === "string" && current.trim() !== "") current = Number(current);
134
+ return typeof current === "number" && Number.isFinite(current) && current < count;
135
+ }
136
+ /**
105
137
  * Failure-aware login throttle. Locks an identifier (account, IP, or both)
106
138
  * after too many failed login attempts within a window — without penalising
107
139
  * a user who eventually types the right password.
@@ -110,11 +142,16 @@ function buildDefaultIdentifiers(request, tracked, credentialField) {
110
142
  *
111
143
  * 1. **Before the controller** — reject with `429` if a lock key is set,
112
144
  * skipping the DB lookup AND the bcrypt verify (this also neutralises the
113
- * CPU-DoS angle of brute-forcing).
145
+ * CPU-DoS angle of brute-forcing). Otherwise count the attempt in a
146
+ * fixed-window counter right away, and reject with `429` (setting the lock)
147
+ * when it goes past `max`. Counting at entry is what bounds a burst of
148
+ * concurrent requests: at most `max` attempts per window reach the
149
+ * controller, however many arrive at once.
114
150
  * 2. **After the controller** — observe the outcome via `response.onSent`.
115
- * On failure (non-2xx by default), bump a fixed-window counter; once it
116
- * reaches `max`, set a lock key with `lockoutDuration` TTL. On success,
117
- * clear both the counter and the lock for that identifier.
151
+ * On failure (non-2xx by default), set a lock key with `lockoutDuration`
152
+ * TTL once the attempt count has reached `max` (unless a success reset the
153
+ * counter meanwhile). On success, reset the counter to 0 and clear the lock
154
+ * for that identifier.
118
155
  *
119
156
  * Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,
120
157
  * transitively guaranteed via `@warlock.js/core`). Lockout state is shared
@@ -143,15 +180,47 @@ function loginThrottleMiddleware(options = {}) {
143
180
  const lockoutDuration = options.lockoutDuration ?? "15m";
144
181
  const tracked = options.by ?? ["email", "ip"];
145
182
  const credentialField = options.identifierKey ?? "email";
183
+ const pair = options.emailLock === "pair" && tracked.includes("email") && tracked.includes("ip") ? { accountMax: options.accountMax ?? max * 10 } : void 0;
184
+ /**
185
+ * Lock an identifier for `lockoutDuration`. The counter is rewritten with
186
+ * the same TTL, so the two expire together and the identifier starts a fresh
187
+ * window once the lockout ends. Rewriting keeps a value of at least `count`,
188
+ * so a request that slipped past the lock check still sees "over the limit".
189
+ */
190
+ const lock = async (identifier, count) => {
191
+ const lockSeconds = durationSeconds(lockoutDuration);
192
+ await cache.set(lockKey(identifier), lockSeconds === void 0 ? true : Date.now() + lockSeconds * 1e3, { ttl: lockoutDuration });
193
+ await cache.set(counterKey(identifier), count, { ttl: lockoutDuration });
194
+ };
146
195
  return async ({ request, response }) => {
147
- const identifiers = options.identify ? options.identify(request) : buildDefaultIdentifiers(request, tracked, credentialField);
196
+ const identifiers = options.identify ? options.identify(request).map((key) => ({
197
+ key,
198
+ max
199
+ })) : buildDefaultIdentifiers(request, tracked, credentialField, max, pair);
148
200
  if (identifiers.length === 0) return;
149
201
  warnIfNullDriver();
202
+ const tooManyRequests = () => response.tooManyRequests({
203
+ error: options.errorMessage ?? t("auth.errors.tooManyAttempts"),
204
+ errorCode: "EC004"
205
+ });
206
+ /** The attempt number this request took in each identifier's window. */
207
+ const counts = /* @__PURE__ */ new Map();
150
208
  try {
151
- for (const identifier of identifiers) if (isLocked(await cache.get(lockKey(identifier)))) return response.tooManyRequests({
152
- error: options.errorMessage ?? t("auth.errors.tooManyAttempts"),
153
- errorCode: "EC004"
154
- });
209
+ for (const identifier of identifiers) if (isLocked(await cache.get(lockKey(identifier.key)))) return tooManyRequests();
210
+ for (const identifier of identifiers) {
211
+ const key = counterKey(identifier.key);
212
+ await cache.set(key, 0, {
213
+ ttl: window,
214
+ onConflict: "create"
215
+ });
216
+ const count = await cache.increment(key, 1, { ttl: window });
217
+ if (typeof count !== "number" || !Number.isFinite(count)) continue;
218
+ counts.set(identifier.key, count);
219
+ if (count > identifier.max) {
220
+ if (count === identifier.max + 1) await lock(identifier.key, count);
221
+ return tooManyRequests();
222
+ }
223
+ }
155
224
  } catch (error) {
156
225
  log.error("auth", "login-throttle", error);
157
226
  return;
@@ -160,21 +229,16 @@ function loginThrottleMiddleware(options = {}) {
160
229
  try {
161
230
  if (!(options.isFailure ? options.isFailure(resolvedResponse) : !resolvedResponse.isOk)) {
162
231
  for (const identifier of identifiers) {
163
- await cache.remove(counterKey(identifier));
164
- await cache.remove(lockKey(identifier));
232
+ await cache.set(counterKey(identifier.key), 0, { ttl: window });
233
+ await cache.remove(lockKey(identifier.key));
165
234
  }
166
235
  return;
167
236
  }
168
237
  for (const identifier of identifiers) {
169
- const key = counterKey(identifier);
170
- await cache.set(key, 0, {
171
- ttl: window,
172
- onConflict: "create"
173
- });
174
- if (await cache.increment(key, 1, { ttl: window }) >= max) {
175
- const lockSeconds = durationSeconds(lockoutDuration);
176
- await cache.set(lockKey(identifier), lockSeconds === void 0 ? true : Date.now() + lockSeconds * 1e3, { ttl: lockoutDuration });
177
- }
238
+ const count = counts.get(identifier.key);
239
+ if (count === void 0 || count < identifier.max) continue;
240
+ if (await counterWasReset(identifier.key, count)) continue;
241
+ await lock(identifier.key, count);
178
242
  }
179
243
  } catch (error) {
180
244
  log.error("auth", "login-throttle", error);
@@ -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: only counts requests whose response is non-2xx\n * (or whatever `isFailure` says) and resets on success, so a user who types\n * 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.\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 * 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): string[] {\n const identifiers: string[] = [];\n\n if (tracked.includes(\"email\")) {\n const value = request.input(credentialField);\n\n if (typeof value === \"string\" && value.trim().length > 0) {\n identifiers.push(`email.${throttleIdentifierHash(\"email\", value)}`);\n }\n }\n\n if (tracked.includes(\"ip\")) {\n const ip = request.detectIp();\n\n if (ip) {\n identifiers.push(`ip.${throttleIdentifierHash(\"ip\", ip)}`);\n }\n }\n\n return identifiers;\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).\n * 2. **After the controller** — observe the outcome via `response.onSent`.\n * On failure (non-2xx by default), bump a fixed-window counter; once it\n * reaches `max`, set a lock key with `lockoutDuration` TTL. On success,\n * clear both the counter and the lock 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\n return async ({ request, response }) => {\n const identifiers = options.identify\n ? options.identify(request)\n : buildDefaultIdentifiers(request, tracked, credentialField);\n\n if (identifiers.length === 0) return;\n\n warnIfNullDriver();\n\n try {\n for (const identifier of identifiers) {\n const locked = isLocked(await cache.get(lockKey(identifier)));\n\n if (locked) {\n return response.tooManyRequests({\n error: options.errorMessage ?? t(\"auth.errors.tooManyAttempts\"),\n errorCode: AuthErrorCodes.TooManyAttempts,\n });\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 await cache.remove(counterKey(identifier));\n await cache.remove(lockKey(identifier));\n }\n\n return;\n }\n\n for (const identifier of identifiers) {\n const key = counterKey(identifier);\n\n // Open the window on the first failure: 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 failures across servers are never\n // lost (redis INCRBY / pg upsert keep the window's TTL). Passing\n // the 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 (count >= max) {\n const lockSeconds = durationSeconds(lockoutDuration);\n\n // The lock stores its own deadline: a driver with sliding\n // expiration (`memoryExtended`) pushes the key's TTL forward on\n // every read, but the deadline in the value does not move, so a\n // client that keeps retrying is still released after\n // `lockoutDuration`.\n await cache.set(\n lockKey(identifier),\n lockSeconds === undefined ? true : Date.now() + lockSeconds * 1000,\n { ttl: lockoutDuration },\n );\n }\n }\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AA2FA,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;CAE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,MAFgB,MAAM,UAAU,KAAK,GAAG,EAAE,KAAK,OAAO,CAAC,KAE9C,KAAK;MAChB,MAAM,cAAc,gBAAgB,eAAe;MAOnD,MAAM,MAAM,IACV,QAAQ,UAAU,GAClB,gBAAgB,SAAY,OAAO,KAAK,IAAI,IAAI,cAAc,KAC9D,EAAE,KAAK,gBAAgB,CACzB;KACF;IACF;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"],"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,KAAK,GAAG,yBAAyB,KAAK;CAC5D,MAAM,MAAM,gBAAgB;CAE5B,OAAO,MACH,WAAW,UAAU,GAAG,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK,IACzD,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK;AAC1D;AAEA,IAAI,mBAAmB;;;;;AAMvB,SAAS,mBAAyB;CAChC,IAAI,kBAAkB;CAItB,IAFoB,MAAgD,eAAe,SAEhE,QAAQ;CAE3B,mBAAmB;CACnB,IAAI,KACF,QACA,kBACA,2IACF;AACF;;;;;AAMA,SAAS,SAAS,OAAyB;CACzC,IAAI,OAAO,UAA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AK;GAC3C;EACF,CAAC;CACH;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"one-time-token-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/one-time-token-throttle.middleware.ts"],"sourcesContent":["import type { Middleware } from \"@warlock.js/core\";\nimport { loginThrottleMiddleware, type LoginThrottleOptions } from \"./login-throttle.middleware\";\n\n/**\n * Throttle for routes that ISSUE a verification or reset token (\"send\n * verification email\", \"forgot password\"). Built on\n * {@link loginThrottleMiddleware}, tracked per email and per IP, with one\n * difference: EVERY request counts. A reset request answers the same success\n * for known and unknown emails, so a failure-aware counter would never trip.\n *\n * Defaults: 3 requests per 1h window, then a 1h lockout (`429`, `EC004`).\n *\n * @example\n * router.post(\"/auth/forgot-password\", forgotPassword, {\n * middleware: [tokenIssueThrottleMiddleware()],\n * });\n */\nexport function tokenIssueThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n return loginThrottleMiddleware({\n max: 3,\n window: \"1h\",\n lockoutDuration: \"1h\",\n by: [\"email\", \"ip\"],\n isFailure: () => true,\n ...options,\n });\n}\n\n/**\n * Throttle for routes that CONSUME a token (\"verify email\", \"reset\n * password\"). Built on {@link loginThrottleMiddleware}: per IP (the body\n * carries a token, not an account), failure-aware — a rejected token counts,\n * a successful use clears the counter.\n *\n * Defaults: 10 failures per 15m window, then a 15m lockout (`429`, `EC004`).\n *\n * @example\n * router.post(\"/auth/reset-password\", resetPasswordController, {\n * middleware: [tokenConsumeThrottleMiddleware()],\n * });\n */\nexport function tokenConsumeThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n return loginThrottleMiddleware({\n max: 10,\n window: \"15m\",\n lockoutDuration: \"15m\",\n by: [\"ip\"],\n ...options,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,SAAgB,6BAA6B,UAAgC,CAAC,GAAe;CAC3F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,SAAS,IAAI;EAClB,iBAAiB;EACjB,GAAG;CACL,CAAC;AACH;;;;;;;;;;;;;;AAeA,SAAgB,+BAA+B,UAAgC,CAAC,GAAe;CAC7F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,IAAI;EACT,GAAG;CACL,CAAC;AACH"}
1
+ {"version":3,"file":"one-time-token-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/one-time-token-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,SAAgB,6BAA6B,UAAgC,CAAC,GAAe;CAC3F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,SAAS,IAAI;EAClB,iBAAiB;EACjB,GAAG;CACL,CAAC;AACH;;;;;;;;;;;;;;AAeA,SAAgB,+BAA+B,UAAgC,CAAC,GAAe;CAC7F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,IAAI;EACT,GAAG;CACL,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"otp-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/otp-throttle.middleware.ts"],"sourcesContent":["import type { Middleware } from \"@warlock.js/core\";\nimport { loginThrottleMiddleware, type LoginThrottleOptions } from \"./login-throttle.middleware\";\nimport { tokenIssueThrottleMiddleware } from \"./one-time-token-throttle.middleware\";\n\n/**\n * Throttle for the route that SENDS a login code. {@link tokenIssueThrottleMiddleware}\n * keyed on the `phone` input and IP: every request counts (the answer is the\n * same for unknown phones), 3 per 1h, then a 1h lockout (`429`, `EC004`).\n *\n * @example\n * router.post(\"/auth/otp/request\", requestOtpController, {\n * middleware: [otpRequestThrottleMiddleware()],\n * });\n */\nexport function otpRequestThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n return tokenIssueThrottleMiddleware({ identifierKey: \"phone\", ...options });\n}\n\n/**\n * Throttle for the route that VERIFIES a login code. {@link loginThrottleMiddleware}\n * keyed on `phone` and IP, failure-aware: 5 failures per 15m, then a 15m lockout\n * (`429`, `EC004`). Complements the per-code attempt cap, which a fresh code\n * would otherwise reset.\n *\n * @example\n * router.post(\"/auth/otp/verify\", verifyOtpController, {\n * middleware: [otpVerifyThrottleMiddleware()],\n * });\n */\nexport function otpVerifyThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n return loginThrottleMiddleware({\n max: 5,\n window: \"15m\",\n lockoutDuration: \"15m\",\n by: [\"email\", \"ip\"],\n identifierKey: \"phone\",\n ...options,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,SAAgB,6BAA6B,UAAgC,CAAC,GAAe;CAC3F,OAAO,6BAA6B;EAAE,eAAe;EAAS,GAAG;CAAQ,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,4BAA4B,UAAgC,CAAC,GAAe;CAC1F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,SAAS,IAAI;EAClB,eAAe;EACf,GAAG;CACL,CAAC;AACH"}
1
+ {"version":3,"file":"otp-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/otp-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;;;AAcA,SAAgB,6BAA6B,UAAgC,CAAC,GAAe;CAC3F,OAAO,6BAA6B;EAAE,eAAe;EAAS,GAAG;CAAQ,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,4BAA4B,UAAgC,CAAC,GAAe;CAC1F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,SAAS,IAAI;EAClB,eAAe;EACf,GAAG;CACL,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"require-verified-email.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/require-verified-email.middleware.ts"],"sourcesContent":["import type { Middleware } from \"@warlock.js/core\";\nimport { EmailNotVerifiedError } from \"../errors/email-not-verified.error\";\nimport { authConfig } from \"../services/auth-config\";\n\n/**\n * Opt-in route gate that rejects a user who has not verified their email with\n * {@link EmailNotVerifiedError} (`403`, `EC007`). Place it AFTER\n * `authMiddleware` — it reads `request.locals.user`. A request with no user\n * fails closed with the same error.\n *\n * @example\n * router.post(\"/orders\", createOrder, {\n * middleware: [authMiddleware(\"user\"), requireVerifiedEmail()],\n * });\n */\nexport function requireVerifiedEmail(): Middleware {\n return async ({ request }) => {\n const user = request.locals.user as { get?: (key: string) => unknown } | undefined;\n\n if (!user?.get?.(authConfig.verification.field())) {\n throw new EmailNotVerifiedError();\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,SAAgB,uBAAmC;CACjD,OAAO,OAAO,EAAE,cAAc;EAG5B,IAAI,CAFS,QAAQ,OAAO,MAEjB,MAAM,WAAW,aAAa,MAAM,CAAC,GAC9C,MAAM,IAAI,sBAAsB;CAEpC;AACF"}
1
+ {"version":3,"file":"require-verified-email.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/require-verified-email.middleware.ts"],"mappings":";;;;;;;;;;;;;;;AAeA,SAAgB,uBAAmC;CACjD,OAAO,OAAO,EAAE,cAAc;EAG5B,IAAI,CAFS,QAAQ,OAAO,MAEjB,MAAM,WAAW,aAAa,MAAM,CAAC,GAC9C,MAAM,IAAI,sBAAsB;CAEpC;AACF"}
@@ -46,6 +46,10 @@ export declare class AccessToken extends Model {
46
46
  * only strips it from `toJSON()` / `JSON.stringify(model)` (so
47
47
  * `response.json(token)` or a resource cannot leak it); `get("token")`,
48
48
  * `findByToken` and every query still read the column.
49
+ *
50
+ * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256
51
+ * digest instead, so a copy of the table cannot be replayed; read the raw
52
+ * token of a freshly issued row through {@link plainToken}.
49
53
  */
50
54
  static hidden: string[];
51
55
  /**
@@ -60,6 +64,11 @@ export declare class AccessToken extends Model {
60
64
  get userId(): any;
61
65
  /** The user-type slug this token was issued for. */
62
66
  get userType(): string;
67
+ /**
68
+ * The raw token, when it is known: always for a row stored unhashed, and
69
+ * for a hashed row only in the process that just issued it.
70
+ */
71
+ get plainToken(): string | undefined;
63
72
  /**
64
73
  * Whether the persisted expiry has passed.
65
74
  *
@@ -84,15 +93,17 @@ export declare class AccessToken extends Model {
84
93
  */
85
94
  get neverExpires(): boolean;
86
95
  /**
87
- * Persist a freshly-signed access token for the user.
96
+ * Persist a freshly-signed access token for the user. `token` is the value
97
+ * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.
88
98
  */
89
99
  static issue(user: Auth, token: string, expiresAt: Date, familyId?: string): Promise<AccessToken>;
90
100
  /**
91
- * Find an access-token row by its raw token string.
101
+ * Find an access-token row by its raw token string, whether the row stores
102
+ * the token hashed or raw (one query).
92
103
  */
93
104
  static findByToken(token: string): Promise<AccessToken | null>;
94
105
  /**
95
- * Delete a specific token that belongs to the given user.
106
+ * Delete a specific token that belongs to the given user, stored hashed or raw.
96
107
  */
97
108
  static deleteForUser(user: Auth, token: string): Promise<number>;
98
109
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"access-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"mappings":";;;;;;;;;;;qBAaa,8CAAiB;;;;;;;;;;;;;;;;;;;;qBAmBjB,oBAAoB;SACjB;SAEA,mCAAM;;;;;;;;;;;;;;;;SAQN;;;;;;;;SASA;;MAGH;;MAKA;;;;;;;;;;;;;;;;MAmBA;;;;;;;MAcA;;;;SAOG,MAAM,MAAM,MAAM,eAAe,WAAW,MAAM,oBAAiB,QAAA;;;;SAanE,YAAY,gBAAgB,QAAQ;;;;SAOpC,cAAc,MAAM,MAAM,gBAAa;;;;SAOvC,iBAAiB,MAAM,OAAI;;;;;;SASrB,6BAA6B,MAAM,MAAM,mBAAmB;;;;;SAS5D,gBAAgB;;;;;;;;;;;;SAqBhB,qBAAqB,QAAQ;;;;;;SAW7B,sBAAsB,QAAQ"}
1
+ {"version":3,"file":"access-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"mappings":";;;;;;;;;;;qBAca,8CAAiB;;;;;;;;;;;;;;;;;;;;qBAmBjB,oBAAoB;SACjB;SAEA,mCAAM;;;;;;;;;;;;;;;;;;;;SAYN;;;;;;;;SASA;;MAGH;;MAKA;;;;;MAQA;;;;;;;;;;;;;;;;MAmBA;;;;;;;MAcA;;;;;SAQG,MAAM,MAAM,MAAM,eAAe,WAAW,MAAM,oBAAiB,QAAA;;;;;SAcnE,YAAY,gBAAgB,QAAQ;;;;SAOpC,cAAc,MAAM,MAAM,gBAAa;;;;SAUvC,iBAAiB,MAAM,OAAI;;;;;;SASrB,6BAA6B,MAAM,MAAM,mBAAmB;;;;;SAS5D,gBAAgB;;;;;;;;;;;;SAqBhB,qBAAqB,QAAQ;;;;;;SAW7B,sBAAsB,QAAQ"}
@@ -1,3 +1,4 @@
1
+ import { plainTokenOf, storedTokenForms } from "../../utils/token-digest.mjs";
1
2
  import { isNeverExpiring, isUsableExpiry } from "../../utils/token-expiry.mjs";
2
3
  import { Model } from "@warlock.js/cascade";
3
4
  import { v } from "@warlock.js/seal";
@@ -51,6 +52,13 @@ var AccessToken = class extends Model {
51
52
  return this.get("user_type");
52
53
  }
53
54
  /**
55
+ * The raw token, when it is known: always for a row stored unhashed, and
56
+ * for a hashed row only in the process that just issued it.
57
+ */
58
+ get plainToken() {
59
+ return plainTokenOf(this, this.get("token"));
60
+ }
61
+ /**
54
62
  * Whether the persisted expiry has passed.
55
63
  *
56
64
  * The middleware asks this on every request, which is what makes the row the
@@ -80,7 +88,8 @@ var AccessToken = class extends Model {
80
88
  return isNeverExpiring(this.get("token"), this.get("expires_at"));
81
89
  }
82
90
  /**
83
- * Persist a freshly-signed access token for the user.
91
+ * Persist a freshly-signed access token for the user. `token` is the value
92
+ * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.
84
93
  */
85
94
  static issue(user, token, expiresAt, familyId) {
86
95
  return this.create({
@@ -92,19 +101,17 @@ var AccessToken = class extends Model {
92
101
  });
93
102
  }
94
103
  /**
95
- * Find an access-token row by its raw token string.
104
+ * Find an access-token row by its raw token string, whether the row stores
105
+ * the token hashed or raw (one query).
96
106
  */
97
107
  static findByToken(token) {
98
- return this.first({ token });
108
+ return this.query().whereIn("token", storedTokenForms(token)).first();
99
109
  }
100
110
  /**
101
- * Delete a specific token that belongs to the given user.
111
+ * Delete a specific token that belongs to the given user, stored hashed or raw.
102
112
  */
103
113
  static deleteForUser(user, token) {
104
- return this.delete({
105
- token,
106
- user_id: user.id
107
- });
114
+ return this.query().where({ user_id: user.id }).whereIn("token", storedTokenForms(token)).delete();
108
115
  }
109
116
  /**
110
117
  * Delete every access token belonging to the user.
@@ -1 +1 @@
1
- {"version":3,"file":"access-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted access-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 * `last_access` and the `is_active` soft-revoke flag were removed — neither was\n * ever read; access tokens are revoked by deleting the row.\n */\nexport const accessTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n /** Null for tokens issued before family tracking was introduced. */\n family_id: v.string().optional(),\n expires_at: v.date().required(),\n});\n\n/**\n * Persisted access-token record + the data layer for access tokens.\n *\n * **Role.** Owns access-token persistence and lookup. The middleware checks a\n * presented JWT against this table so deleting a row (logout) invalidates the\n * token immediately, before its JWT expiry. The auth service goes through the\n * named statics exclusively, so it never hard-codes a column name and an\n * override can rename/add columns by registering under\n * `config.auth.accessToken.model`.\n */\nexport class AccessToken extends Model {\n public static table = \"access_tokens\";\n\n public static schema = accessTokenSchema;\n\n /**\n * The raw signed JWT is a bearer credential — never serialize it. `hidden`\n * only strips it from `toJSON()` / `JSON.stringify(model)` (so\n * `response.json(token)` or a resource cannot leak it); `get(\"token\")`,\n * `findByToken` and every query still read the column.\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 `access_tokensTrash` on every `destroy()` (logout, expiry purge,\n * never-expiring purge). A revoked/expired access token must not survive\n * anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** The user this token was issued for. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The user-type slug this token was issued for. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /**\n * Whether the persisted expiry has passed.\n *\n * The middleware asks this on every request, which is what makes the row the\n * authority it always looked like it was: before 4.12.0 the gate only checked\n * that the row *existed*, so a row the database knew was dead still let its\n * token through — the database was never asked.\n *\n * **Fails closed.** A missing or unparseable `expires_at` counts as expired.\n * `expires_at` is `required` in the schema, so a row that cannot answer \"when\n * does this die\" is malformed, and the safe reading of a malformed credential\n * is that it is not one. This is deliberately stricter than a naive\n * `now > expires_at`, which answers `false` for an `Invalid Date` and thereby\n * grants exactly the poisoned rows an unlimited life.\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(expiresAt).getTime() <= Date.now();\n }\n\n /**\n * Whether nothing about this row can ever retire it — an unusable\n * `expires_at`, or a token carrying no `exp` claim. See\n * {@link isNeverExpiring}; this is the predicate `purgeNeverExpiring` selects\n * on.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /**\n * Persist a freshly-signed access token for the user.\n */\n public static issue(user: Auth, token: string, expiresAt: Date, familyId?: string) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: familyId,\n expires_at: expiresAt,\n });\n }\n\n /**\n * Find an access-token row by its raw token string.\n */\n public static findByToken(token: string): Promise<AccessToken | null> {\n return this.first({ token });\n }\n\n /**\n * Delete a specific token that belongs to the given user.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.delete({ token, user_id: user.id });\n }\n\n /**\n * Delete every access token belonging to the user.\n */\n public static deleteAllForUser(user: Auth) {\n return this.delete({ user_id: user.id });\n }\n\n /**\n * Delete every access token attached to one family, plus pre-family rows for\n * the same user type. The latter is deliberately conservative during the\n * additive upgrade: old access rows cannot be assigned safely to a family.\n */\n public static async deleteFamilyAndLegacyForUser(user: Auth, familyId: string): Promise<void> {\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: familyId });\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: null });\n }\n\n /**\n * Hard-delete every expired access-token row. Returns the number removed.\n * Runs from the `auth.cleanup` CLI command (a cold batch path).\n */\n public static async purgeExpired(): Promise<number> {\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.length;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}.\n *\n * **A full scan, filtered in memory, on purpose.** The defining case is a row\n * whose `expires_at` is an `Invalid Date`, which no date predicate can select\n * (`< now` and `> now` are both `false` for it), and the definitive case is a\n * token with no `exp` claim, which lives inside the token string rather than\n * in a column. Neither is expressible as a `where`, so the rows have to be\n * read to be judged. This runs from a one-off remediation command, not a\n * request path.\n */\n public static async findNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: AccessToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed so the\n * caller can report what it revoked. Deletion *is* revocation for access\n * tokens — the middleware rejects a token with no row.\n */\n public static async purgeNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens)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AC;CACzC;;;;;;CAOA,aAAoB,6BAA6B,MAAY,UAAiC;EAC5F,MAAM,KAAK,OAAO;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,WAAW;EAAS,CAAC;EACrF,MAAM,KAAK,OAAO;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,WAAW;EAAK,CAAC;CACnF;;;;;CAMA,aAAoB,eAAgC;EAClD,MAAM,gBAAgB,MAAM,KAAK,MAAM,CAAC,CAAC,MAAM,cAAc,qBAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI;EAElF,KAAK,MAAM,SAAS,eAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO,cAAc;CACvB;;;;;;;;;;;;CAaA,aAAoB,oBAA4C;EAG9D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAuB,MAAM,YAAY;CACjE;;;;;;CAOA,aAAoB,qBAA6C;EAC/D,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"access-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,oBAAoB,EAAE,OAAO;CACxC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;;CAE/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;AAChC,CAAC;;;;;;;;;;;AAYD,IAAa,cAAb,cAAiC,MAAM;;eACf;;;gBAEC;;;gBAYA,CAAC,OAAO;;;wBASA;;;CAG/B,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WA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AK,MAAM,CAAC,CAAC,MAAM,cAAc,qBAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI;EAElF,KAAK,MAAM,SAAS,eAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO,cAAc;CACvB;;;;;;;;;;;;CAaA,aAAoB,oBAA4C;EAG9D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAuB,MAAM,YAAY;CACjE;;;;;;CAOA,aAAoB,qBAA6C;EAC/D,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"family-association.migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/family-association.migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { AccessToken } from \"./access-token.model\";\n\n/** Adds an optional family association without invalidating existing access tokens. */\nexport const AccessTokenFamilyAssociationMigration = migrate(AccessToken, {\n name: \"accessTokenFamilyAssociation\",\n up() {\n this.string(\"family_id\", 64).nullable().index();\n },\n down() {\n this.dropColumn(\"family_id\");\n },\n});\n"],"mappings":";;;;;AAIA,MAAa,wCAAwC,QAAQ,aAAa;CACxE,MAAM;CACN,KAAK;EACH,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM;CAChD;CACA,OAAO;EACL,KAAK,WAAW,WAAW;CAC7B;AACF,CAAC"}
1
+ {"version":3,"file":"family-association.migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/family-association.migration.ts"],"mappings":";;;;;AAIA,MAAa,wCAAwC,QAAQ,aAAa;CACxE,MAAM;CACN,KAAK;EACH,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM;CAChD;CACA,OAAO;EACL,KAAK,WAAW,WAAW;CAC7B;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { AccessToken } from \"./access-token.model\";\n\nexport const AccessTokenMigration = migrate(AccessToken, {\n name: \"accessToken\",\n up() {\n // Create table\n this.createTableIfNotExists();\n\n // Primary key\n this.primaryUuid();\n\n // Token field\n this.text(\"token\").unique();\n\n // User reference (flat columns for cross-driver compatibility).\n // `foreignId` matches the DataSource's default primary-key type, so the\n // column stays compatible with the user model's `id` whether the app uses\n // integer (the default) or uuid PKs — hardcoding uuid here 500'd every\n // login on a default integer-PK app (finding 5e47bdb3).\n this.foreignId(\"user_id\").index();\n this.string(\"user_type\", 50).nullable();\n\n // Expiry — enables server-side cleanup of stale access-token rows\n this.timestamp(\"expires_at\").index().nullable();\n\n // Timestamps\n this.timestamps();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n"],"mappings":";;;;AAGA,MAAa,uBAAuB,QAAQ,aAAa;CACvD,MAAM;CACN,KAAK;EAEH,KAAK,uBAAuB;EAG5B,KAAK,YAAY;EAGjB,KAAK,KAAK,OAAO,CAAC,CAAC,OAAO;EAO1B,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EAGtC,KAAK,UAAU,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EAG9C,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
1
+ {"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/migration.ts"],"mappings":";;;;AAGA,MAAa,uBAAuB,QAAQ,aAAa;CACvD,MAAM;CACN,KAAK;EAEH,KAAK,uBAAuB;EAG5B,KAAK,YAAY;EAGjB,KAAK,KAAK,OAAO,CAAC,CAAC,OAAO;EAO1B,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EAGtC,KAAK,UAAU,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EAG9C,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
@@ -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"],"mappings":";;;;;AAKA,MAAa,wBAAwB,EAAE,OAAO;CAC5C,WAAW,EAAE,OAAO,CAAC,CAAC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,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":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { AuthTokenFamily } from \"./auth-token-family.model\";\n\n/** Creates the durable authority shared by every token in a refresh family. */\nexport const AuthTokenFamilyMigration = migrate(AuthTokenFamily, {\n name: \"authTokenFamily\",\n up() {\n this.createTableIfNotExists();\n this.primaryUuid();\n this.string(\"family_id\", 64).unique();\n this.foreignId(\"user_id\").index();\n this.string(\"user_type\", 50).nullable();\n this.integer(\"revision\").default(0);\n this.timestamp(\"revoked_at\").nullable();\n this.timestamps();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n"],"mappings":";;;;;AAIA,MAAa,2BAA2B,QAAQ,iBAAiB;CAC/D,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAC5B,KAAK,YAAY;EACjB,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,OAAO;EACpC,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EACtC,KAAK,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC;EAClC,KAAK,UAAU,YAAY,CAAC,CAAC,SAAS;EACtC,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
1
+ {"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/migration.ts"],"mappings":";;;;;AAIA,MAAa,2BAA2B,QAAQ,iBAAiB;CAC/D,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAC5B,KAAK,YAAY;EACjB,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,OAAO;EACpC,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EACtC,KAAK,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC;EAClC,KAAK,UAAU,YAAY,CAAC,CAAC,SAAS;EACtC,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
@@ -4,6 +4,14 @@ import { Authenticable } from "../contracts/auth-contract.mjs";
4
4
  import { ChildModel, Model, ModelSchema } from "@warlock.js/cascade";
5
5
  //#region ../../packages/auth/src/models/auth.model.d.ts
6
6
  export declare abstract class Auth<out Schema extends ModelSchema = ModelSchema> extends Model<Schema> implements Authenticable {
7
+ /**
8
+ * The password hash never leaves the server through serialization:
9
+ * `toJSON()` (so `response.json(user)`), lean query rows and embedded
10
+ * copies all drop it, while `user.get("password")` / `user.string("password")`
11
+ * still read it for verification. A subclass that sets its own `hidden`
12
+ * replaces this list, so keep `"password"` in it.
13
+ */
14
+ static hidden: string[];
7
15
  /**
8
16
  * Get user type
9
17
  */
@@ -1 +1 @@
1
- {"version":3,"file":"auth.model.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/models/auth.model.ts"],"mappings":";;;;;8BAQsB,SAAS,eAAe,cAAc,qBAClD,MAAM,mBACH;;;;eAKS;;;;EAKb,sBAAkB;;;;EAOZ,gBAAgB,aAAa,aAAa,QAAQ;;;;EAOlD,oBAAoB,aAAa,QAAQ;;;;EAOzC,qBAAqB,aAAa,aAAa,QAAQ;;;;EAOvD,kBAAkB,gBAAgB;;;;EAOlC,mBAAmB,gBAAgB;;;;EAOnC,yBAAyB;;;;EAOzB,mBAAmB;;;;EAOnB,kBAAkB,QAAQ;;;;SAOnB,QAAQ,MAAM,WAAW,OAAO,YAAY,QAAQ;;;;EAO3D,gBAAgB,mBAAmB"}
1
+ {"version":3,"file":"auth.model.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/models/auth.model.ts"],"mappings":";;;;;8BAQsB,SAAS,eAAe,cAAc,qBAClD,MAAM,mBACH;;;;;;;;SASG;;;;eAKM;;;;EAKb,sBAAkB;;;;EAOZ,gBAAgB,aAAa,aAAa,QAAQ;;;;EAOlD,oBAAoB,aAAa,QAAQ;;;;EAOzC,qBAAqB,aAAa,aAAa,QAAQ;;;;EAOvD,kBAAkB,gBAAgB;;;;EAOlC,mBAAmB,gBAAgB;;;;EAOnC,yBAAyB;;;;EAOzB,mBAAmB;;;;EAOnB,kBAAkB,QAAQ;;;;SAOnB,QAAQ,MAAM,WAAW,OAAO,YAAY,QAAQ;;;;EAO3D,gBAAgB,mBAAmB"}