@warlock.js/auth 5.25.0 → 5.27.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 (34) hide show
  1. package/CHANGELOG.md +25 -9
  2. package/esm/contracts/index.d.mts +1 -1
  3. package/esm/contracts/request-locals.d.mts +1 -1
  4. package/esm/contracts/types.d.mts +8 -3
  5. package/esm/contracts/types.d.mts.map +1 -1
  6. package/esm/contracts/types.mjs.map +1 -1
  7. package/esm/index.d.mts +4 -4
  8. package/esm/index.mjs +3 -3
  9. package/esm/middleware/auth.middleware.d.mts +19 -1
  10. package/esm/middleware/auth.middleware.d.mts.map +1 -1
  11. package/esm/middleware/auth.middleware.mjs +19 -1
  12. package/esm/middleware/auth.middleware.mjs.map +1 -1
  13. package/esm/middleware/index.d.mts +1 -1
  14. package/esm/middleware/index.mjs +1 -1
  15. package/esm/services/auth-config.mjs +3 -1
  16. package/esm/services/auth-config.mjs.map +1 -1
  17. package/esm/services/auth.service.d.mts +9 -4
  18. package/esm/services/auth.service.d.mts.map +1 -1
  19. package/esm/services/auth.service.mjs +35 -8
  20. package/esm/services/auth.service.mjs.map +1 -1
  21. package/esm/services/index.d.mts +1 -1
  22. package/esm/services/index.mjs +1 -1
  23. package/esm/services/resolve-request-user.d.mts +3 -2
  24. package/esm/services/resolve-request-user.d.mts.map +1 -1
  25. package/esm/services/resolve-request-user.mjs +8 -2
  26. package/esm/services/resolve-request-user.mjs.map +1 -1
  27. package/esm/session/page-session.d.mts +3 -1
  28. package/esm/session/page-session.d.mts.map +1 -1
  29. package/esm/session/page-session.mjs +2 -1
  30. package/esm/session/page-session.mjs.map +1 -1
  31. package/llms-full.txt +43 -20
  32. package/package.json +8 -8
  33. package/skills/handle-login-and-logout/SKILL.md +36 -21
  34. package/skills/protect-routes/SKILL.md +4 -0
@@ -1 +1 @@
1
- {"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport { type Algorithm } from \"fast-jwt\";\nimport ms from \"ms\";\nimport type {\n AuthNotification,\n CanAuthenticate,\n LogoutWithoutTokenBehavior,\n OneTimeTokenUrlBuilder,\n PasswordSetter,\n} from \"../contracts/types\";\nimport type {\n AppleProviderConfig,\n AuthProvider,\n DiscordProviderConfig,\n FacebookProviderConfig,\n GitHubProviderConfig,\n GoogleProviderConfig,\n LinkedInProviderConfig,\n OtpSender,\n PasskeysConfig,\n ProviderUserCreator,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport type { Auth } from \"../models/auth.model\";\n\nconst warnedLegacyKeys = new Set<string>();\n\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\n\n/**\n * `ms` accepts anything at runtime and answers `undefined` for a string it\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\n * `(value: ms.StringValue) => number`, which is exactly what let an\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\n * here, so every caller is forced to deal with the `undefined`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * Turn a configured lifetime into a positive number of milliseconds, or throw\n * naming the key.\n *\n * A token lifetime is a security boundary, so an unusable value is a hard error\n * rather than a silent fallback: substituting a default would trade one\n * unintended lifetime for another, just as quietly — and quiet is the whole\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\n *\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\n * claim** and an `Invalid Date` written to the token row.\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\n * emits with **no `exp` claim** — it survives any guard that only rejects\n * `undefined`. `\"-1h\"` signs an already-expired token.\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\n */\nfunction parseDuration(key: string, raw: unknown): number {\n let parsed: number | string | undefined;\n\n try {\n parsed = parseMs(raw);\n } catch {\n // ms throws (rather than returning undefined) for \"\" and non-strings\n parsed = undefined;\n }\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\n );\n }\n\n return parsed;\n}\n\n/** Email-verification token lifetime used when nothing is configured. */\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\n\n/** Password-reset token lifetime used when nothing is configured. */\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\n\n/** Passkey challenge lifetime used when nothing is configured. */\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\n\n/** OTP lifetime used when nothing is configured. */\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\n\n/** Access-token lifetime used when nothing is configured. */\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\n\n/**\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\n *\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\n * keep working after the config split.\n */\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\n const fromNew = config.key(`auth.${newKey}`);\n\n if (fromNew !== undefined && fromNew !== null) {\n return fromNew as T;\n }\n\n const fromLegacy = config.key(`auth.${legacyKey}`);\n\n if (fromLegacy !== undefined && fromLegacy !== null) {\n if (!warnedLegacyKeys.has(legacyKey)) {\n warnedLegacyKeys.add(legacyKey);\n log.warn(\n \"auth\",\n \"config-deprecation\",\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\n );\n }\n\n return fromLegacy as T;\n }\n\n return fallback as T;\n}\n\n/**\n * Typed, backward-compatible access to auth configuration. The service and the\n * jwt signer read configuration exclusively through here, so the new split\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\n */\nexport const authConfig = {\n canAuthenticate: async (user: Auth): Promise<boolean> => {\n const canAuthenticate = config.key<CanAuthenticate>(\n \"auth.canAuthenticate\",\n permitAuthentication,\n );\n\n return canAuthenticate(user);\n },\n accessToken: {\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\n secret: (): string => {\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\n\n if (!secret) {\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\n }\n\n return secret;\n },\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\n * to 1 hour when unset; throws naming the key when the configured value is\n * not a positive `ms` duration. See {@link parseDuration}.\n */\n expiresInMs: (): number =>\n parseDuration(\n \"accessToken.expiresIn\",\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\n ),\n },\n pageAuth: {\n /**\n * Login path a guarded PAGE route redirects a logged-out browser to.\n *\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\n * to opt a browser-facing app into login-redirect UX: a logged-out human\n * navigating to a guarded page lands on the login screen instead of reading\n * a raw JSON error blob. Finding b9ab9804.\n */\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\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. Defaults to\n * `\"returnUrl\"`.\n */\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\n },\n cookie: {\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\n },\n csrf: {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * beyond the request's own origin. @default []\n */\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\n },\n verification: {\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\n expiresInMs: (): number =>\n parseDuration(\n \"verification.expiresIn\",\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\n ),\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\n /** App notification replacing the default verification email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\n },\n passwordReset: {\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\n expiresInMs: (): number =>\n parseDuration(\n \"passwordReset.expiresIn\",\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\n ),\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\n /** App notification replacing the default reset email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\n /** App-owned password writer replacing the default. */\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\n },\n providers: {\n /** `auth.providers.google`, when configured. */\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\n /** `auth.providers.github`, when configured. */\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\n /** `auth.providers.discord`, when configured. */\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\n /** `auth.providers.linkedin`, when configured. */\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\n /** `auth.providers.apple`, when configured. */\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\n /** `auth.providers.facebook`, when configured. */\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\n /** `auth.providers.x`, when configured. */\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\n /** An app-registered provider under `auth.providers.custom.<name>`. */\n custom: (name: string): AuthProvider | undefined => {\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\n\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\n },\n /** User attribute a verified provider email is matched against. @default \"email\" */\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\n /** App-owned user creation for a first provider login. */\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\n },\n passkeys: {\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\n settings: (): PasskeysConfig => {\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\n\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\n throw new Error(\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\n );\n }\n\n return settings;\n },\n /** Allowed ceremony origins, as a list. */\n origins: (): string[] => {\n const { origin } = authConfig.passkeys.settings();\n\n return Array.isArray(origin) ? origin : [origin];\n },\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n challengeExpiresInMs: (): number =>\n parseDuration(\n \"passkeys.challengeExpiresIn\",\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\n ),\n },\n otp: {\n /** Notifications channel the code is sent through. @default \"sms\" */\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\n /** User attribute holding the phone number. @default \"phone\" */\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n expiresInMs: (): number =>\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\n /** Verify attempts before the code is invalidated. @default 5 */\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\n /** The message text for a code. */\n message: (code: string): string => {\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\n\n return build ? build(code) : `Your verification code is ${code}`;\n },\n /** App-owned delivery replacing the notifications channel send. */\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\n },\n refreshToken: {\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\n secret: (): string | undefined => resolve(\"refreshToken.secret\", \"jwt.refresh.secret\"),\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\n * naming the key when the configured value is not a positive `ms` duration.\n */\n expiresInMs: (): number =>\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\n },\n};\n"],"mappings":";;;;;AA0BA,MAAM,mCAAmB,IAAI,IAAY;AAEzC,MAAM,6BAAuD;;;;;;;;;;AAW7D,MAAM,UAAU;;;;;;;;;;;;;;;;;;AAmBhB,SAAS,cAAc,KAAa,KAAsB;CACxD,IAAI;CAEJ,IAAI;EACF,SAAS,QAAQ,GAAG;CACtB,QAAQ;EAEN,SAAS;CACX;CAEA,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,QAAQ,IAAI,IAAI,KAAK,UAAU,GAAG,EAAE,mGAEtC;CAGF,OAAO;AACT;;AAGA,MAAM,kCAAkC;;AAGxC,MAAM,oCAAoC;;AAG1C,MAAM,uCAAuC;;AAG7C,MAAM,yBAAyB;;AAG/B,MAAM,kCAAkC;;;;;;;;;AAUxC,SAAS,QAAW,QAAgB,WAAmB,UAAiB;CACtE,MAAM,UAAU,OAAO,IAAI,QAAQ,QAAQ;CAE3C,IAAI,YAAY,UAAa,YAAY,MACvC,OAAO;CAGT,MAAM,aAAa,OAAO,IAAI,QAAQ,WAAW;CAEjD,IAAI,eAAe,UAAa,eAAe,MAAM;EACnD,IAAI,CAAC,iBAAiB,IAAI,SAAS,GAAG;GACpC,iBAAiB,IAAI,SAAS;GAC9B,IAAI,KACF,QACA,sBACA,QAAQ,UAAU,4BAA4B,QAChD;EACF;EA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AuB,IAAI;;EAEnF,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
1
+ {"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport { type Algorithm } from \"fast-jwt\";\nimport ms from \"ms\";\nimport type {\n AuthNotification,\n CanAuthenticate,\n LogoutWithoutTokenBehavior,\n OneTimeTokenUrlBuilder,\n PasswordSetter,\n} from \"../contracts/types\";\nimport type {\n AppleProviderConfig,\n AuthProvider,\n DiscordProviderConfig,\n FacebookProviderConfig,\n GitHubProviderConfig,\n GoogleProviderConfig,\n LinkedInProviderConfig,\n OtpSender,\n PasskeysConfig,\n ProviderUserCreator,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport type { Auth } from \"../models/auth.model\";\n\nconst warnedLegacyKeys = new Set<string>();\n\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\n\n/**\n * `ms` accepts anything at runtime and answers `undefined` for a string it\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\n * `(value: ms.StringValue) => number`, which is exactly what let an\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\n * here, so every caller is forced to deal with the `undefined`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * Turn a configured lifetime into a positive number of milliseconds, or throw\n * naming the key.\n *\n * A token lifetime is a security boundary, so an unusable value is a hard error\n * rather than a silent fallback: substituting a default would trade one\n * unintended lifetime for another, just as quietly — and quiet is the whole\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\n *\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\n * claim** and an `Invalid Date` written to the token row.\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\n * emits with **no `exp` claim** — it survives any guard that only rejects\n * `undefined`. `\"-1h\"` signs an already-expired token.\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\n */\nfunction parseDuration(key: string, raw: unknown): number {\n let parsed: number | string | undefined;\n\n try {\n parsed = parseMs(raw);\n } catch {\n // ms throws (rather than returning undefined) for \"\" and non-strings\n parsed = undefined;\n }\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\n );\n }\n\n return parsed;\n}\n\n/** Email-verification token lifetime used when nothing is configured. */\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\n\n/** Password-reset token lifetime used when nothing is configured. */\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\n\n/** Passkey challenge lifetime used when nothing is configured. */\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\n\n/** OTP lifetime used when nothing is configured. */\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\n\n/** Access-token lifetime used when nothing is configured. */\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\n\n/**\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\n *\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\n * keep working after the config split.\n */\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\n const fromNew = config.key(`auth.${newKey}`);\n\n if (fromNew !== undefined && fromNew !== null) {\n return fromNew as T;\n }\n\n const fromLegacy = config.key(`auth.${legacyKey}`);\n\n if (fromLegacy !== undefined && fromLegacy !== null) {\n if (!warnedLegacyKeys.has(legacyKey)) {\n warnedLegacyKeys.add(legacyKey);\n log.warn(\n \"auth\",\n \"config-deprecation\",\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\n );\n }\n\n return fromLegacy as T;\n }\n\n return fallback as T;\n}\n\n/**\n * Typed, backward-compatible access to auth configuration. The service and the\n * jwt signer read configuration exclusively through here, so the new split\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\n */\nexport const authConfig = {\n canAuthenticate: async (user: Auth): Promise<boolean> => {\n const canAuthenticate = config.key<CanAuthenticate>(\n \"auth.canAuthenticate\",\n permitAuthentication,\n );\n\n return canAuthenticate(user);\n },\n accessToken: {\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\n secret: (): string => {\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\n\n if (!secret) {\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\n }\n\n return secret;\n },\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\n * to 1 hour when unset; throws naming the key when the configured value is\n * not a positive `ms` duration. See {@link parseDuration}.\n */\n expiresInMs: (): number =>\n parseDuration(\n \"accessToken.expiresIn\",\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\n ),\n },\n pageAuth: {\n /**\n * Login path a guarded PAGE route redirects a logged-out browser to.\n *\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\n * to opt a browser-facing app into login-redirect UX: a logged-out human\n * navigating to a guarded page lands on the login screen instead of reading\n * a raw JSON error blob. Finding b9ab9804.\n */\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\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. Defaults to\n * `\"returnUrl\"`.\n */\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\n },\n cookie: {\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\n /** Select the request-scoped cookie Domain; undefined keeps it host-only. */\n cookieDomain: (): CookieDomainResolver | undefined => config.key(\"auth.cookie.cookieDomain\"),\n },\n csrf: {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * beyond the request's own origin. @default []\n */\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\n },\n verification: {\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\n expiresInMs: (): number =>\n parseDuration(\n \"verification.expiresIn\",\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\n ),\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\n /** App notification replacing the default verification email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\n },\n passwordReset: {\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\n expiresInMs: (): number =>\n parseDuration(\n \"passwordReset.expiresIn\",\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\n ),\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\n /** App notification replacing the default reset email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\n /** App-owned password writer replacing the default. */\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\n },\n providers: {\n /** `auth.providers.google`, when configured. */\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\n /** `auth.providers.github`, when configured. */\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\n /** `auth.providers.discord`, when configured. */\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\n /** `auth.providers.linkedin`, when configured. */\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\n /** `auth.providers.apple`, when configured. */\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\n /** `auth.providers.facebook`, when configured. */\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\n /** `auth.providers.x`, when configured. */\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\n /** An app-registered provider under `auth.providers.custom.<name>`. */\n custom: (name: string): AuthProvider | undefined => {\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\n\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\n },\n /** User attribute a verified provider email is matched against. @default \"email\" */\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\n /** App-owned user creation for a first provider login. */\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\n },\n passkeys: {\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\n settings: (): PasskeysConfig => {\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\n\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\n throw new Error(\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\n );\n }\n\n return settings;\n },\n /** Allowed ceremony origins, as a list. */\n origins: (): string[] => {\n const { origin } = authConfig.passkeys.settings();\n\n return Array.isArray(origin) ? origin : [origin];\n },\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n challengeExpiresInMs: (): number =>\n parseDuration(\n \"passkeys.challengeExpiresIn\",\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\n ),\n },\n otp: {\n /** Notifications channel the code is sent through. @default \"sms\" */\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\n /** User attribute holding the phone number. @default \"phone\" */\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n expiresInMs: (): number =>\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\n /** Verify attempts before the code is invalidated. @default 5 */\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\n /** The message text for a code. */\n message: (code: string): string => {\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\n\n return build ? build(code) : `Your verification code is ${code}`;\n },\n /** App-owned delivery replacing the notifications channel send. */\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\n },\n refreshToken: {\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\n secret: (): string | undefined => resolve(\"refreshToken.secret\", \"jwt.refresh.secret\"),\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\n * naming the key when the configured value is not a positive `ms` duration.\n */\n expiresInMs: (): number =>\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\n },\n};\n"],"mappings":";;;;;AA2BA,MAAM,mCAAmB,IAAI,IAAY;AAEzC,MAAM,6BAAuD;;;;;;;;;;AAW7D,MAAM,UAAU;;;;;;;;;;;;;;;;;;AAmBhB,SAAS,cAAc,KAAa,KAAsB;CACxD,IAAI;CAEJ,IAAI;EACF,SAAS,QAAQ,GAAG;CACtB,QAAQ;EAEN,SAAS;CACX;CAEA,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,QAAQ,IAAI,IAAI,KAAK,UAAU,GAAG,EAAE,mGAEtC;CAGF,OAAO;AAC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;EAEA,4BACE,cACE,+BACA,OAAO,IAAI,oCAAoC,oCAAoC,CACrF;CACJ;CACA,KAAK;;EAEH,eAAuB,OAAO,IAAI,oBAAoB,KAAK;;EAE3D,kBAA0B,OAAO,IAAI,uBAAuB,OAAO;;EAEnE,mBACE,cAAc,iBAAiB,OAAO,IAAI,sBAAsB,sBAAsB,CAAC;;EAEzF,mBAA2B,OAAO,IAAI,wBAAwB,CAAC;;EAE/D,UAAU,SAAyB;GACjC,MAAM,QAAQ,OAAO,IAA4C,kBAAkB;GAEnF,OAAO,QAAQ,MAAM,IAAI,IAAI,6BAA6B;EAC5D;;EAEA,YAAmC,OAAO,IAAI,eAAe;CAC/D;CACA,cAAc;;EAEZ,cAAkC,QAAQ,uBAAuB,oBAAoB;;EAErF,eAAwB,QAAQ,wBAAwB,uBAAuB,IAAI;;EAEnF,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
@@ -6,6 +6,10 @@ import { Request, Response } from "@warlock.js/core";
6
6
  import { ChildModel } from "@warlock.js/cascade";
7
7
 
8
8
  //#region ../auth/src/services/auth.service.d.ts
9
+ /** Thrown when a request-scoped cookie Domain cannot be resolved safely. */
10
+ declare class CookieDomainRequestRequiredError extends Error {
11
+ constructor(method: string);
12
+ }
9
13
  declare class AuthService {
10
14
  /**
11
15
  * Resolve the active access-token model — the package default, or a subclass
@@ -195,6 +199,7 @@ declare class AuthService {
195
199
  * string (a session cookie) or an unparseable `expiresAt`.
196
200
  */
197
201
  private cookieMaxAgeFromToken;
202
+ private cookieDomainFor;
198
203
  /**
199
204
  * Write the auth cookie on `response` — the write side of the `cookie:<name>`
200
205
  * token source `authMiddleware([], "cookie:<name>")` already reads. An explicit
@@ -227,7 +232,7 @@ declare class AuthService {
227
232
  * await authService.logout(user, accessToken, refreshToken);
228
233
  * authService.clearAuthCookie(response);
229
234
  */
230
- clearAuthCookie(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }, options?: ClearAuthCookieOptions): void;
235
+ clearAuthCookie(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }, options?: ClearAuthCookieOptions, request?: Request): void;
231
236
  /**
232
237
  * Write the access and refresh cookies of a browser session. Both are
233
238
  * `HttpOnly`, `SameSite=Lax`, `Path=/` (the refresh cookie must reach every
@@ -242,14 +247,14 @@ declare class AuthService {
242
247
  setSessionCookies(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }, tokens: {
243
248
  accessToken: AccessTokenOutput;
244
249
  refreshToken: AccessTokenOutput;
245
- }): void;
250
+ }, request?: Request): void;
246
251
  /**
247
252
  * Clear both session cookies {@link setSessionCookies} wrote, on `Path=/`.
248
253
  * Pair it with {@link logout} after the token rows are revoked.
249
254
  */
250
- clearSessionCookies(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }): void;
255
+ clearSessionCookies(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }, request?: Request): void;
251
256
  }
252
257
  declare const authService: AuthService;
253
258
  //#endregion
254
- export { authService };
259
+ export { CookieDomainRequestRequiredError, authService };
255
260
  //# sourceMappingURL=auth.service.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.d.mts","names":[],"sources":["../../../../../../../auth/src/services/auth.service.ts"],"mappings":";;;;;;;;cAmCM,WAAA;;;;AAViD;;;cAiBzC,gBAAA;EAqBgC;;;EAAA,YAdhC,iBAAA;EA6DA;;;EAAA,YAtDA,iBAAA;EAyIG;;;EAlIR,uBAAA,CAAwB,IAAA,EAAM,IAAA,GAAO,MAAA;EAsMU;EA7LzC,eAAA,C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,GAAU,OAAA;EAhS0B;;;;EA0T/B,mBAAA,CACL,QAAA,yCAAiD,IAAA,EAAM,UAAA,CAAW,QAAA,CAAS,CAAA,kBAC3E,OAAA,GAAU,OAAA;AAAA;AAAA,cAcD,WAAA,EAAW,WAAoB"}
@@ -16,6 +16,13 @@ import { ForbiddenError, config, hashPassword, verifyPassword } from "@warlock.j
16
16
  import { randomUUID } from "node:crypto";
17
17
 
18
18
  //#region ../auth/src/services/auth.service.ts
19
+ /** Thrown when a request-scoped cookie Domain cannot be resolved safely. */
20
+ var CookieDomainRequestRequiredError = class extends Error {
21
+ constructor(method) {
22
+ super(`${method} requires the request when auth.cookie.cookieDomain is configured because the cookie Domain must be resolved for that request.`);
23
+ this.name = "CookieDomainRequestRequiredError";
24
+ }
25
+ };
19
26
  var AuthService = class {
20
27
  /**
21
28
  * Resolve the active access-token model — the package default, or a subclass
@@ -387,8 +394,8 @@ var AuthService = class {
387
394
  if (result.tokens.refreshToken) this.setSessionCookies(response, {
388
395
  accessToken: result.tokens.accessToken,
389
396
  refreshToken: result.tokens.refreshToken
390
- });
391
- else this.setAuthCookie(response, result.tokens.accessToken);
397
+ }, request);
398
+ else this.setAuthCookie(response, result.tokens.accessToken, { domain: this.cookieDomainFor("loginWithSessionCookies", request) });
392
399
  return result;
393
400
  }
394
401
  /** The one token-issuing tail every login method shares. */
@@ -569,6 +576,12 @@ var AuthService = class {
569
576
  if (Number.isNaN(expiresAt)) return void 0;
570
577
  return Math.max(0, Math.round((expiresAt - Date.now()) / 1e3));
571
578
  }
579
+ cookieDomainFor(method, request) {
580
+ const resolver = authConfig.cookie.cookieDomain();
581
+ if (!resolver) return;
582
+ if (!request) throw new CookieDomainRequestRequiredError(method);
583
+ return resolver(request);
584
+ }
572
585
  /**
573
586
  * Write the auth cookie on `response` — the write side of the `cookie:<name>`
574
587
  * token source `authMiddleware([], "cookie:<name>")` already reads. An explicit
@@ -598,6 +611,7 @@ var AuthService = class {
598
611
  response.cookie(name, tokenValue, {
599
612
  raw: true,
600
613
  path,
614
+ ...options.domain !== void 0 ? { domain: options.domain } : {},
601
615
  ...maxAge !== void 0 ? { maxAge } : {}
602
616
  });
603
617
  }
@@ -611,9 +625,14 @@ var AuthService = class {
611
625
  * await authService.logout(user, accessToken, refreshToken);
612
626
  * authService.clearAuthCookie(response);
613
627
  */
614
- clearAuthCookie(response, options = {}) {
628
+ clearAuthCookie(response, options = {}, request) {
615
629
  const name = options.name ?? authConfig.cookie.name();
616
630
  const path = options.path ?? authConfig.cookie.path();
631
+ const domain = this.cookieDomainFor("clearAuthCookie", request);
632
+ if (domain !== void 0) response.clearCookie(name, {
633
+ path,
634
+ domain
635
+ });
617
636
  response.clearCookie(name, { path });
618
637
  }
619
638
  /**
@@ -627,7 +646,8 @@ var AuthService = class {
627
646
  * const { tokens } = await authService.login(User, credentials);
628
647
  * authService.setSessionCookies(response, tokens);
629
648
  */
630
- setSessionCookies(response, tokens) {
649
+ setSessionCookies(response, tokens, request) {
650
+ const domain = this.cookieDomainFor("setSessionCookies", request);
631
651
  const cookies = [[authConfig.cookie.name(), tokens.accessToken], [authConfig.cookie.refreshName(), tokens.refreshToken]];
632
652
  for (const [name, token] of cookies) {
633
653
  const maxAge = this.cookieMaxAgeFromToken(token);
@@ -636,6 +656,7 @@ var AuthService = class {
636
656
  httpOnly: true,
637
657
  sameSite: "lax",
638
658
  path: "/",
659
+ ...domain !== void 0 ? { domain } : {},
639
660
  ...maxAge !== void 0 ? { maxAge } : {}
640
661
  });
641
662
  }
@@ -644,13 +665,19 @@ var AuthService = class {
644
665
  * Clear both session cookies {@link setSessionCookies} wrote, on `Path=/`.
645
666
  * Pair it with {@link logout} after the token rows are revoked.
646
667
  */
647
- clearSessionCookies(response) {
648
- response.clearCookie(authConfig.cookie.name(), { path: "/" });
649
- response.clearCookie(authConfig.cookie.refreshName(), { path: "/" });
668
+ clearSessionCookies(response, request) {
669
+ const domain = this.cookieDomainFor("clearSessionCookies", request);
670
+ for (const name of [authConfig.cookie.name(), authConfig.cookie.refreshName()]) {
671
+ if (domain !== void 0) response.clearCookie(name, {
672
+ path: "/",
673
+ domain
674
+ });
675
+ response.clearCookie(name, { path: "/" });
676
+ }
650
677
  }
651
678
  };
652
679
  const authService = new AuthService();
653
680
 
654
681
  //#endregion
655
- export { authService };
682
+ export { CookieDomainRequestRequiredError, authService };
656
683
  //# sourceMappingURL=auth.service.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth.service.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\nimport { randomUUID } from \"node:crypto\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport {\n config,\n ForbiddenError,\n hashPassword,\n type Request,\n type Response,\n verifyPassword,\n} from \"@warlock.js/core\";\nimport type {\n AccessTokenOutput,\n AuthCredentials,\n ClearAuthCookieOptions,\n DeviceInfo,\n LoginResult,\n SetAuthCookieOptions,\n TokenPair,\n} from \"../contracts/types\";\nimport { assertCsrfOriginAllowed } from \"../middleware/csrf-origin-check\";\nimport { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport { AuthTokenFamily } from \"../models/auth-token-family\";\nimport { OneTimeToken } from \"../models/one-time-token\";\nimport { RefreshToken } from \"../models/refresh-token\";\nimport { authConfig } from \"./auth-config\";\nimport { authEvents } from \"./auth-events\";\nimport { isInvalidCredentialError, jwt } from \"./jwt\";\nimport {\n afterTokenFamilyOperation,\n runTokenFamilyOperation,\n TokenFamilyUnavailableError,\n} from \"./token-family-operation\";\n\nclass AuthService {\n /**\n * Resolve the active access-token model — the package default, or a subclass\n * an app registered under `config.auth.accessToken.model` (e.g. to add a\n * tenant column). The service never references the concrete class directly so\n * an override is a pure config change.\n */\n private get accessTokenModel(): typeof AccessToken {\n return config.key(\"auth.accessToken.model\", AccessToken);\n }\n\n /**\n * Resolve the active refresh-token model (default or registered override).\n */\n private get refreshTokenModel(): typeof RefreshToken {\n return config.key(\"auth.refreshToken.model\", RefreshToken);\n }\n\n /**\n * Resolve the active one-time-token model (default or registered override).\n */\n private get oneTimeTokenModel(): typeof OneTimeToken {\n return config.key(\"auth.oneTimeToken.model\", OneTimeToken);\n }\n\n /**\n * Build the default access-token JWT payload from a user.\n */\n public buildAccessTokenPayload(user: Auth): Record<string, unknown> {\n return {\n id: user.id,\n userType: user.userType,\n created_at: Date.now(),\n };\n }\n\n /** One policy seam keeps account-state checks identical across all auth paths. */\n public async canAuthenticate(user: Auth): Promise<boolean> {\n return authConfig.canAuthenticate(user);\n }\n\n private async assertCanAuthenticate(user: Auth): Promise<void> {\n if (!(await this.canAuthenticate(user))) {\n throw new ForbiddenError(\"This user cannot authenticate.\");\n }\n }\n\n private async issueAccessToken(\n user: Auth,\n payload?: Record<string, unknown>,\n familyId?: string,\n ): Promise<AccessTokenOutput> {\n const data = { ...(payload || this.buildAccessTokenPayload(user)), jti: randomUUID() };\n // Validate before signing so an unusable lifetime cannot mint an immortal token.\n const expiresIn = authConfig.accessToken.expiresInMs();\n\n const token = await jwt.generate(data, { expiresIn });\n const expiresAt = new Date(Date.now() + expiresIn);\n\n if (familyId) {\n await this.accessTokenModel.issue(user, token, expiresAt, familyId);\n } else {\n await this.accessTokenModel.issue(user, token, expiresAt);\n }\n\n return { token, expiresAt: expiresAt.toISOString() };\n }\n\n /**\n * Sign + persist an access token for the user and return the token with its\n * expiry. The expiry is computed locally from `expiresIn` rather than by\n * re-verifying the token we just signed.\n */\n public async generateAccessToken(\n user: Auth,\n payload?: Record<string, unknown>,\n ): Promise<AccessTokenOutput> {\n await this.assertCanAuthenticate(user);\n\n return this.issueAccessToken(user, payload);\n }\n\n private async issueRefreshToken(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ensuredFamily?: AuthTokenFamily,\n ): Promise<RefreshToken | undefined> {\n if (!authConfig.refreshToken.enabled()) return;\n\n // Validate the lifetime first — before the per-user cap is enforced, before\n // anything is signed — so a bad value can never revoke a user's oldest\n // session on its way to failing.\n const expiresIn = authConfig.refreshToken.expiresInMs();\n\n const familyId = deviceInfo?.familyId || Random.string(32);\n\n const family = ensuredFamily ?? (await AuthTokenFamily.ensure(user, familyId));\n\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n const payload = {\n userId: user.id,\n userType: user.userType,\n familyId,\n jti: randomUUID(),\n };\n\n const expiresAt = new Date(Date.now() + expiresIn).toISOString();\n\n await this.refreshTokenModel.enforceMax(user, authConfig.refreshToken.maxPerUser());\n\n const token = await jwt.generateRefreshToken(payload, { expiresIn });\n\n return this.refreshTokenModel.issue(user, token, { familyId, expiresAt, deviceInfo });\n }\n\n /**\n * Keep issuance into an explicitly reused family in the same durable\n * transition boundary as rotation and revocation. A new, caller-unspecified\n * family has no concurrent session to protect and retains the lightweight\n * issuance path.\n */\n private async issueInSuppliedFamily<T>(\n user: Auth,\n familyId: string,\n issue: (family: AuthTokenFamily) => Promise<T>,\n ): Promise<T> {\n // Preserve the established error for a family that was already revoked\n // before issuance started. The coordinator covers a revoke that races\n // after this observation.\n const family = await AuthTokenFamily.ensure(user, familyId);\n\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n try {\n return await runTokenFamilyOperation(familyId, issue);\n } catch (error) {\n // Do not expose a timing-dependent error shape to callers: a family\n // revoked between ensure() and the transaction is the same unusable\n // family condition as one found above.\n if (error instanceof TokenFamilyUnavailableError) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n throw error;\n }\n }\n\n /**\n * Sign + persist a refresh token for the user (enforcing the per-user cap\n * first). Resolves to `undefined` when refresh tokens are disabled in config.\n */\n public async createRefreshToken(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ): Promise<RefreshToken | undefined> {\n if (!authConfig.refreshToken.enabled()) return;\n\n await this.assertCanAuthenticate(user);\n\n if (deviceInfo?.familyId) {\n return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) =>\n this.issueRefreshToken(user, deviceInfo, family),\n );\n }\n\n return this.issueRefreshToken(user, deviceInfo);\n }\n\n private async issueTokenPair(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ensuredFamily?: AuthTokenFamily,\n ): Promise<TokenPair> {\n const refreshEnabled = authConfig.refreshToken.enabled();\n const familyId = deviceInfo?.familyId || Random.string(32);\n\n const family = refreshEnabled\n ? (ensuredFamily ?? (await AuthTokenFamily.ensure(user, familyId)))\n : undefined;\n\n if (family) {\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n }\n\n const accessToken = await this.issueAccessToken(\n user,\n deviceInfo?.payload,\n refreshEnabled ? familyId : undefined,\n );\n const refreshToken = await this.issueRefreshToken(\n user,\n refreshEnabled ? { ...deviceInfo, familyId } : deviceInfo,\n family,\n );\n\n const tokenPair: TokenPair = {\n accessToken,\n refreshToken: refreshToken\n ? {\n token: refreshToken.get(\"token\"),\n expiresAt: refreshToken.get(\"expires_at\"),\n }\n : undefined,\n };\n\n afterTokenFamilyOperation(() => authEvents.emit(\"token.created\", user, tokenPair));\n\n if (refreshToken) {\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"session.created\", user, refreshToken, deviceInfo),\n );\n }\n\n return tokenPair;\n }\n\n /**\n * Issue both an access and a refresh token, emitting the creation events.\n */\n public async createTokenPair(user: Auth, deviceInfo?: DeviceInfo): Promise<TokenPair> {\n await this.assertCanAuthenticate(user);\n\n if (authConfig.refreshToken.enabled() && deviceInfo?.familyId) {\n return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) =>\n this.issueTokenPair(user, deviceInfo, family),\n );\n }\n\n return this.issueTokenPair(user, deviceInfo);\n }\n\n /**\n * Exchange a refresh token for a new token pair, with rotation + replay\n * detection. A concurrent reuse of the same token loses the atomic revoke and\n * is treated as a breach — the whole family is revoked and the request fails.\n */\n public async refreshTokens(\n refreshTokenString: string,\n deviceInfo?: DeviceInfo,\n ): Promise<TokenPair | null> {\n let decoded: {\n userId: number;\n userType: string;\n familyId: string;\n } | null;\n\n try {\n decoded = await jwt.verifyRefreshToken<{\n userId: number;\n userType: string;\n familyId: string;\n }>(refreshTokenString);\n } catch (error) {\n if (isInvalidCredentialError(error)) return null;\n\n throw error;\n }\n\n if (!decoded) return null;\n\n const presentedToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n\n if (!presentedToken || !this.refreshIdentityMatches(presentedToken, decoded)) return null;\n\n await AuthTokenFamily.ensure(\n { id: decoded.userId, userType: decoded.userType } as Auth,\n presentedToken.familyId,\n );\n return runTokenFamilyOperation(presentedToken.familyId, async () => {\n // Each serializable attempt must read the current row in its own snapshot.\n const refreshToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!refreshToken || !this.refreshIdentityMatches(refreshToken, decoded)) return null;\n if (!refreshToken.isValid) {\n // An already-invalid token may be a replay of a rotated credential.\n if (refreshToken) {\n await this.revokeTokenFamily(refreshToken.familyId);\n }\n\n return null;\n }\n\n const UserModel = config.key(`auth.userType.${decoded.userType}`);\n\n if (!UserModel) {\n throw new Error(`User type ${decoded.userType} is unknown type.`);\n }\n\n const user = (await UserModel.find(decoded.userId)) as Auth | null;\n\n if (!user) return null;\n\n if (!(await this.canAuthenticate(user))) return null;\n\n const rotationEnabled = authConfig.refreshToken.rotation();\n\n if (rotationEnabled) {\n const won = await refreshToken.revokeIfActive();\n\n if (!won) {\n // A concurrent request already rotated this token.\n await this.revokeTokenFamily(refreshToken.familyId);\n\n return null;\n }\n } else {\n await refreshToken.markAsUsed();\n }\n\n const newTokenPair = await this.issueTokenPair(user, {\n ...deviceInfo,\n familyId: refreshToken.familyId,\n });\n\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.refreshed\", user, newTokenPair, refreshToken),\n );\n\n return newTokenPair;\n }).catch((error) => {\n if (error instanceof TokenFamilyUnavailableError) return null;\n throw error;\n });\n }\n\n /**\n * Opt-in browser-session renewal. Unlike {@link refreshTokens}, this permits\n * a short duplicate presentation to receive the exact committed successor\n * pair. It is deliberately not used by the legacy/public refresh API.\n */\n public async renewAutomaticSession(\n refreshTokenString: string,\n expectedUserType: string,\n options: { overlapMs?: number; deviceInfo?: DeviceInfo; maxAgeMs?: number } = {},\n ): Promise<TokenPair | null> {\n let decoded: { userId: number; userType: string; familyId: string } | null;\n try {\n decoded = await jwt.verifyRefreshToken<{\n userId: number;\n userType: string;\n familyId: string;\n }>(refreshTokenString);\n } catch (error) {\n if (isInvalidCredentialError(error)) return null;\n throw error;\n }\n\n if (!decoded || decoded.userType !== expectedUserType) return null;\n const presentedToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!presentedToken || !this.refreshIdentityMatches(presentedToken, decoded)) return null;\n\n await AuthTokenFamily.ensure(\n { id: decoded.userId, userType: decoded.userType } as Auth,\n presentedToken.familyId,\n );\n return runTokenFamilyOperation(presentedToken.familyId, async () => {\n // A retry can follow another process's committed rotation. Never reuse\n // a model captured before the transaction or before a failed attempt.\n const oldToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!oldToken || !this.refreshIdentityMatches(oldToken, decoded)) return null;\n if (!oldToken.isValid) {\n const successor = await this.readAutomaticSuccessor(oldToken, decoded, options.overlapMs);\n if (successor) return successor;\n if (\n this.isAutomaticOverlapOpen(oldToken, options.overlapMs) &&\n this.hasSuccessor(oldToken)\n ) {\n return null;\n }\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n // Rotation never extends a family past `maxAgeMs` from its first issue.\n if (\n options.maxAgeMs !== undefined &&\n (await this.familyExceedsMaxAge(oldToken.familyId, options.maxAgeMs))\n ) {\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n const UserModel = config.key(`auth.userType.${decoded.userType}`);\n if (!UserModel) throw new Error(`User type ${decoded.userType} is unknown type.`);\n const user = (await UserModel.find(decoded.userId)) as Auth | null;\n if (!user || !(await this.canAuthenticate(user))) return null;\n\n if (!(await oldToken.revokeIfActive())) {\n // A newer successor is never substituted here. A stale automatic\n // response must fail quietly rather than revoke a legitimate family.\n const currentToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!currentToken) return null;\n const successor = await this.readAutomaticSuccessor(\n currentToken,\n decoded,\n options.overlapMs,\n );\n if (successor) return successor;\n if (\n this.isAutomaticOverlapOpen(currentToken, options.overlapMs) &&\n this.hasSuccessor(currentToken)\n )\n return null;\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n const pair = await this.issueTokenPair(user, {\n ...options.deviceInfo,\n familyId: oldToken.familyId,\n });\n const successorAccess = await this.accessTokenModel.findByToken(pair.accessToken.token);\n const successorRefresh = pair.refreshToken\n ? await this.refreshTokenModel.findByToken(pair.refreshToken.token)\n : null;\n if (!successorAccess || !successorRefresh) {\n throw new Error(\"Automatic renewal did not persist a complete successor pair\");\n }\n\n // `revokeIfActive()` updates the database, not this hydrated instance.\n // Saving that stale instance would write its old `revoked_at: null` back\n // and reopen the predecessor. Update only the successor columns instead.\n const linked = await this.refreshTokenModel.atomic(\n { id: oldToken.id },\n {\n $set: {\n successor_access_token_id: successorAccess.id,\n successor_refresh_token_id: successorRefresh.id,\n },\n },\n );\n if (linked !== 1) throw new Error(\"Automatic renewal could not link its successor pair\");\n afterTokenFamilyOperation(() => authEvents.emit(\"token.refreshed\", user, pair, oldToken));\n return pair;\n }).catch((error) => {\n if (error instanceof TokenFamilyUnavailableError) return null;\n throw error;\n });\n }\n\n /**\n * Whether the family's first issue is older than `maxAgeMs`. The start is the\n * family row's `created_at`, falling back to its oldest refresh token when\n * the row carries none (an upserted legacy family).\n */\n private async familyExceedsMaxAge(familyId: string, maxAgeMs: number): Promise<boolean> {\n const family = await AuthTokenFamily.findByFamilyId(familyId);\n let started: unknown = family?.get(\"created_at\");\n\n if (!started) {\n const oldest = await this.refreshTokenModel\n .query()\n .where({ family_id: familyId })\n .orderBy(\"created_at\", \"asc\")\n .first();\n\n started = oldest?.get(\"created_at\");\n }\n\n const startedAt = started ? new Date(started as string | number | Date).getTime() : NaN;\n\n // Unknown start: nothing to measure against, so the cap cannot apply.\n if (!Number.isFinite(startedAt)) return false;\n\n return Date.now() - startedAt > maxAgeMs;\n }\n\n private automaticOverlapMs(overlapMs: number | undefined): number {\n return typeof overlapMs === \"number\" && Number.isFinite(overlapMs)\n ? Math.max(0, Math.min(10_000, overlapMs))\n : 5000;\n }\n\n private refreshIdentityMatches(\n token: RefreshToken,\n decoded: { userId: string | number; userType: string; familyId: string },\n ): boolean {\n return (\n token.familyId === decoded.familyId &&\n token.get(\"user_id\") === decoded.userId &&\n token.get(\"user_type\") === decoded.userType\n );\n }\n\n private hasSuccessor(oldToken: RefreshToken): boolean {\n return Boolean(\n oldToken.get(\"successor_access_token_id\") && oldToken.get(\"successor_refresh_token_id\"),\n );\n }\n\n private isAutomaticOverlapOpen(oldToken: RefreshToken, overlapMs: number | undefined): boolean {\n const revokedAt = oldToken.get<Date | undefined>(\"revoked_at\");\n const window = this.automaticOverlapMs(overlapMs);\n const elapsed = revokedAt ? Date.now() - new Date(revokedAt).getTime() : NaN;\n return window > 0 && elapsed >= 0 && elapsed <= window;\n }\n\n private async readAutomaticSuccessor(\n oldToken: RefreshToken,\n decoded: { userId: number; userType: string; familyId: string },\n overlapMs: number | undefined,\n ): Promise<TokenPair | null> {\n if (!this.isAutomaticOverlapOpen(oldToken, overlapMs)) return null;\n const accessId = oldToken.get<string | undefined>(\"successor_access_token_id\");\n const refreshId = oldToken.get<string | undefined>(\"successor_refresh_token_id\");\n if (!accessId || !refreshId) return null;\n const [access, refresh] = await Promise.all([\n this.accessTokenModel.find(accessId),\n this.refreshTokenModel.find(refreshId),\n ]);\n if (!access || access.isExpired || !refresh?.isValid) return null;\n if (\n access.get(\"family_id\") !== decoded.familyId ||\n refresh.get(\"family_id\") !== decoded.familyId ||\n access.get(\"user_id\") !== decoded.userId ||\n refresh.get(\"user_id\") !== decoded.userId ||\n access.get(\"user_type\") !== decoded.userType ||\n refresh.get(\"user_type\") !== decoded.userType\n )\n return null;\n const accessExpiry = new Date(access.get(\"expires_at\")).getTime();\n if (!Number.isFinite(accessExpiry) || accessExpiry <= Date.now()) return null;\n return {\n accessToken: { token: access.get(\"token\"), expiresAt: access.get(\"expires_at\") },\n refreshToken: { token: refresh.get(\"token\"), expiresAt: refresh.get(\"expires_at\") },\n };\n }\n\n /**\n * Verify a plaintext password against a stored hash.\n */\n public async verifyPassword(plainPassword: string, hashedPassword: string): Promise<boolean> {\n return verifyPassword(plainPassword, hashedPassword);\n }\n\n /**\n * Hash a plaintext password.\n */\n public async hashPassword(password: string): Promise<string> {\n return hashPassword(password);\n }\n\n /**\n * Resolve a user by credentials, verifying the password. Returns `null` on a\n * missing user or a wrong password, emitting `login.failed` either way.\n */\n public async attemptLogin<T extends Auth>(\n Model: ChildModel<T>,\n data: AuthCredentials,\n ): Promise<T | null> {\n const { password, ...otherData } = data;\n\n authEvents.emit(\"login.attempt\", otherData);\n\n const user = (await Model.first(otherData)) as T | null;\n\n if (!user) {\n authEvents.emit(\"login.failed\", otherData, \"User not found\");\n\n return null;\n }\n\n if (!(await this.verifyPassword(password, user.string(\"password\")!))) {\n authEvents.emit(\"login.failed\", otherData, \"Invalid password\");\n\n return null;\n }\n\n if (!(await this.canAuthenticate(user))) {\n authEvents.emit(\"login.failed\", otherData, \"Authentication not allowed\");\n\n return null;\n }\n\n return user;\n }\n\n /**\n * Full login flow: validate credentials, issue tokens, emit events. Returns\n * the user + token pair on success, `null` on failure.\n */\n public async login<T extends Auth>(\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T> | null> {\n const user = await this.attemptLogin(Model, credentials);\n\n if (!user) {\n return null;\n }\n\n return this.finalizeLogin(user, deviceInfo);\n }\n\n /**\n * Log in a user some OTHER method already authenticated — a provider\n * callback, a passkey assertion, a one-time code. Applies the\n * `auth.canAuthenticate` policy (403 on refusal), then produces exactly\n * what {@link login} produces: the same tokens, rows and events. Pair with\n * {@link setAuthCookie} for a cookie session, as with password login.\n *\n * Never call this for a user you have not authenticated.\n */\n public async completeLogin<T extends Auth>(\n user: T,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T>> {\n await this.assertCanAuthenticate(user);\n\n return this.finalizeLogin(user, deviceInfo);\n }\n\n /**\n * Cookie login for a browser: same-origin check, credential login, then both\n * session cookies. Unlike the default CSRF guard, the Origin/Referer check\n * runs even when the request carries no cookies (login CSRF): a missing or\n * cross-site Origin/Referer throws `CsrfOriginMismatchError` before any\n * credential is looked at. Returns `null` on bad credentials.\n */\n public async loginWithSessionCookies<T extends Auth>(\n request: Request,\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T> | null> {\n assertCsrfOriginAllowed(request);\n\n const result = await this.login(Model, credentials, deviceInfo);\n\n if (!result) return null;\n\n if (result.tokens.refreshToken) {\n this.setSessionCookies(response, {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n });\n } else {\n this.setAuthCookie(response, result.tokens.accessToken);\n }\n\n return result;\n }\n\n /** The one token-issuing tail every login method shares. */\n private async finalizeLogin<T extends Auth>(\n user: T,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T>> {\n if (!authConfig.refreshToken.enabled()) {\n const accessToken = await this.issueAccessToken(user, deviceInfo?.payload);\n\n return { user, tokens: { accessToken } };\n }\n\n const tokens = await this.issueTokenPair(user, deviceInfo);\n\n authEvents.emit(\"login.success\", user, tokens, deviceInfo);\n\n return { user, tokens };\n }\n\n /**\n * Log a user out.\n *\n * @param accessToken - access token string to revoke (optional)\n * @param refreshToken - refresh token string to revoke (optional)\n *\n * When no refresh token is supplied, `config.auth.refreshToken.logoutWithoutToken`\n * decides the behavior: `\"revoke-all\"` (default, fail-safe) revokes every\n * refresh token; `\"error\"` requires the caller to pass one.\n */\n public async logout(user: Auth, accessToken?: string, refreshToken?: string): Promise<void> {\n if (accessToken) {\n await this.removeAccessToken(user, accessToken);\n }\n\n if (refreshToken) {\n const token = await this.refreshTokenModel.findForUser(user, refreshToken);\n\n if (token) {\n await this.revokeTokenFamily(token.familyId);\n authEvents.emit(\"session.destroyed\", user, token);\n }\n } else {\n const behavior = authConfig.refreshToken.logoutWithoutToken();\n\n if (behavior === \"error\") {\n throw new Error(\"Refresh token required for logout\");\n }\n\n await this.revokeAllTokens(user);\n authEvents.emit(\"logout.failsafe\", user);\n }\n\n authEvents.emit(\"logout\", user);\n }\n\n /**\n * Remove a specific access token belonging to the user.\n */\n public async removeAccessToken(user: Auth, token: string): Promise<void> {\n await this.accessTokenModel.deleteForUser(user, token);\n }\n\n /**\n * Remove every access token belonging to the user.\n */\n public async removeAllAccessTokens(user: Auth): Promise<void> {\n await this.accessTokenModel.deleteAllForUser(user);\n }\n\n /**\n * Remove a specific refresh token belonging to the user.\n */\n public async removeRefreshToken(user: Auth, token: string): Promise<void> {\n await this.refreshTokenModel.deleteForUser(user, token);\n }\n\n /**\n * Revoke every active refresh token for the user and delete their access\n * tokens — \"log out of all devices\". Each durable family is first marked through its revision coordinator; an\n * event fires per revoked token.\n */\n public async revokeAllTokens(user: Auth): Promise<void> {\n // Upgrade existing installations lazily before the family scan. Include\n // revoked rows: a rotation may have revoked its predecessor while its\n // durable family still needs logout's marker.\n const existingRows = await this.refreshTokenModel.familiesForUser(user);\n\n for (const token of existingRows) {\n await AuthTokenFamily.ensure(user, token.familyId);\n }\n\n const families = await AuthTokenFamily.activeFor(user);\n\n for (const family of families) {\n await this.revokeTokenFamily(family.get<string>(\"family_id\"));\n }\n\n // A deployment can still have rows created before the additive migration\n // ran; retain the old bulk cleanup as a final conservative backstop.\n const legacyTokens = await this.refreshTokenModel.revokeAllFor(user);\n\n for (const token of legacyTokens) {\n authEvents.emit(\"token.revoked\", user, token);\n }\n await this.removeAllAccessTokens(user);\n\n authEvents.emit(\"logout.all\", user);\n }\n\n /**\n * Revoke an entire token family — rotation breach containment.\n */\n public async revokeTokenFamily(familyId: string): Promise<void> {\n let family = await AuthTokenFamily.findByFamilyId(familyId);\n\n if (!family) {\n const legacyToken = await this.refreshTokenModel.findInFamily(familyId);\n\n if (!legacyToken) return;\n\n family = await AuthTokenFamily.ensure(\n {\n id: legacyToken.get(\"user_id\"),\n userType: legacyToken.get<string>(\"user_type\"),\n } as Auth,\n familyId,\n );\n }\n\n const user = {\n id: family.get(\"user_id\"),\n userType: family.get<string>(\"user_type\"),\n } as Auth;\n\n if (family.isRevoked) {\n // Logout and replay containment are idempotent. Re-run cleanup because a\n // request that lost the original race may have observed stale rows.\n const revokedTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(user, familyId);\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.familyRevoked\", familyId, revokedTokens),\n );\n\n return;\n }\n\n let revokedTokens: RefreshToken[];\n try {\n revokedTokens = await runTokenFamilyOperation(familyId, async (currentFamily) => {\n const familyUser = {\n id: currentFamily.get(\"user_id\"),\n userType: currentFamily.get<string>(\"user_type\"),\n } as Auth;\n const revision = currentFamily.get<number>(\"revision\");\n const revoked = await AuthTokenFamily.revoke(familyId, revision);\n\n if (revoked !== 1) {\n throw new Error(\"Token family revoke lost its revision transition\");\n }\n\n const familyTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(familyUser, familyId);\n\n return familyTokens;\n });\n } catch (error) {\n if (!(error instanceof TokenFamilyUnavailableError)) throw error;\n\n // Another request committed the revoke between the read above and its\n // CAS. A second logout is successful after idempotent cleanup.\n revokedTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(user, familyId);\n }\n\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.familyRevoked\", familyId, revokedTokens),\n );\n }\n\n /**\n * Delete expired tokens (refresh + access) and spent one-time tokens\n * (expired or consumed verification/reset/OTP/passkey rows). Emits `token.expired` per refresh\n * token and `cleanup.completed` with the refresh count. Drives the\n * `auth.cleanup` CLI command.\n */\n public async cleanupExpiredTokens(): Promise<number> {\n const expiredTokens = await this.refreshTokenModel.purgeExpired();\n\n for (const token of expiredTokens) {\n authEvents.emit(\"token.expired\", token);\n }\n\n await this.accessTokenModel.purgeExpired();\n await this.oneTimeTokenModel.purgeSpent();\n\n authEvents.emit(\"cleanup.completed\", expiredTokens.length);\n\n return expiredTokens.length;\n }\n\n /**\n * Find every persisted token — access and refresh — that can never retire\n * itself: an unusable `expires_at`, or a token carrying no `exp` claim.\n *\n * This is the remediation read for the pre-4.12.0 `expiresIn` defect (#25).\n * Nothing else surfaces these rows: `auth.cleanup` selects `expires_at < now`,\n * which an `Invalid Date` never satisfies, and a row whose date column is\n * perfectly fine can still hold a token with no deadline in it. Read-only —\n * pair with {@link purgeNeverExpiringTokens} to act on the answer.\n */\n public async findNeverExpiringTokens(): Promise<{\n accessTokens: AccessToken[];\n refreshTokens: RefreshToken[];\n }> {\n return {\n accessTokens: await this.accessTokenModel.findNeverExpiring(),\n refreshTokens: await this.refreshTokenModel.findNeverExpiring(),\n };\n }\n\n /**\n * Revoke every never-expiring token by deleting its row, emitting\n * `token.revoked` per refresh token. Drives `warlock auth.purge-never-expiring`.\n *\n * Access tokens first: deleting one is immediate revocation, while a refresh\n * token left in place for a moment can only mint an access token through a\n * verifier that now rejects it for the missing `exp`.\n */\n public async purgeNeverExpiringTokens(): Promise<{\n accessTokens: number;\n refreshTokens: number;\n }> {\n const accessTokens = await this.accessTokenModel.purgeNeverExpiring();\n const refreshTokens = await this.refreshTokenModel.purgeNeverExpiring();\n\n // `token.expired` (the event `auth.cleanup` already emits for a removed\n // refresh token) rather than `token.revoked`, which carries a loaded `Auth`\n // this batch path has no reason to fetch a user row for.\n for (const token of refreshTokens) {\n authEvents.emit(\"token.expired\", token);\n }\n\n return { accessTokens: accessTokens.length, refreshTokens: refreshTokens.length };\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public async getActiveSessions(user: Auth): Promise<RefreshToken[]> {\n return this.refreshTokenModel.activeFor(user);\n }\n\n /**\n * `Max-Age` (seconds) `setAuthCookie` should apply, derived from an\n * `AccessTokenOutput`'s `expiresAt` — or `undefined` for a bare token\n * string (a session cookie) or an unparseable `expiresAt`.\n */\n private cookieMaxAgeFromToken(token: string | AccessTokenOutput): number | undefined {\n if (typeof token === \"string\") return undefined;\n\n const expiresAt = new Date(token.expiresAt).getTime();\n\n if (Number.isNaN(expiresAt)) return undefined;\n\n return Math.max(0, Math.round((expiresAt - Date.now()) / 1000));\n }\n\n /**\n * Write the auth cookie on `response` — the write side of the `cookie:<name>`\n * token source `authMiddleware([], \"cookie:<name>\")` already reads. An explicit\n * app-controller call, never a side effect of {@link login}, so an existing\n * bearer-only app never starts emitting `Set-Cookie` just by upgrading.\n *\n * Attribute flags (`HttpOnly`, `SameSite=Lax`, `Secure` outside dev) come\n * from `response.cookie()`'s own `secureCookieDefaults()` floor — this\n * method never overrides them, only `name`/`path`/`maxAge`. `raw: true`\n * writes the token unquoted, so the same string a `cookie:<name>` source\n * reads back is exactly what was issued, not a JSON-wrapped copy.\n *\n * @param token - the token string, or an `AccessTokenOutput` (e.g. from\n * {@link login}) whose `expiresAt` sets `Max-Age` automatically when\n * `options.maxAge` is not given. A bare string with no `options.maxAge`\n * produces a session cookie.\n *\n * @example\n * const { user, tokens } = await authService.login(User, credentials);\n * authService.setAuthCookie(response, tokens.accessToken);\n */\n public setAuthCookie(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n token: string | AccessTokenOutput,\n options: SetAuthCookieOptions = {},\n ): void {\n const name = options.name ?? authConfig.cookie.name();\n const path = options.path ?? authConfig.cookie.path();\n const tokenValue = typeof token === \"string\" ? token : token.token;\n const maxAge = options.maxAge ?? this.cookieMaxAgeFromToken(token);\n\n response.cookie(name, tokenValue, {\n raw: true,\n path,\n ...(maxAge !== undefined ? { maxAge } : {}),\n });\n }\n\n /**\n * Clear the auth cookie {@link setAuthCookie} wrote. An explicit\n * app-controller call — pair it with {@link logout} after the token row is\n * revoked. `path` must match what the cookie was set with, or the browser\n * silently ignores the clear (see `response.clearCookie`'s own doc comment).\n *\n * @example\n * await authService.logout(user, accessToken, refreshToken);\n * authService.clearAuthCookie(response);\n */\n public clearAuthCookie(response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown }, options: ClearAuthCookieOptions = {}): void {\n const name = options.name ?? authConfig.cookie.name();\n const path = options.path ?? authConfig.cookie.path();\n\n response.clearCookie(name, { path });\n }\n\n /**\n * Write the access and refresh cookies of a browser session. Both are\n * `HttpOnly`, `SameSite=Lax`, `Path=/` (the refresh cookie must reach every\n * page) and `Secure` outside development, named by `auth.cookie.name` and\n * `auth.cookie.refreshName`. Each `Max-Age` is derived from its token's\n * `expiresAt`, so the cookie lives exactly as long as the token.\n *\n * @example\n * const { tokens } = await authService.login(User, credentials);\n * authService.setSessionCookies(response, tokens);\n */\n public setSessionCookies(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n tokens: { accessToken: AccessTokenOutput; refreshToken: AccessTokenOutput },\n ): void {\n const cookies = [\n [authConfig.cookie.name(), tokens.accessToken],\n [authConfig.cookie.refreshName(), tokens.refreshToken],\n ] as const;\n\n for (const [name, token] of cookies) {\n const maxAge = this.cookieMaxAgeFromToken(token);\n\n response.cookie(name, token.token, {\n raw: true,\n httpOnly: true,\n sameSite: \"lax\",\n path: \"/\",\n ...(maxAge !== undefined ? { maxAge } : {}),\n });\n }\n }\n\n /**\n * Clear both session cookies {@link setSessionCookies} wrote, on `Path=/`.\n * Pair it with {@link logout} after the token rows are revoked.\n */\n public clearSessionCookies(response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown }): void {\n response.clearCookie(authConfig.cookie.name(), { path: \"/\" });\n response.clearCookie(authConfig.cookie.refreshName(), { path: \"/\" });\n }\n}\n\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;GAC3C,CAAC;EACH;CACF;;;;;CAMA,AAAO,oBAAoB,UAAoG;EAC7H,SAAS,YAAY,WAAW,OAAO,KAAK,GAAG,EAAE,MAAM,IAAI,CAAC;EAC5D,SAAS,YAAY,WAAW,OAAO,YAAY,GAAG,EAAE,MAAM,IAAI,CAAC;CACrE;AACF;AAEA,MAAa,cAAc,IAAI,YAAY"}
1
+ {"version":3,"file":"auth.service.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth.service.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\nimport { randomUUID } from \"node:crypto\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport {\n config,\n ForbiddenError,\n hashPassword,\n type Request,\n type Response,\n verifyPassword,\n} from \"@warlock.js/core\";\nimport type {\n AccessTokenOutput,\n AuthCredentials,\n ClearAuthCookieOptions,\n DeviceInfo,\n LoginResult,\n SetAuthCookieOptions,\n TokenPair,\n} from \"../contracts/types\";\nimport { assertCsrfOriginAllowed } from \"../middleware/csrf-origin-check\";\nimport { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport { AuthTokenFamily } from \"../models/auth-token-family\";\nimport { OneTimeToken } from \"../models/one-time-token\";\nimport { RefreshToken } from \"../models/refresh-token\";\nimport { authConfig } from \"./auth-config\";\nimport { authEvents } from \"./auth-events\";\nimport { isInvalidCredentialError, jwt } from \"./jwt\";\nimport {\n afterTokenFamilyOperation,\n runTokenFamilyOperation,\n TokenFamilyUnavailableError,\n} from \"./token-family-operation\";\n\n/** Thrown when a request-scoped cookie Domain cannot be resolved safely. */\nexport class CookieDomainRequestRequiredError extends Error {\n public constructor(method: string) {\n super(\n `${method} requires the request when auth.cookie.cookieDomain is configured because the cookie Domain must be resolved for that request.`,\n );\n this.name = \"CookieDomainRequestRequiredError\";\n }\n}\n\nclass AuthService {\n /**\n * Resolve the active access-token model — the package default, or a subclass\n * an app registered under `config.auth.accessToken.model` (e.g. to add a\n * tenant column). The service never references the concrete class directly so\n * an override is a pure config change.\n */\n private get accessTokenModel(): typeof AccessToken {\n return config.key(\"auth.accessToken.model\", AccessToken);\n }\n\n /**\n * Resolve the active refresh-token model (default or registered override).\n */\n private get refreshTokenModel(): typeof RefreshToken {\n return config.key(\"auth.refreshToken.model\", RefreshToken);\n }\n\n /**\n * Resolve the active one-time-token model (default or registered override).\n */\n private get oneTimeTokenModel(): typeof OneTimeToken {\n return config.key(\"auth.oneTimeToken.model\", OneTimeToken);\n }\n\n /**\n * Build the default access-token JWT payload from a user.\n */\n public buildAccessTokenPayload(user: Auth): Record<string, unknown> {\n return {\n id: user.id,\n userType: user.userType,\n created_at: Date.now(),\n };\n }\n\n /** One policy seam keeps account-state checks identical across all auth paths. */\n public async canAuthenticate(user: Auth): Promise<boolean> {\n return authConfig.canAuthenticate(user);\n }\n\n private async assertCanAuthenticate(user: Auth): Promise<void> {\n if (!(await this.canAuthenticate(user))) {\n throw new ForbiddenError(\"This user cannot authenticate.\");\n }\n }\n\n private async issueAccessToken(\n user: Auth,\n payload?: Record<string, unknown>,\n familyId?: string,\n ): Promise<AccessTokenOutput> {\n const data = { ...(payload || this.buildAccessTokenPayload(user)), jti: randomUUID() };\n // Validate before signing so an unusable lifetime cannot mint an immortal token.\n const expiresIn = authConfig.accessToken.expiresInMs();\n\n const token = await jwt.generate(data, { expiresIn });\n const expiresAt = new Date(Date.now() + expiresIn);\n\n if (familyId) {\n await this.accessTokenModel.issue(user, token, expiresAt, familyId);\n } else {\n await this.accessTokenModel.issue(user, token, expiresAt);\n }\n\n return { token, expiresAt: expiresAt.toISOString() };\n }\n\n /**\n * Sign + persist an access token for the user and return the token with its\n * expiry. The expiry is computed locally from `expiresIn` rather than by\n * re-verifying the token we just signed.\n */\n public async generateAccessToken(\n user: Auth,\n payload?: Record<string, unknown>,\n ): Promise<AccessTokenOutput> {\n await this.assertCanAuthenticate(user);\n\n return this.issueAccessToken(user, payload);\n }\n\n private async issueRefreshToken(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ensuredFamily?: AuthTokenFamily,\n ): Promise<RefreshToken | undefined> {\n if (!authConfig.refreshToken.enabled()) return;\n\n // Validate the lifetime first — before the per-user cap is enforced, before\n // anything is signed — so a bad value can never revoke a user's oldest\n // session on its way to failing.\n const expiresIn = authConfig.refreshToken.expiresInMs();\n\n const familyId = deviceInfo?.familyId || Random.string(32);\n\n const family = ensuredFamily ?? (await AuthTokenFamily.ensure(user, familyId));\n\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n const payload = {\n userId: user.id,\n userType: user.userType,\n familyId,\n jti: randomUUID(),\n };\n\n const expiresAt = new Date(Date.now() + expiresIn).toISOString();\n\n await this.refreshTokenModel.enforceMax(user, authConfig.refreshToken.maxPerUser());\n\n const token = await jwt.generateRefreshToken(payload, { expiresIn });\n\n return this.refreshTokenModel.issue(user, token, { familyId, expiresAt, deviceInfo });\n }\n\n /**\n * Keep issuance into an explicitly reused family in the same durable\n * transition boundary as rotation and revocation. A new, caller-unspecified\n * family has no concurrent session to protect and retains the lightweight\n * issuance path.\n */\n private async issueInSuppliedFamily<T>(\n user: Auth,\n familyId: string,\n issue: (family: AuthTokenFamily) => Promise<T>,\n ): Promise<T> {\n // Preserve the established error for a family that was already revoked\n // before issuance started. The coordinator covers a revoke that races\n // after this observation.\n const family = await AuthTokenFamily.ensure(user, familyId);\n\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n try {\n return await runTokenFamilyOperation(familyId, issue);\n } catch (error) {\n // Do not expose a timing-dependent error shape to callers: a family\n // revoked between ensure() and the transaction is the same unusable\n // family condition as one found above.\n if (error instanceof TokenFamilyUnavailableError) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n throw error;\n }\n }\n\n /**\n * Sign + persist a refresh token for the user (enforcing the per-user cap\n * first). Resolves to `undefined` when refresh tokens are disabled in config.\n */\n public async createRefreshToken(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ): Promise<RefreshToken | undefined> {\n if (!authConfig.refreshToken.enabled()) return;\n\n await this.assertCanAuthenticate(user);\n\n if (deviceInfo?.familyId) {\n return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) =>\n this.issueRefreshToken(user, deviceInfo, family),\n );\n }\n\n return this.issueRefreshToken(user, deviceInfo);\n }\n\n private async issueTokenPair(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ensuredFamily?: AuthTokenFamily,\n ): Promise<TokenPair> {\n const refreshEnabled = authConfig.refreshToken.enabled();\n const familyId = deviceInfo?.familyId || Random.string(32);\n\n const family = refreshEnabled\n ? (ensuredFamily ?? (await AuthTokenFamily.ensure(user, familyId)))\n : undefined;\n\n if (family) {\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n }\n\n const accessToken = await this.issueAccessToken(\n user,\n deviceInfo?.payload,\n refreshEnabled ? familyId : undefined,\n );\n const refreshToken = await this.issueRefreshToken(\n user,\n refreshEnabled ? { ...deviceInfo, familyId } : deviceInfo,\n family,\n );\n\n const tokenPair: TokenPair = {\n accessToken,\n refreshToken: refreshToken\n ? {\n token: refreshToken.get(\"token\"),\n expiresAt: refreshToken.get(\"expires_at\"),\n }\n : undefined,\n };\n\n afterTokenFamilyOperation(() => authEvents.emit(\"token.created\", user, tokenPair));\n\n if (refreshToken) {\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"session.created\", user, refreshToken, deviceInfo),\n );\n }\n\n return tokenPair;\n }\n\n /**\n * Issue both an access and a refresh token, emitting the creation events.\n */\n public async createTokenPair(user: Auth, deviceInfo?: DeviceInfo): Promise<TokenPair> {\n await this.assertCanAuthenticate(user);\n\n if (authConfig.refreshToken.enabled() && deviceInfo?.familyId) {\n return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) =>\n this.issueTokenPair(user, deviceInfo, family),\n );\n }\n\n return this.issueTokenPair(user, deviceInfo);\n }\n\n /**\n * Exchange a refresh token for a new token pair, with rotation + replay\n * detection. A concurrent reuse of the same token loses the atomic revoke and\n * is treated as a breach — the whole family is revoked and the request fails.\n */\n public async refreshTokens(\n refreshTokenString: string,\n deviceInfo?: DeviceInfo,\n ): Promise<TokenPair | null> {\n let decoded: {\n userId: number;\n userType: string;\n familyId: string;\n } | null;\n\n try {\n decoded = await jwt.verifyRefreshToken<{\n userId: number;\n userType: string;\n familyId: string;\n }>(refreshTokenString);\n } catch (error) {\n if (isInvalidCredentialError(error)) return null;\n\n throw error;\n }\n\n if (!decoded) return null;\n\n const presentedToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n\n if (!presentedToken || !this.refreshIdentityMatches(presentedToken, decoded)) return null;\n\n await AuthTokenFamily.ensure(\n { id: decoded.userId, userType: decoded.userType } as Auth,\n presentedToken.familyId,\n );\n return runTokenFamilyOperation(presentedToken.familyId, async () => {\n // Each serializable attempt must read the current row in its own snapshot.\n const refreshToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!refreshToken || !this.refreshIdentityMatches(refreshToken, decoded)) return null;\n if (!refreshToken.isValid) {\n // An already-invalid token may be a replay of a rotated credential.\n if (refreshToken) {\n await this.revokeTokenFamily(refreshToken.familyId);\n }\n\n return null;\n }\n\n const UserModel = config.key(`auth.userType.${decoded.userType}`);\n\n if (!UserModel) {\n throw new Error(`User type ${decoded.userType} is unknown type.`);\n }\n\n const user = (await UserModel.find(decoded.userId)) as Auth | null;\n\n if (!user) return null;\n\n if (!(await this.canAuthenticate(user))) return null;\n\n const rotationEnabled = authConfig.refreshToken.rotation();\n\n if (rotationEnabled) {\n const won = await refreshToken.revokeIfActive();\n\n if (!won) {\n // A concurrent request already rotated this token.\n await this.revokeTokenFamily(refreshToken.familyId);\n\n return null;\n }\n } else {\n await refreshToken.markAsUsed();\n }\n\n const newTokenPair = await this.issueTokenPair(user, {\n ...deviceInfo,\n familyId: refreshToken.familyId,\n });\n\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.refreshed\", user, newTokenPair, refreshToken),\n );\n\n return newTokenPair;\n }).catch((error) => {\n if (error instanceof TokenFamilyUnavailableError) return null;\n throw error;\n });\n }\n\n /**\n * Opt-in browser-session renewal. Unlike {@link refreshTokens}, this permits\n * a short duplicate presentation to receive the exact committed successor\n * pair. It is deliberately not used by the legacy/public refresh API.\n */\n public async renewAutomaticSession(\n refreshTokenString: string,\n expectedUserType: string,\n options: { overlapMs?: number; deviceInfo?: DeviceInfo; maxAgeMs?: number } = {},\n ): Promise<TokenPair | null> {\n let decoded: { userId: number; userType: string; familyId: string } | null;\n try {\n decoded = await jwt.verifyRefreshToken<{\n userId: number;\n userType: string;\n familyId: string;\n }>(refreshTokenString);\n } catch (error) {\n if (isInvalidCredentialError(error)) return null;\n throw error;\n }\n\n if (!decoded || decoded.userType !== expectedUserType) return null;\n const presentedToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!presentedToken || !this.refreshIdentityMatches(presentedToken, decoded)) return null;\n\n await AuthTokenFamily.ensure(\n { id: decoded.userId, userType: decoded.userType } as Auth,\n presentedToken.familyId,\n );\n return runTokenFamilyOperation(presentedToken.familyId, async () => {\n // A retry can follow another process's committed rotation. Never reuse\n // a model captured before the transaction or before a failed attempt.\n const oldToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!oldToken || !this.refreshIdentityMatches(oldToken, decoded)) return null;\n if (!oldToken.isValid) {\n const successor = await this.readAutomaticSuccessor(oldToken, decoded, options.overlapMs);\n if (successor) return successor;\n if (\n this.isAutomaticOverlapOpen(oldToken, options.overlapMs) &&\n this.hasSuccessor(oldToken)\n ) {\n return null;\n }\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n // Rotation never extends a family past `maxAgeMs` from its first issue.\n if (\n options.maxAgeMs !== undefined &&\n (await this.familyExceedsMaxAge(oldToken.familyId, options.maxAgeMs))\n ) {\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n const UserModel = config.key(`auth.userType.${decoded.userType}`);\n if (!UserModel) throw new Error(`User type ${decoded.userType} is unknown type.`);\n const user = (await UserModel.find(decoded.userId)) as Auth | null;\n if (!user || !(await this.canAuthenticate(user))) return null;\n\n if (!(await oldToken.revokeIfActive())) {\n // A newer successor is never substituted here. A stale automatic\n // response must fail quietly rather than revoke a legitimate family.\n const currentToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!currentToken) return null;\n const successor = await this.readAutomaticSuccessor(\n currentToken,\n decoded,\n options.overlapMs,\n );\n if (successor) return successor;\n if (\n this.isAutomaticOverlapOpen(currentToken, options.overlapMs) &&\n this.hasSuccessor(currentToken)\n )\n return null;\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n const pair = await this.issueTokenPair(user, {\n ...options.deviceInfo,\n familyId: oldToken.familyId,\n });\n const successorAccess = await this.accessTokenModel.findByToken(pair.accessToken.token);\n const successorRefresh = pair.refreshToken\n ? await this.refreshTokenModel.findByToken(pair.refreshToken.token)\n : null;\n if (!successorAccess || !successorRefresh) {\n throw new Error(\"Automatic renewal did not persist a complete successor pair\");\n }\n\n // `revokeIfActive()` updates the database, not this hydrated instance.\n // Saving that stale instance would write its old `revoked_at: null` back\n // and reopen the predecessor. Update only the successor columns instead.\n const linked = await this.refreshTokenModel.atomic(\n { id: oldToken.id },\n {\n $set: {\n successor_access_token_id: successorAccess.id,\n successor_refresh_token_id: successorRefresh.id,\n },\n },\n );\n if (linked !== 1) throw new Error(\"Automatic renewal could not link its successor pair\");\n afterTokenFamilyOperation(() => authEvents.emit(\"token.refreshed\", user, pair, oldToken));\n return pair;\n }).catch((error) => {\n if (error instanceof TokenFamilyUnavailableError) return null;\n throw error;\n });\n }\n\n /**\n * Whether the family's first issue is older than `maxAgeMs`. The start is the\n * family row's `created_at`, falling back to its oldest refresh token when\n * the row carries none (an upserted legacy family).\n */\n private async familyExceedsMaxAge(familyId: string, maxAgeMs: number): Promise<boolean> {\n const family = await AuthTokenFamily.findByFamilyId(familyId);\n let started: unknown = family?.get(\"created_at\");\n\n if (!started) {\n const oldest = await this.refreshTokenModel\n .query()\n .where({ family_id: familyId })\n .orderBy(\"created_at\", \"asc\")\n .first();\n\n started = oldest?.get(\"created_at\");\n }\n\n const startedAt = started ? new Date(started as string | number | Date).getTime() : NaN;\n\n // Unknown start: nothing to measure against, so the cap cannot apply.\n if (!Number.isFinite(startedAt)) return false;\n\n return Date.now() - startedAt > maxAgeMs;\n }\n\n private automaticOverlapMs(overlapMs: number | undefined): number {\n return typeof overlapMs === \"number\" && Number.isFinite(overlapMs)\n ? Math.max(0, Math.min(10_000, overlapMs))\n : 5000;\n }\n\n private refreshIdentityMatches(\n token: RefreshToken,\n decoded: { userId: string | number; userType: string; familyId: string },\n ): boolean {\n return (\n token.familyId === decoded.familyId &&\n token.get(\"user_id\") === decoded.userId &&\n token.get(\"user_type\") === decoded.userType\n );\n }\n\n private hasSuccessor(oldToken: RefreshToken): boolean {\n return Boolean(\n oldToken.get(\"successor_access_token_id\") && oldToken.get(\"successor_refresh_token_id\"),\n );\n }\n\n private isAutomaticOverlapOpen(oldToken: RefreshToken, overlapMs: number | undefined): boolean {\n const revokedAt = oldToken.get<Date | undefined>(\"revoked_at\");\n const window = this.automaticOverlapMs(overlapMs);\n const elapsed = revokedAt ? Date.now() - new Date(revokedAt).getTime() : NaN;\n return window > 0 && elapsed >= 0 && elapsed <= window;\n }\n\n private async readAutomaticSuccessor(\n oldToken: RefreshToken,\n decoded: { userId: number; userType: string; familyId: string },\n overlapMs: number | undefined,\n ): Promise<TokenPair | null> {\n if (!this.isAutomaticOverlapOpen(oldToken, overlapMs)) return null;\n const accessId = oldToken.get<string | undefined>(\"successor_access_token_id\");\n const refreshId = oldToken.get<string | undefined>(\"successor_refresh_token_id\");\n if (!accessId || !refreshId) return null;\n const [access, refresh] = await Promise.all([\n this.accessTokenModel.find(accessId),\n this.refreshTokenModel.find(refreshId),\n ]);\n if (!access || access.isExpired || !refresh?.isValid) return null;\n if (\n access.get(\"family_id\") !== decoded.familyId ||\n refresh.get(\"family_id\") !== decoded.familyId ||\n access.get(\"user_id\") !== decoded.userId ||\n refresh.get(\"user_id\") !== decoded.userId ||\n access.get(\"user_type\") !== decoded.userType ||\n refresh.get(\"user_type\") !== decoded.userType\n )\n return null;\n const accessExpiry = new Date(access.get(\"expires_at\")).getTime();\n if (!Number.isFinite(accessExpiry) || accessExpiry <= Date.now()) return null;\n return {\n accessToken: { token: access.get(\"token\"), expiresAt: access.get(\"expires_at\") },\n refreshToken: { token: refresh.get(\"token\"), expiresAt: refresh.get(\"expires_at\") },\n };\n }\n\n /**\n * Verify a plaintext password against a stored hash.\n */\n public async verifyPassword(plainPassword: string, hashedPassword: string): Promise<boolean> {\n return verifyPassword(plainPassword, hashedPassword);\n }\n\n /**\n * Hash a plaintext password.\n */\n public async hashPassword(password: string): Promise<string> {\n return hashPassword(password);\n }\n\n /**\n * Resolve a user by credentials, verifying the password. Returns `null` on a\n * missing user or a wrong password, emitting `login.failed` either way.\n */\n public async attemptLogin<T extends Auth>(\n Model: ChildModel<T>,\n data: AuthCredentials,\n ): Promise<T | null> {\n const { password, ...otherData } = data;\n\n authEvents.emit(\"login.attempt\", otherData);\n\n const user = (await Model.first(otherData)) as T | null;\n\n if (!user) {\n authEvents.emit(\"login.failed\", otherData, \"User not found\");\n\n return null;\n }\n\n if (!(await this.verifyPassword(password, user.string(\"password\")!))) {\n authEvents.emit(\"login.failed\", otherData, \"Invalid password\");\n\n return null;\n }\n\n if (!(await this.canAuthenticate(user))) {\n authEvents.emit(\"login.failed\", otherData, \"Authentication not allowed\");\n\n return null;\n }\n\n return user;\n }\n\n /**\n * Full login flow: validate credentials, issue tokens, emit events. Returns\n * the user + token pair on success, `null` on failure.\n */\n public async login<T extends Auth>(\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T> | null> {\n const user = await this.attemptLogin(Model, credentials);\n\n if (!user) {\n return null;\n }\n\n return this.finalizeLogin(user, deviceInfo);\n }\n\n /**\n * Log in a user some OTHER method already authenticated — a provider\n * callback, a passkey assertion, a one-time code. Applies the\n * `auth.canAuthenticate` policy (403 on refusal), then produces exactly\n * what {@link login} produces: the same tokens, rows and events. Pair with\n * {@link setAuthCookie} for a cookie session, as with password login.\n *\n * Never call this for a user you have not authenticated.\n */\n public async completeLogin<T extends Auth>(\n user: T,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T>> {\n await this.assertCanAuthenticate(user);\n\n return this.finalizeLogin(user, deviceInfo);\n }\n\n /**\n * Cookie login for a browser: same-origin check, credential login, then both\n * session cookies. Unlike the default CSRF guard, the Origin/Referer check\n * runs even when the request carries no cookies (login CSRF): a missing or\n * cross-site Origin/Referer throws `CsrfOriginMismatchError` before any\n * credential is looked at. Returns `null` on bad credentials.\n */\n public async loginWithSessionCookies<T extends Auth>(\n request: Request,\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T> | null> {\n assertCsrfOriginAllowed(request);\n\n const result = await this.login(Model, credentials, deviceInfo);\n\n if (!result) return null;\n\n if (result.tokens.refreshToken) {\n this.setSessionCookies(\n response,\n {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n },\n request,\n );\n } else {\n this.setAuthCookie(response, result.tokens.accessToken, {\n domain: this.cookieDomainFor(\"loginWithSessionCookies\", request),\n });\n }\n\n return result;\n }\n\n /** The one token-issuing tail every login method shares. */\n private async finalizeLogin<T extends Auth>(\n user: T,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T>> {\n if (!authConfig.refreshToken.enabled()) {\n const accessToken = await this.issueAccessToken(user, deviceInfo?.payload);\n\n return { user, tokens: { accessToken } };\n }\n\n const tokens = await this.issueTokenPair(user, deviceInfo);\n\n authEvents.emit(\"login.success\", user, tokens, deviceInfo);\n\n return { user, tokens };\n }\n\n /**\n * Log a user out.\n *\n * @param accessToken - access token string to revoke (optional)\n * @param refreshToken - refresh token string to revoke (optional)\n *\n * When no refresh token is supplied, `config.auth.refreshToken.logoutWithoutToken`\n * decides the behavior: `\"revoke-all\"` (default, fail-safe) revokes every\n * refresh token; `\"error\"` requires the caller to pass one.\n */\n public async logout(user: Auth, accessToken?: string, refreshToken?: string): Promise<void> {\n if (accessToken) {\n await this.removeAccessToken(user, accessToken);\n }\n\n if (refreshToken) {\n const token = await this.refreshTokenModel.findForUser(user, refreshToken);\n\n if (token) {\n await this.revokeTokenFamily(token.familyId);\n authEvents.emit(\"session.destroyed\", user, token);\n }\n } else {\n const behavior = authConfig.refreshToken.logoutWithoutToken();\n\n if (behavior === \"error\") {\n throw new Error(\"Refresh token required for logout\");\n }\n\n await this.revokeAllTokens(user);\n authEvents.emit(\"logout.failsafe\", user);\n }\n\n authEvents.emit(\"logout\", user);\n }\n\n /**\n * Remove a specific access token belonging to the user.\n */\n public async removeAccessToken(user: Auth, token: string): Promise<void> {\n await this.accessTokenModel.deleteForUser(user, token);\n }\n\n /**\n * Remove every access token belonging to the user.\n */\n public async removeAllAccessTokens(user: Auth): Promise<void> {\n await this.accessTokenModel.deleteAllForUser(user);\n }\n\n /**\n * Remove a specific refresh token belonging to the user.\n */\n public async removeRefreshToken(user: Auth, token: string): Promise<void> {\n await this.refreshTokenModel.deleteForUser(user, token);\n }\n\n /**\n * Revoke every active refresh token for the user and delete their access\n * tokens — \"log out of all devices\". Each durable family is first marked through its revision coordinator; an\n * event fires per revoked token.\n */\n public async revokeAllTokens(user: Auth): Promise<void> {\n // Upgrade existing installations lazily before the family scan. Include\n // revoked rows: a rotation may have revoked its predecessor while its\n // durable family still needs logout's marker.\n const existingRows = await this.refreshTokenModel.familiesForUser(user);\n\n for (const token of existingRows) {\n await AuthTokenFamily.ensure(user, token.familyId);\n }\n\n const families = await AuthTokenFamily.activeFor(user);\n\n for (const family of families) {\n await this.revokeTokenFamily(family.get<string>(\"family_id\"));\n }\n\n // A deployment can still have rows created before the additive migration\n // ran; retain the old bulk cleanup as a final conservative backstop.\n const legacyTokens = await this.refreshTokenModel.revokeAllFor(user);\n\n for (const token of legacyTokens) {\n authEvents.emit(\"token.revoked\", user, token);\n }\n await this.removeAllAccessTokens(user);\n\n authEvents.emit(\"logout.all\", user);\n }\n\n /**\n * Revoke an entire token family — rotation breach containment.\n */\n public async revokeTokenFamily(familyId: string): Promise<void> {\n let family = await AuthTokenFamily.findByFamilyId(familyId);\n\n if (!family) {\n const legacyToken = await this.refreshTokenModel.findInFamily(familyId);\n\n if (!legacyToken) return;\n\n family = await AuthTokenFamily.ensure(\n {\n id: legacyToken.get(\"user_id\"),\n userType: legacyToken.get<string>(\"user_type\"),\n } as Auth,\n familyId,\n );\n }\n\n const user = {\n id: family.get(\"user_id\"),\n userType: family.get<string>(\"user_type\"),\n } as Auth;\n\n if (family.isRevoked) {\n // Logout and replay containment are idempotent. Re-run cleanup because a\n // request that lost the original race may have observed stale rows.\n const revokedTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(user, familyId);\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.familyRevoked\", familyId, revokedTokens),\n );\n\n return;\n }\n\n let revokedTokens: RefreshToken[];\n try {\n revokedTokens = await runTokenFamilyOperation(familyId, async (currentFamily) => {\n const familyUser = {\n id: currentFamily.get(\"user_id\"),\n userType: currentFamily.get<string>(\"user_type\"),\n } as Auth;\n const revision = currentFamily.get<number>(\"revision\");\n const revoked = await AuthTokenFamily.revoke(familyId, revision);\n\n if (revoked !== 1) {\n throw new Error(\"Token family revoke lost its revision transition\");\n }\n\n const familyTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(familyUser, familyId);\n\n return familyTokens;\n });\n } catch (error) {\n if (!(error instanceof TokenFamilyUnavailableError)) throw error;\n\n // Another request committed the revoke between the read above and its\n // CAS. A second logout is successful after idempotent cleanup.\n revokedTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(user, familyId);\n }\n\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.familyRevoked\", familyId, revokedTokens),\n );\n }\n\n /**\n * Delete expired tokens (refresh + access) and spent one-time tokens\n * (expired or consumed verification/reset/OTP/passkey rows). Emits `token.expired` per refresh\n * token and `cleanup.completed` with the refresh count. Drives the\n * `auth.cleanup` CLI command.\n */\n public async cleanupExpiredTokens(): Promise<number> {\n const expiredTokens = await this.refreshTokenModel.purgeExpired();\n\n for (const token of expiredTokens) {\n authEvents.emit(\"token.expired\", token);\n }\n\n await this.accessTokenModel.purgeExpired();\n await this.oneTimeTokenModel.purgeSpent();\n\n authEvents.emit(\"cleanup.completed\", expiredTokens.length);\n\n return expiredTokens.length;\n }\n\n /**\n * Find every persisted token — access and refresh — that can never retire\n * itself: an unusable `expires_at`, or a token carrying no `exp` claim.\n *\n * This is the remediation read for the pre-4.12.0 `expiresIn` defect (#25).\n * Nothing else surfaces these rows: `auth.cleanup` selects `expires_at < now`,\n * which an `Invalid Date` never satisfies, and a row whose date column is\n * perfectly fine can still hold a token with no deadline in it. Read-only —\n * pair with {@link purgeNeverExpiringTokens} to act on the answer.\n */\n public async findNeverExpiringTokens(): Promise<{\n accessTokens: AccessToken[];\n refreshTokens: RefreshToken[];\n }> {\n return {\n accessTokens: await this.accessTokenModel.findNeverExpiring(),\n refreshTokens: await this.refreshTokenModel.findNeverExpiring(),\n };\n }\n\n /**\n * Revoke every never-expiring token by deleting its row, emitting\n * `token.revoked` per refresh token. Drives `warlock auth.purge-never-expiring`.\n *\n * Access tokens first: deleting one is immediate revocation, while a refresh\n * token left in place for a moment can only mint an access token through a\n * verifier that now rejects it for the missing `exp`.\n */\n public async purgeNeverExpiringTokens(): Promise<{\n accessTokens: number;\n refreshTokens: number;\n }> {\n const accessTokens = await this.accessTokenModel.purgeNeverExpiring();\n const refreshTokens = await this.refreshTokenModel.purgeNeverExpiring();\n\n // `token.expired` (the event `auth.cleanup` already emits for a removed\n // refresh token) rather than `token.revoked`, which carries a loaded `Auth`\n // this batch path has no reason to fetch a user row for.\n for (const token of refreshTokens) {\n authEvents.emit(\"token.expired\", token);\n }\n\n return { accessTokens: accessTokens.length, refreshTokens: refreshTokens.length };\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public async getActiveSessions(user: Auth): Promise<RefreshToken[]> {\n return this.refreshTokenModel.activeFor(user);\n }\n\n /**\n * `Max-Age` (seconds) `setAuthCookie` should apply, derived from an\n * `AccessTokenOutput`'s `expiresAt` — or `undefined` for a bare token\n * string (a session cookie) or an unparseable `expiresAt`.\n */\n private cookieMaxAgeFromToken(token: string | AccessTokenOutput): number | undefined {\n if (typeof token === \"string\") return undefined;\n\n const expiresAt = new Date(token.expiresAt).getTime();\n\n if (Number.isNaN(expiresAt)) return undefined;\n\n return Math.max(0, Math.round((expiresAt - Date.now()) / 1000));\n }\n\n private cookieDomainFor(method: string, request?: Request): string | undefined {\n const resolver = authConfig.cookie.cookieDomain();\n\n if (!resolver) {\n return undefined;\n }\n\n if (!request) {\n throw new CookieDomainRequestRequiredError(method);\n }\n\n return resolver(request);\n }\n\n /**\n * Write the auth cookie on `response` — the write side of the `cookie:<name>`\n * token source `authMiddleware([], \"cookie:<name>\")` already reads. An explicit\n * app-controller call, never a side effect of {@link login}, so an existing\n * bearer-only app never starts emitting `Set-Cookie` just by upgrading.\n *\n * Attribute flags (`HttpOnly`, `SameSite=Lax`, `Secure` outside dev) come\n * from `response.cookie()`'s own `secureCookieDefaults()` floor — this\n * method never overrides them, only `name`/`path`/`maxAge`. `raw: true`\n * writes the token unquoted, so the same string a `cookie:<name>` source\n * reads back is exactly what was issued, not a JSON-wrapped copy.\n *\n * @param token - the token string, or an `AccessTokenOutput` (e.g. from\n * {@link login}) whose `expiresAt` sets `Max-Age` automatically when\n * `options.maxAge` is not given. A bare string with no `options.maxAge`\n * produces a session cookie.\n *\n * @example\n * const { user, tokens } = await authService.login(User, credentials);\n * authService.setAuthCookie(response, tokens.accessToken);\n */\n public setAuthCookie(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n token: string | AccessTokenOutput,\n options: SetAuthCookieOptions = {},\n ): void {\n const name = options.name ?? authConfig.cookie.name();\n const path = options.path ?? authConfig.cookie.path();\n const tokenValue = typeof token === \"string\" ? token : token.token;\n const maxAge = options.maxAge ?? this.cookieMaxAgeFromToken(token);\n\n response.cookie(name, tokenValue, {\n raw: true,\n path,\n ...(options.domain !== undefined ? { domain: options.domain } : {}),\n ...(maxAge !== undefined ? { maxAge } : {}),\n });\n }\n\n /**\n * Clear the auth cookie {@link setAuthCookie} wrote. An explicit\n * app-controller call — pair it with {@link logout} after the token row is\n * revoked. `path` must match what the cookie was set with, or the browser\n * silently ignores the clear (see `response.clearCookie`'s own doc comment).\n *\n * @example\n * await authService.logout(user, accessToken, refreshToken);\n * authService.clearAuthCookie(response);\n */\n public clearAuthCookie(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n options: ClearAuthCookieOptions = {},\n request?: Request,\n ): void {\n const name = options.name ?? authConfig.cookie.name();\n const path = options.path ?? authConfig.cookie.path();\n const domain = this.cookieDomainFor(\"clearAuthCookie\", request);\n\n if (domain !== undefined) {\n response.clearCookie(name, { path, domain });\n }\n\n response.clearCookie(name, { path });\n }\n\n /**\n * Write the access and refresh cookies of a browser session. Both are\n * `HttpOnly`, `SameSite=Lax`, `Path=/` (the refresh cookie must reach every\n * page) and `Secure` outside development, named by `auth.cookie.name` and\n * `auth.cookie.refreshName`. Each `Max-Age` is derived from its token's\n * `expiresAt`, so the cookie lives exactly as long as the token.\n *\n * @example\n * const { tokens } = await authService.login(User, credentials);\n * authService.setSessionCookies(response, tokens);\n */\n public setSessionCookies(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n tokens: { accessToken: AccessTokenOutput; refreshToken: AccessTokenOutput },\n request?: Request,\n ): void {\n const domain = this.cookieDomainFor(\"setSessionCookies\", request);\n const cookies = [\n [authConfig.cookie.name(), tokens.accessToken],\n [authConfig.cookie.refreshName(), tokens.refreshToken],\n ] as const;\n\n for (const [name, token] of cookies) {\n const maxAge = this.cookieMaxAgeFromToken(token);\n\n response.cookie(name, token.token, {\n raw: true,\n httpOnly: true,\n sameSite: \"lax\",\n path: \"/\",\n ...(domain !== undefined ? { domain } : {}),\n ...(maxAge !== undefined ? { maxAge } : {}),\n });\n }\n }\n\n /**\n * Clear both session cookies {@link setSessionCookies} wrote, on `Path=/`.\n * Pair it with {@link logout} after the token rows are revoked.\n */\n public clearSessionCookies(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n request?: Request,\n ): void {\n const domain = this.cookieDomainFor(\"clearSessionCookies\", request);\n\n for (const name of [authConfig.cookie.name(), authConfig.cookie.refreshName()]) {\n if (domain !== undefined) {\n response.clearCookie(name, { path: \"/\", domain });\n }\n\n response.clearCookie(name, { path: \"/\" });\n }\n }\n}\n\nexport const authService = new AuthService();\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,IAAa,mCAAb,cAAsD,MAAM;CAC1D,AAAO,YAAY,QAAgB;EACjC,MACE,GAAG,OAAO,+HACZ;EACA,KAAK,OAAO;CACd;AACF;AAEA,IAAM,cAAN,MAAkB;;;;;;;CAOhB,IAAY,mBAAuC;EACjD,OAAO,OAAO,IAAI,0BAA0B,WAAW;CACzD;;;;CAKA,IAAY,oBAAyC;EACnD,OAAO,OAAO,IAAI,2BAA2B,YAAY;CAC3D;;;;CAKA,IAAY,oBAAyC;EACnD,OAAO,OAAO,IAAI,2BAA2B,YAAY;CAC3D;;;;CAKA,AAAO,wBAAwB,MAAqC;EAClE,OAAO;GACL,IAAI,KAAK;GACT,UAAU,KAAK;GACf,YAAY,KAAK,IAAI;EACvB;CACF;;CAGA,MAAa,gBAAgB,MAA8B;EACzD,OAAO,WAAW,gBAA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,IAAI,CAAC;IACzC,GAAI,WAAW,SAAY,EAAE,OAAO,IAAI,CAAC;GAC3C,CAAC;EACH;CACF;;;;;CAMA,AAAO,oBACL,UACA,SACM;EACN,MAAM,SAAS,KAAK,gBAAgB,uBAAuB,OAAO;EAElE,KAAK,MAAM,QAAQ,CAAC,WAAW,OAAO,KAAK,GAAG,WAAW,OAAO,YAAY,CAAC,GAAG;GAC9E,IAAI,WAAW,QACb,SAAS,YAAY,MAAM;IAAE,MAAM;IAAK;GAAO,CAAC;GAGlD,SAAS,YAAY,MAAM,EAAE,MAAM,IAAI,CAAC;EAC1C;CACF;AACF;AAEA,MAAa,cAAc,IAAI,YAAY"}
@@ -1,5 +1,5 @@
1
1
  import { AuthEventCallback, AuthEventName, AuthEventPayloads, authEvents } from "./auth-events.mjs";
2
- import { authService } from "./auth.service.mjs";
2
+ import { CookieDomainRequestRequiredError, authService } from "./auth.service.mjs";
3
3
  import { currentUser } from "./current-user.mjs";
4
4
  import { generateJWTSecret } from "./generate-jwt-secret.mjs";
5
5
  import { TokenType, TokenTypeError, isInvalidCredentialError, jwt } from "./jwt.mjs";
@@ -1,6 +1,6 @@
1
1
  import { authEvents } from "./auth-events.mjs";
2
2
  import { TokenTypeError, isInvalidCredentialError, jwt } from "./jwt.mjs";
3
- import { authService } from "./auth.service.mjs";
3
+ import { CookieDomainRequestRequiredError, authService } from "./auth.service.mjs";
4
4
  import { generateJWTSecret } from "./generate-jwt-secret.mjs";
5
5
  import { readCredential, resolveRequestUser, resolveRequestUserOutcome } from "./resolve-request-user.mjs";
6
6
  import { currentUser } from "./current-user.mjs";
@@ -1,4 +1,4 @@
1
- import { TokenFrom } from "../contracts/types.mjs";
1
+ import { CookieDomainResolver, TokenFrom } from "../contracts/types.mjs";
2
2
  import { Request, Response } from "@warlock.js/core";
3
3
 
4
4
  //#region ../auth/src/services/resolve-request-user.d.ts
@@ -8,7 +8,8 @@ type ResolveRequestUserOptions = {
8
8
  overlapMs?: number; /** User types allowed to pass. Empty means any authenticated type. */
9
9
  allowedTypes?: string[]; /** Absolute family lifetime in ms; rotation never extends a family past it. */
10
10
  maxAgeMs?: number; /** The single user type a renewal mints for. Required for renewal. */
11
- renewalUserType?: string;
11
+ renewalUserType?: string; /** Select a request-scoped Domain for renewed cookies. */
12
+ cookieDomain?: CookieDomainResolver;
12
13
  };
13
14
  /**
14
15
  * Why a request did not resolve to a user. The middleware maps each reason to
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-request-user.d.mts","names":[],"sources":["../../../../../../../auth/src/services/resolve-request-user.ts"],"mappings":";;;;KAgBY,yBAAA;qEAEV,SAAA,GAAY,SAAA,EAFuB;EAInC,iBAAA,GAAoB,SAAS,EAAA;EAE7B,SAAA,WAJY;EAMZ,YAAA,aAJoB;EAMpB,QAAA,WAFA;EAIA,eAAA;AAAA;;AAAe;AAOjB;;KAAY,kBAAA;AAAA,KAEA,kBAAA;EACN,IAAA,EAAM,KAAA;EAAO,OAAA;AAAA;EACb,IAAA;EAAY,OAAA,EAAS,kBAAkB;AAAA;;iBAoB7B,cAAA,CAAe,OAAA,EAAS,OAAA,EAAS,SAAA,EAAW,SAAS;;;;;;AApBxB;AAoB7C;;;;;iBAqBsB,yBAAA,CACpB,OAAA,EAAS,OAAA,EACT,QAAA,EAAU,QAAA,EACV,OAAA,GAAS,yBAAA,GACR,OAAA,CAAQ,kBAAA;;;;AAzB0D;AAqBrE;;;iBAqHgB,kBAAA,CACd,OAAA,EAAS,OAAA,EACT,QAAA,EAAU,QAAA,EACV,OAAA,GAAS,yBAAA,GACR,OAAA"}
1
+ {"version":3,"file":"resolve-request-user.d.mts","names":[],"sources":["../../../../../../../auth/src/services/resolve-request-user.ts"],"mappings":";;;;KAgBY,yBAAA;qEAEV,SAAA,GAAY,SAAA,EAFuB;EAInC,iBAAA,GAAoB,SAAA,EAFR;EAIZ,SAAA,WAQe;EANf,YAAA,aAMmC;EAJnC,QAAA,WARY;EAUZ,eAAA,WARoB;EAUpB,YAAA,GAAe,oBAAA;AAAA;;;;;KAOL,kBAAA;AAAA,KAEA,kBAAA;EACR,IAAA,EAAM,KAAA;EAAO,OAAA;AAAA;EAA0B,IAAA;EAAY,OAAA,EAAS,kBAAkB;AAAA;;iBAoBlE,cAAA,CAAe,OAAA,EAAS,OAAA,EAAS,SAAA,EAAW,SAAS;;;;;;;;;;AApBa;AAoBlF;iBAqBsB,yBAAA,CACpB,OAAA,EAAS,OAAA,EACT,QAAA,EAAU,QAAA,EACV,OAAA,GAAS,yBAAA,GACR,OAAA,CAAQ,kBAAA;;;;;;;;iBAmHK,kBAAA,CACd,OAAA,EAAS,OAAA,EACT,QAAA,EAAU,QAAA,EACV,OAAA,GAAS,yBAAA,GACR,OAAA"}
@@ -55,8 +55,14 @@ async function resolveRequestUserOutcome(request, response, options = {}) {
55
55
  maxAgeMs: options.maxAgeMs
56
56
  });
57
57
  if (!pair?.refreshToken) return false;
58
- authService.setAuthCookie(response, pair.accessToken, { name: tokenFrom.slice(7) });
59
- authService.setAuthCookie(response, pair.refreshToken, { name: refreshCredential.slice(7) });
58
+ authService.setAuthCookie(response, pair.accessToken, {
59
+ name: tokenFrom.slice(7),
60
+ domain: options.cookieDomain?.(request)
61
+ });
62
+ authService.setAuthCookie(response, pair.refreshToken, {
63
+ name: refreshCredential.slice(7),
64
+ domain: options.cookieDomain?.(request)
65
+ });
60
66
  authorizationValue = pair.accessToken.token;
61
67
  return true;
62
68
  };