@warlock.js/auth 5.64.0 → 5.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/esm/contracts/index.d.mts +2 -2
  3. package/esm/contracts/types.d.mts +36 -2
  4. package/esm/contracts/types.d.mts.map +1 -1
  5. package/esm/contracts/types.mjs.map +1 -1
  6. package/esm/index.d.mts +2 -2
  7. package/esm/models/access-token/access-token.model.d.mts +2 -1
  8. package/esm/models/access-token/access-token.model.d.mts.map +1 -1
  9. package/esm/models/access-token/access-token.model.mjs +10 -3
  10. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  11. package/esm/models/refresh-token/refresh-token.model.mjs +8 -2
  12. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  13. package/esm/otp/otp.d.mts +4 -1
  14. package/esm/otp/otp.d.mts.map +1 -1
  15. package/esm/otp/otp.mjs +7 -2
  16. package/esm/otp/otp.mjs.map +1 -1
  17. package/esm/passkeys/passkey-authentication.mjs +4 -1
  18. package/esm/passkeys/passkey-authentication.mjs.map +1 -1
  19. package/esm/providers/provider-login.mjs +4 -1
  20. package/esm/providers/provider-login.mjs.map +1 -1
  21. package/esm/services/auth-config.mjs +2 -2
  22. package/esm/services/auth-config.mjs.map +1 -1
  23. package/esm/services/auth.service.d.mts +32 -7
  24. package/esm/services/auth.service.d.mts.map +1 -1
  25. package/esm/services/auth.service.mjs +82 -27
  26. package/esm/services/auth.service.mjs.map +1 -1
  27. package/esm/services/resolve-request-user.d.mts.map +1 -1
  28. package/esm/services/resolve-request-user.mjs +6 -2
  29. package/esm/services/resolve-request-user.mjs.map +1 -1
  30. package/llms-full.txt +7 -3
  31. package/package.json +8 -8
  32. package/skills/customize-user-type/SKILL.md +1 -1
  33. package/skills/handle-login-and-logout/SKILL.md +4 -0
  34. package/skills/login-with-providers/SKILL.md +1 -1
  35. package/skills/manage-tokens/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth.service.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\nimport { createCipheriv, createDecipheriv, createHmac, randomBytes, randomUUID } from \"node:crypto\";\nimport { cache } from \"@warlock.js/cache\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport {\n config,\n ForbiddenError,\n hashPassword,\n needsRehash,\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 {\n assertHostPrefixAllowed,\n authCookieNames,\n authCookieWriteName,\n HOST_COOKIE_PREFIX,\n} from \"./auth-cookie-names\";\nimport { type AuthIdentifiers, trimIdentifiers } from \"../utils/normalize-credentials\";\nimport {\n isTokenDigest,\n plainTokenOf,\n rememberPlainToken,\n tokenDigest,\n} from \"../utils/token-digest\";\nimport { authEvents } from \"./auth-events\";\nimport { log } from \"@warlock.js/logger\";\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\n/**\n * A hash of a random password, made once with the app's own `hashPassword`\n * (same algorithm and cost as real users) the first time a login names an\n * unknown account. Checking a password against it costs what a real check\n * costs, so the response time does not reveal whether the account exists.\n */\nlet dummyPasswordHash: Promise<string> | undefined;\n\nfunction dummyHash(): Promise<string> {\n dummyPasswordHash ??= Promise.resolve()\n .then(() => hashPassword(randomBytes(16).toString(\"hex\")))\n .catch((error: unknown) => {\n dummyPasswordHash = undefined;\n throw error;\n });\n\n return dummyPasswordHash;\n}\n\n/** The value a token row stores for `token` (`auth.hashTokensAtRest`). */\nfunction storedToken(token: string): string {\n return authConfig.hashTokensAtRest() ? tokenDigest(token) : token;\n}\n\n/** Whether a row's stored token value is `token`, hashed or raw. */\nfunction storesToken(stored: unknown, token: unknown): boolean {\n return typeof token === \"string\" && (stored === token || stored === tokenDigest(token));\n}\n\nconst SUCCESSOR_PREFIX = \"auth.renewal.successor.\";\n\n/** AES-256-GCM key for successor pairs parked in the cache, derived from the access secret. */\nfunction successorKey(): Buffer {\n return createHmac(\"sha256\", authConfig.accessToken.secret())\n .update(\"@warlock.js/auth:renewal-successor\")\n .digest();\n}\n\nfunction sealSuccessor(pair: TokenPair): string {\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", successorKey(), iv);\n const body = Buffer.concat([cipher.update(JSON.stringify(pair), \"utf8\"), cipher.final()]);\n\n return [iv, cipher.getAuthTag(), body].map((part) => part.toString(\"base64url\")).join(\".\");\n}\n\nfunction openSuccessor(sealed: unknown): TokenPair | null {\n if (typeof sealed !== \"string\") return null;\n\n const [iv, tag, body] = sealed.split(\".\").map((part) => Buffer.from(part, \"base64url\"));\n\n if (!iv || !tag || !body) return null;\n\n try {\n const decipher = createDecipheriv(\"aes-256-gcm\", successorKey(), iv);\n decipher.setAuthTag(tag);\n\n return JSON.parse(\n Buffer.concat([decipher.update(body), decipher.final()]).toString(\"utf8\"),\n ) as TokenPair;\n } catch {\n return null;\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 // The identity claims always come from the user the row is issued to: a\n // custom payload may add claims, never point the token at someone else.\n const data = {\n ...(payload || this.buildAccessTokenPayload(user)),\n id: user.id,\n userType: user.userType,\n jti: randomUUID(),\n };\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, storedToken(token), expiresAt, familyId);\n } else {\n await this.accessTokenModel.issue(user, storedToken(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 const row = await this.refreshTokenModel.issue(user, storedToken(token), {\n familyId,\n expiresAt,\n deviceInfo,\n });\n\n rememberPlainToken(row, token);\n\n return row;\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: plainTokenOf(refreshToken, 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 await this.parkAutomaticSuccessor(oldToken, successorAccess, pair, options.overlapMs);\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\n const storedAccess = access.get<string>(\"token\");\n const storedRefresh = refresh.get<string>(\"token\");\n\n if (!isTokenDigest(storedAccess) && !isTokenDigest(storedRefresh)) {\n return {\n accessToken: { token: storedAccess, expiresAt: access.get(\"expires_at\") },\n refreshToken: { token: storedRefresh, expiresAt: refresh.get(\"expires_at\") },\n };\n }\n\n // Hashed rows cannot hand the pair back; it was parked, encrypted, in the\n // cache for the overlap window. It must still match the linked rows.\n const parked = await this.readParkedSuccessor(oldToken);\n\n if (\n !parked?.refreshToken ||\n !storesToken(storedAccess, parked.accessToken.token) ||\n !storesToken(storedRefresh, parked.refreshToken.token)\n ) {\n return null;\n }\n\n return {\n accessToken: { token: parked.accessToken.token, expiresAt: access.get(\"expires_at\") },\n refreshToken: { token: parked.refreshToken.token, expiresAt: refresh.get(\"expires_at\") },\n };\n }\n\n /**\n * With hashed token rows, keep the successor pair (encrypted) in the cache\n * for the overlap window, so a duplicate renewal inside it can still receive\n * the same pair. Unhashed rows need nothing: the pair is read from them.\n * Best-effort: without a cache, a duplicate inside the window fails quietly.\n */\n private async parkAutomaticSuccessor(\n oldToken: RefreshToken,\n successorAccess: AccessToken,\n pair: TokenPair,\n overlapMs: number | undefined,\n ): Promise<void> {\n const window = this.automaticOverlapMs(overlapMs);\n\n if (window <= 0 || !isTokenDigest(successorAccess.get(\"token\"))) return;\n\n try {\n await cache.set(`${SUCCESSOR_PREFIX}${String(oldToken.id)}`, sealSuccessor(pair), {\n ttl: Math.max(1, Math.ceil(window / 1000)),\n });\n } catch (error) {\n log.error(\"auth\", \"renewal\", error);\n }\n }\n\n private async readParkedSuccessor(oldToken: RefreshToken): Promise<TokenPair | null> {\n try {\n return openSuccessor(await cache.get(`${SUCCESSOR_PREFIX}${String(oldToken.id)}`));\n } catch (error) {\n log.error(\"auth\", \"renewal\", error);\n\n return null;\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 * Look a user up by login identifiers: normalized first (see\n * `auth.normalizeCredentials`), then once more with the values as sent\n * (trimmed) when that differs, so legacy rows stored with capitals still match.\n */\n private async findLoginUser<T extends Auth>(\n Model: ChildModel<T>,\n identifiers: AuthIdentifiers,\n ): Promise<T | null> {\n const normalize = authConfig.normalizeCredentials();\n\n if (normalize === false) {\n return (await Model.first(identifiers)) as T | null;\n }\n\n const normalized = normalize(identifiers);\n const user = (await Model.first(normalized)) as T | null;\n\n if (user) return user;\n\n const asSent = trimIdentifiers(identifiers);\n\n if (JSON.stringify(asSent) === JSON.stringify(normalized)) return null;\n\n return (await Model.first(asSent)) as T | null;\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 this.findLoginUser(Model, otherData);\n const storedHash = user?.string(\"password\");\n\n if (!user || !storedHash) {\n // Spend the same hashing work as a real check, so an unknown account\n // answers no faster than a wrong password.\n await dummyHash()\n .then((hash) => this.verifyPassword(String(password ?? \"\"), hash))\n .catch(() => false);\n\n authEvents.emit(\"login.failed\", otherData, user ? \"Invalid password\" : \"User not found\");\n\n return null;\n }\n\n if (!(await this.verifyPassword(password, storedHash))) {\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 await this.rehashPassword(user, String(password), storedHash);\n\n return user;\n }\n\n /**\n * After a successful password check, replace a hash that no longer matches\n * the configured algorithm or cost (`auth.rehashPasswords`, default on) with\n * a fresh one made from the password just verified. Never fails the login:\n * a problem is logged and the old hash keeps working.\n */\n private async rehashPassword(user: Auth, plainPassword: string, storedHash: string) {\n try {\n if (!authConfig.rehashPasswords() || !needsRehash(storedHash)) return;\n\n // Save a hash first. A model that hashes on save (`useHashedPassword()`)\n // would hash that again, so check what was stored and, if it no longer\n // verifies, save the plaintext for the model's own transformer.\n await user.merge({ password: await this.hashPassword(plainPassword) } as never).save();\n\n if (await this.verifyPassword(plainPassword, user.string(\"password\") ?? \"\")) return;\n\n await user.merge({ password: plainPassword } as never).save();\n } catch (error) {\n log.error(\"auth\", \"rehash-password\", error);\n }\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\". Durable families are ensured together\n * and revoked with one update, refresh tokens with another; a\n * `token.familyRevoked` event fires per family (and `token.revoked` for a\n * token outside any durable family).\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 // Every rotation leaves a row behind, so the rows outnumber the families\n // by far: ensure the distinct families together, with one read and one\n // insert for the missing ones.\n const familyIds = new Set(existingRows.map((token) => token.familyId).filter(Boolean));\n\n await AuthTokenFamily.ensureMany(user, [...familyIds]);\n\n const families = await AuthTokenFamily.activeFor(user);\n const revokedFamilyIds = families.map((family) => family.get<string>(\"family_id\"));\n\n // One update revokes every family, which also fences out a rotation in flight.\n if (revokedFamilyIds.length > 0) await AuthTokenFamily.revokeAllFor(user);\n\n // One update revokes every refresh token; the rows read just before it say\n // which family each belonged to, for the per-family events.\n const revokedTokens = await this.refreshTokenModel.revokeAllFor(user);\n const tokensByFamily = new Map<string, RefreshToken[]>();\n const unfamilied: RefreshToken[] = [];\n\n for (const token of revokedTokens) {\n const familyId = token.familyId;\n\n if (familyId && revokedFamilyIds.includes(familyId)) {\n tokensByFamily.set(familyId, [...(tokensByFamily.get(familyId) ?? []), token]);\n } else {\n unfamilied.push(token);\n }\n }\n\n for (const familyId of revokedFamilyIds) {\n authEvents.emit(\"token.familyRevoked\", familyId, tokensByFamily.get(familyId) ?? []);\n }\n\n // Rows without an active durable family (created before the additive\n // migration ran) are reported one by one.\n for (const token of unfamilied) {\n authEvents.emit(\"token.revoked\", user, token);\n }\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 = authCookieWriteName(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 const hostOnly = name.startsWith(HOST_COOKIE_PREFIX);\n\n assertHostPrefixAllowed(name, { path, domain: options.domain });\n\n response.cookie(name, tokenValue, {\n raw: true,\n path,\n ...(hostOnly ? { secure: true } : {}),\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 path = options.path ?? authConfig.cookie.path();\n const domain = this.cookieDomainFor(\"clearAuthCookie\", request);\n\n for (const name of authCookieNames(options.name ?? authConfig.cookie.name())) {\n if (name.startsWith(HOST_COOKIE_PREFIX)) {\n response.clearCookie(name, { path: \"/\", secure: true });\n continue;\n }\n\n if (domain !== undefined) {\n response.clearCookie(name, { path, domain });\n }\n\n response.clearCookie(name, { path });\n }\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 [authCookieWriteName(authConfig.cookie.name()), tokens.accessToken],\n [authCookieWriteName(authConfig.cookie.refreshName()), tokens.refreshToken],\n ] as const;\n\n for (const [name, token] of cookies) {\n const maxAge = this.cookieMaxAgeFromToken(token);\n const hostOnly = name.startsWith(HOST_COOKIE_PREFIX);\n\n assertHostPrefixAllowed(name, { path: \"/\", domain });\n\n response.cookie(name, token.token, {\n raw: true,\n httpOnly: true,\n sameSite: \"lax\",\n path: \"/\",\n ...(hostOnly ? { secure: true } : {}),\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 const names = [\n ...authCookieNames(authConfig.cookie.name()),\n ...authCookieNames(authConfig.cookie.refreshName()),\n ];\n\n for (const name of names) {\n if (name.startsWith(HOST_COOKIE_PREFIX)) {\n response.clearCookie(name, { path: \"/\", secure: true });\n continue;\n }\n\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":";;;;;;;;;;;;;;;;;;;;;;;;AAoDA,IAAa,mCAAb,cAAsD,MAAM;CAC1D,AAAO,YAAY,QAAgB;EACjC,MACE,GAAG,OAAO,+HACZ;EACA,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAI;AAEJ,SAAS,YAA6B;CACpC,sBAAsB,QAAQ,QAAQ,CAAC,CACpC,WAAW,aAAa,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,CACzD,OAAO,UAAmB;EACzB,oBAAoB;EACpB,MAAM;CACR,CAAC;CAEH,OAAO;AACT;;AAGA,SAAS,YAAY,OAAuB;CAC1C,OAAO,WAAW,iBAAiB,IAAI,YAAY,KAAK,IAAI;AAC9D;;AAGA,SAAS,YAAY,QAAiB,OAAyB;CAC7D,OAAO,OAAO,UAAU,aAAa,WAAW,SAAS,WAAW,YAAY,KAAK;AACvF;AAEA,MAAM,mBAAmB;;AAGzB,SAAS,eAAuB;CAC9B,OAAO,WAAW,UAAU,WAAW,YAAY,OAAO,CAAC,CAAC,CACzD,OAAO,oCAAoC,CAAC,CAC5C,OAAO;AACZ;AAEA,SAAS,cAAc,MAAyB;CAC9C,MAAM,KAAK,YAAY,EAAE;CACzB,MAAM,SAAS,eAAe,eAAe,aAAa,GAAG,EAAE;CAC/D,MAAM,OAAO,OAAO,OAAO,CAAC,OAAO,OAAO,KAAK,UAAU,IAAI,GAAG,MAAM,GAAG,OAAO,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O;EAChE,MAAM,UAAU,CACd,CAAC,oBAAoB,WAAW,OAAO,KAAK,CAAC,GAAG,OAAO,WAAW,GAClE,CAAC,oBAAoB,WAAW,OAAO,YAAY,CAAC,GAAG,OAAO,YAAY,CAC5E;EAEA,KAAK,MAAM,CAAC,MAAM,UAAU,SAAS;GACnC,MAAM,SAAS,KAAK,sBAAsB,KAAK;GAC/C,MAAM,WAAW,KAAK,WAAW,kBAAkB;GAEnD,wBAAwB,MAAM;IAAE,MAAM;IAAK;GAAO,CAAC;GAEnD,SAAS,OAAO,MAAM,MAAM,OAAO;IACjC,KAAK;IACL,UAAU;IACV,UAAU;IACV,MAAM;IACN,GAAI,WAAW,EAAE,QAAQ,KAAK,IAAI,CAAC;IACnC,GAAI,WAAW,SAAY,EAAE,OAAO,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;EAClE,MAAM,QAAQ,CACZ,GAAG,gBAAgB,WAAW,OAAO,KAAK,CAAC,GAC3C,GAAG,gBAAgB,WAAW,OAAO,YAAY,CAAC,CACpD;EAEA,KAAK,MAAM,QAAQ,OAAO;GACxB,IAAI,KAAK,oBAA6B,GAAG;IACvC,SAAS,YAAY,MAAM;KAAE,MAAM;KAAK,QAAQ;IAAK,CAAC;IACtD;GACF;GAEA,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
+ {"version":3,"file":"auth.service.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth.service.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\nimport { createCipheriv, createDecipheriv, createHmac, randomBytes, randomUUID } from \"node:crypto\";\nimport { cache } from \"@warlock.js/cache\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport {\n config,\n ForbiddenError,\n hashPassword,\n needsRehash,\n type Request,\n type Response,\n verifyPassword,\n} from \"@warlock.js/core\";\nimport type {\n AccessTokenOutput,\n AuthCredentials,\n AuthenticationContext,\n ClearAuthCookieOptions,\n DeviceInfo,\n LoginResult,\n CredentialsVerification,\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 {\n assertHostPrefixAllowed,\n authCookieNames,\n authCookieWriteName,\n HOST_COOKIE_PREFIX,\n} from \"./auth-cookie-names\";\nimport { type AuthIdentifiers, trimIdentifiers } from \"../utils/normalize-credentials\";\nimport {\n isTokenDigest,\n plainTokenOf,\n rememberPlainToken,\n tokenDigest,\n} from \"../utils/token-digest\";\nimport { authEvents } from \"./auth-events\";\nimport { log } from \"@warlock.js/logger\";\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\n/**\n * A hash of a random password, made once with the app's own `hashPassword`\n * (same algorithm and cost as real users) the first time a login names an\n * unknown account. Checking a password against it costs what a real check\n * costs, so the response time does not reveal whether the account exists.\n */\nlet dummyPasswordHash: Promise<string> | undefined;\n\nfunction dummyHash(): Promise<string> {\n dummyPasswordHash ??= Promise.resolve()\n .then(() => hashPassword(randomBytes(16).toString(\"hex\")))\n .catch((error: unknown) => {\n dummyPasswordHash = undefined;\n throw error;\n });\n\n return dummyPasswordHash;\n}\n\n/** The value a token row stores for `token` (`auth.hashTokensAtRest`). */\nfunction storedToken(token: string): string {\n return authConfig.hashTokensAtRest() ? tokenDigest(token) : token;\n}\n\n/** Whether a row's stored token value is `token`, hashed or raw. */\nfunction storesToken(stored: unknown, token: unknown): boolean {\n return typeof token === \"string\" && (stored === token || stored === tokenDigest(token));\n}\n\nconst SUCCESSOR_PREFIX = \"auth.renewal.successor.\";\n\n/** AES-256-GCM key for successor pairs parked in the cache, derived from the access secret. */\nfunction successorKey(): Buffer {\n return createHmac(\"sha256\", authConfig.accessToken.secret())\n .update(\"@warlock.js/auth:renewal-successor\")\n .digest();\n}\n\nfunction sealSuccessor(pair: TokenPair): string {\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", successorKey(), iv);\n const body = Buffer.concat([cipher.update(JSON.stringify(pair), \"utf8\"), cipher.final()]);\n\n return [iv, cipher.getAuthTag(), body].map((part) => part.toString(\"base64url\")).join(\".\");\n}\n\nfunction openSuccessor(sealed: unknown): TokenPair | null {\n if (typeof sealed !== \"string\") return null;\n\n const [iv, tag, body] = sealed.split(\".\").map((part) => Buffer.from(part, \"base64url\"));\n\n if (!iv || !tag || !body) return null;\n\n try {\n const decipher = createDecipheriv(\"aes-256-gcm\", successorKey(), iv);\n decipher.setAuthTag(tag);\n\n return JSON.parse(\n Buffer.concat([decipher.update(body), decipher.final()]).toString(\"utf8\"),\n ) as TokenPair;\n } catch {\n return null;\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 /**\n * One policy seam keeps account-state checks identical across all auth paths.\n * `context` tells the `auth.canAuthenticate` policy how the user is\n * authenticating (`via`) and, when the call site has one, the request.\n */\n public async canAuthenticate(user: Auth, context?: AuthenticationContext): Promise<boolean> {\n return authConfig.canAuthenticate(user, context);\n }\n\n private async assertCanAuthenticate(user: Auth, context?: AuthenticationContext): Promise<void> {\n if (!(await this.canAuthenticate(user, context))) {\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 // Claims come from the user model's `accessTokenPayload()` hook, so a model\n // override applies on login, refresh and renewal alike. An explicit payload\n // adds to them. The identity claims always come from the user the row is\n // issued to: a custom payload may add claims, never point the token at\n // someone else.\n // A plain user object (a test's `actingAs` user, an app's own shape) has no\n // hook: it gets the default claims.\n const claims =\n typeof user.accessTokenPayload === \"function\"\n ? user.accessTokenPayload()\n : this.buildAccessTokenPayload(user);\n const data = {\n ...claims,\n ...payload,\n id: user.id,\n userType: user.userType,\n jti: randomUUID(),\n };\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, storedToken(token), expiresAt, familyId);\n } else {\n await this.accessTokenModel.issue(user, storedToken(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, { via: \"token\" });\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 const row = await this.refreshTokenModel.issue(user, storedToken(token), {\n familyId,\n expiresAt,\n deviceInfo,\n });\n\n rememberPlainToken(row, token);\n\n return row;\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, { via: \"token\" });\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: plainTokenOf(refreshToken, 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, { via: \"token\" });\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, { via: \"refresh\" }))) 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: {\n overlapMs?: number;\n deviceInfo?: DeviceInfo;\n maxAgeMs?: number;\n /** The request being renewed, passed to the `auth.canAuthenticate` policy. */\n request?: Request;\n } = {},\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 (\n !user ||\n !(await this.canAuthenticate(user, { via: \"refresh\", request: options.request }))\n )\n 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 await this.parkAutomaticSuccessor(oldToken, successorAccess, pair, options.overlapMs);\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\n const storedAccess = access.get<string>(\"token\");\n const storedRefresh = refresh.get<string>(\"token\");\n\n if (!isTokenDigest(storedAccess) && !isTokenDigest(storedRefresh)) {\n return {\n accessToken: { token: storedAccess, expiresAt: access.get(\"expires_at\") },\n refreshToken: { token: storedRefresh, expiresAt: refresh.get(\"expires_at\") },\n };\n }\n\n // Hashed rows cannot hand the pair back; it was parked, encrypted, in the\n // cache for the overlap window. It must still match the linked rows.\n const parked = await this.readParkedSuccessor(oldToken);\n\n if (\n !parked?.refreshToken ||\n !storesToken(storedAccess, parked.accessToken.token) ||\n !storesToken(storedRefresh, parked.refreshToken.token)\n ) {\n return null;\n }\n\n return {\n accessToken: { token: parked.accessToken.token, expiresAt: access.get(\"expires_at\") },\n refreshToken: { token: parked.refreshToken.token, expiresAt: refresh.get(\"expires_at\") },\n };\n }\n\n /**\n * With hashed token rows, keep the successor pair (encrypted) in the cache\n * for the overlap window, so a duplicate renewal inside it can still receive\n * the same pair. Unhashed rows need nothing: the pair is read from them.\n * Best-effort: without a cache, a duplicate inside the window fails quietly.\n */\n private async parkAutomaticSuccessor(\n oldToken: RefreshToken,\n successorAccess: AccessToken,\n pair: TokenPair,\n overlapMs: number | undefined,\n ): Promise<void> {\n const window = this.automaticOverlapMs(overlapMs);\n\n if (window <= 0 || !isTokenDigest(successorAccess.get(\"token\"))) return;\n\n try {\n await cache.set(`${SUCCESSOR_PREFIX}${String(oldToken.id)}`, sealSuccessor(pair), {\n ttl: Math.max(1, Math.ceil(window / 1000)),\n });\n } catch (error) {\n log.error(\"auth\", \"renewal\", error);\n }\n }\n\n private async readParkedSuccessor(oldToken: RefreshToken): Promise<TokenPair | null> {\n try {\n return openSuccessor(await cache.get(`${SUCCESSOR_PREFIX}${String(oldToken.id)}`));\n } catch (error) {\n log.error(\"auth\", \"renewal\", error);\n\n return null;\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 * Look a user up by login identifiers: normalized first (see\n * `auth.normalizeCredentials`), then once more with the values as sent\n * (trimmed) when that differs, so legacy rows stored with capitals still match.\n */\n private async findLoginUser<T extends Auth>(\n Model: ChildModel<T>,\n identifiers: AuthIdentifiers,\n ): Promise<T | null> {\n const normalize = authConfig.normalizeCredentials();\n\n if (normalize === false) {\n return (await Model.first(identifiers)) as T | null;\n }\n\n const normalized = normalize(identifiers);\n const user = (await Model.first(normalized)) as T | null;\n\n if (user) return user;\n\n const asSent = trimIdentifiers(identifiers);\n\n if (JSON.stringify(asSent) === JSON.stringify(normalized)) return null;\n\n return (await Model.first(asSent)) as T | null;\n }\n\n /**\n * Check credentials and report WHY they failed, without emitting events or\n * touching the stored hash:\n *\n * - `{ type: \"ok\", user }`: the account exists, the password is right and\n * `auth.canAuthenticate` allows it.\n * - `{ type: \"invalid\" }`: unknown account or wrong password (both take the\n * same time, so the answer does not reveal which).\n * - `{ type: \"refused\", user }`: the password is right but\n * `auth.canAuthenticate` refuses the account (suspended, not yet approved).\n * Reveal this only after the correct password, as here.\n */\n public async verifyCredentials<T extends Auth>(\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n request?: Request,\n ): Promise<CredentialsVerification<T>> {\n const { reason: _reason, ...result } = await this.checkCredentials(Model, credentials, request);\n\n return result as CredentialsVerification<T>;\n }\n\n /** The shared check: `verifyCredentials` plus the reason `attemptLogin` reports in its event. */\n private async checkCredentials<T extends Auth>(\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n request?: Request,\n ): Promise<CredentialsVerification<T> & { reason?: string }> {\n const { password, ...otherData } = credentials;\n\n const user = await this.findLoginUser(Model, otherData);\n const storedHash = user?.string(\"password\");\n\n if (!user || !storedHash) {\n // Spend the same hashing work as a real check, so an unknown account\n // answers no faster than a wrong password.\n await dummyHash()\n .then((hash) => this.verifyPassword(String(password ?? \"\"), hash))\n .catch(() => false);\n\n return { type: \"invalid\", reason: user ? \"Invalid password\" : \"User not found\" };\n }\n\n if (!(await this.verifyPassword(password, storedHash))) {\n return { type: \"invalid\", reason: \"Invalid password\" };\n }\n\n if (!(await this.canAuthenticate(user, { via: \"password\", request }))) {\n return { type: \"refused\", user };\n }\n\n return { type: \"ok\", user };\n }\n\n /**\n * Resolve a user by credentials, verifying the password. Returns `null` on a\n * missing user, a wrong password or a refused account, emitting\n * `login.failed` either way. Use {@link verifyCredentials} to tell them apart.\n */\n public async attemptLogin<T extends Auth>(\n Model: ChildModel<T>,\n data: AuthCredentials,\n request?: Request,\n ): Promise<T | null> {\n const { password, ...otherData } = data;\n\n authEvents.emit(\"login.attempt\", otherData);\n\n const result = await this.checkCredentials(Model, data, request);\n\n if (result.type === \"invalid\") {\n authEvents.emit(\"login.failed\", otherData, result.reason ?? \"Invalid password\");\n\n return null;\n }\n\n if (result.type === \"refused\") {\n authEvents.emit(\"login.failed\", otherData, \"Authentication not allowed\");\n\n return null;\n }\n\n const user = result.user;\n const storedHash = user.string(\"password\") as string;\n\n await this.rehashPassword(user, String(password), storedHash);\n\n return user;\n }\n\n /**\n * After a successful password check, replace a hash that no longer matches\n * the configured algorithm or cost (`auth.rehashPasswords`, default on) with\n * a fresh one made from the password just verified. Never fails the login:\n * a problem is logged and the old hash keeps working.\n */\n private async rehashPassword(user: Auth, plainPassword: string, storedHash: string) {\n try {\n if (!authConfig.rehashPasswords() || !needsRehash(storedHash)) return;\n\n // Save a hash first. A model that hashes on save (`useHashedPassword()`)\n // would hash that again, so check what was stored and, if it no longer\n // verifies, save the plaintext for the model's own transformer.\n await user.merge({ password: await this.hashPassword(plainPassword) } as never).save();\n\n if (await this.verifyPassword(plainPassword, user.string(\"password\") ?? \"\")) return;\n\n await user.merge({ password: plainPassword } as never).save();\n } catch (error) {\n log.error(\"auth\", \"rehash-password\", error);\n }\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 request?: Request,\n ): Promise<LoginResult<T> | null> {\n const user = await this.attemptLogin(Model, credentials, request);\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 * `context` is passed to the policy: `via` names the login method (default\n * `\"custom\"`) and `request` is the request being served, when there is one.\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 context?: Partial<AuthenticationContext>,\n ): Promise<LoginResult<T>> {\n await this.assertCanAuthenticate(user, { ...context, via: context?.via ?? \"custom\" });\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, request);\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\". Durable families are ensured together\n * and revoked with one update, refresh tokens with another; a\n * `token.familyRevoked` event fires per family (and `token.revoked` for a\n * token outside any durable family).\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 // Every rotation leaves a row behind, so the rows outnumber the families\n // by far: ensure the distinct families together, with one read and one\n // insert for the missing ones.\n const familyIds = new Set(existingRows.map((token) => token.familyId).filter(Boolean));\n\n await AuthTokenFamily.ensureMany(user, [...familyIds]);\n\n const families = await AuthTokenFamily.activeFor(user);\n const revokedFamilyIds = families.map((family) => family.get<string>(\"family_id\"));\n\n // One update revokes every family, which also fences out a rotation in flight.\n if (revokedFamilyIds.length > 0) await AuthTokenFamily.revokeAllFor(user);\n\n // One update revokes every refresh token; the rows read just before it say\n // which family each belonged to, for the per-family events.\n const revokedTokens = await this.refreshTokenModel.revokeAllFor(user);\n const tokensByFamily = new Map<string, RefreshToken[]>();\n const unfamilied: RefreshToken[] = [];\n\n for (const token of revokedTokens) {\n const familyId = token.familyId;\n\n if (familyId && revokedFamilyIds.includes(familyId)) {\n tokensByFamily.set(familyId, [...(tokensByFamily.get(familyId) ?? []), token]);\n } else {\n unfamilied.push(token);\n }\n }\n\n for (const familyId of revokedFamilyIds) {\n authEvents.emit(\"token.familyRevoked\", familyId, tokensByFamily.get(familyId) ?? []);\n }\n\n // Rows without an active durable family (created before the additive\n // migration ran) are reported one by one.\n for (const token of unfamilied) {\n authEvents.emit(\"token.revoked\", user, token);\n }\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 = authCookieWriteName(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 const hostOnly = name.startsWith(HOST_COOKIE_PREFIX);\n\n assertHostPrefixAllowed(name, { path, domain: options.domain });\n\n response.cookie(name, tokenValue, {\n raw: true,\n path,\n ...(hostOnly ? { secure: true } : {}),\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 path = options.path ?? authConfig.cookie.path();\n const domain = this.cookieDomainFor(\"clearAuthCookie\", request);\n\n for (const name of authCookieNames(options.name ?? authConfig.cookie.name())) {\n if (name.startsWith(HOST_COOKIE_PREFIX)) {\n response.clearCookie(name, { path: \"/\", secure: true });\n continue;\n }\n\n if (domain !== undefined) {\n response.clearCookie(name, { path, domain });\n }\n\n response.clearCookie(name, { path });\n }\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 [authCookieWriteName(authConfig.cookie.name()), tokens.accessToken],\n [authCookieWriteName(authConfig.cookie.refreshName()), tokens.refreshToken],\n ] as const;\n\n for (const [name, token] of cookies) {\n const maxAge = this.cookieMaxAgeFromToken(token);\n const hostOnly = name.startsWith(HOST_COOKIE_PREFIX);\n\n assertHostPrefixAllowed(name, { path: \"/\", domain });\n\n response.cookie(name, token.token, {\n raw: true,\n httpOnly: true,\n sameSite: \"lax\",\n path: \"/\",\n ...(hostOnly ? { secure: true } : {}),\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 const names = [\n ...authCookieNames(authConfig.cookie.name()),\n ...authCookieNames(authConfig.cookie.refreshName()),\n ];\n\n for (const name of names) {\n if (name.startsWith(HOST_COOKIE_PREFIX)) {\n response.clearCookie(name, { path: \"/\", secure: true });\n continue;\n }\n\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":";;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,mCAAb,cAAsD,MAAM;CAC1D,AAAO,YAAY,QAAgB;EACjC,MACE,GAAG,OAAO,+HACZ;EACA,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAI;AAEJ,SAAS,YAA6B;CACpC,sBAAsB,QAAQ,QAAQ,CAAC,CACpC,WAAW,aAAa,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,CACzD,OAAO,UAAmB;EACzB,oBAAoB;EACpB,MAAM;CACR,CAAC;CAEH,OAAO;AACT;;AAGA,SAAS,YAAY,OAAuB;CAC1C,OAAO,WAAW,iBAAiB,IAAI,YAAY,KAAK,IAAI;AAC9D;;AAGA,SAAS,YAAY,QAAiB,OAAyB;CAC7D,OAAO,OAAO,UAAU,aAAa,WAAW,SAAS,WAAW,YAAY,KAAK;AACvF;AAEA,MAAM,mBAAmB;;AAGzB,SAAS,eAAuB;CAC9B,OAAO,WAAW,UAAU,WAAW,YAAY,OAAO,CAAC,CAAC,CACzD,OAAO,oCAAoC,CAAC,CAC5C,OAAO;AACZ;AAEA,SAAS,cAAc,MAAyB;CAC9C,MAAM,KAAK,YAAY,EAAE;CACzB,MAAM,SAAS,eAAe,eAAe,aAAa,GAAG,EAAE;CAC/D,MAAM,OAAO,OAAO,OAAO,CAAC,OAAO,OAAO,KAAK,UAAU,IAAI,GAAG,MAAM,GAAG,OAAO,MAA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IACL,UAAU;IACV,UAAU;IACV,MAAM;IACN,GAAI,WAAW,EAAE,QAAQ,KAAK,IAAI,CAAC;IACnC,GAAI,WAAW,SAAY,EAAE,OAAO,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;EAClE,MAAM,QAAQ,CACZ,GAAG,gBAAgB,WAAW,OAAO,KAAK,CAAC,GAC3C,GAAG,gBAAgB,WAAW,OAAO,YAAY,CAAC,CACpD;EAEA,KAAK,MAAM,QAAQ,OAAO;GACxB,IAAI,KAAK,oBAA6B,GAAG;IACvC,SAAS,YAAY,MAAM;KAAE,MAAM;KAAK,QAAQ;IAAK,CAAC;IACtD;GACF;GAEA,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 +1 @@
1
- {"version":3,"file":"resolve-request-user.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/resolve-request-user.ts"],"mappings":";;;YAiBY;;EAEV,YAAY;;EAEZ,oBAAoB;;EAEpB;;EAEA;;EAEA;;EAEA;;EAEA,eAAe;;;;;;YAOL;YAEA,mBAAmB;EACzB,MAAM;EAAO;;EACb;EAAY,SAAS;;;wBA+BX,eAAe,SAAS,SAAS,WAAW;;;;;;;;;;;;wBAmBtC,0BACpB,SAAS,SACT,UAAU,UACV,UAAS,4BACR,QAAQ;;;;;;;;wBA6HK,mBACd,SAAS,SACT,UAAU,UACV,UAAS,4BACR"}
1
+ {"version":3,"file":"resolve-request-user.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/resolve-request-user.ts"],"mappings":";;;YAiBY;;EAEV,YAAY;;EAEZ,oBAAoB;;EAEpB;;EAEA;;EAEA;;EAEA;;EAEA,eAAe;;;;;;YAOL;YAEA,mBAAmB;EACzB,MAAM;EAAO;;EACb;EAAY,SAAS;;;wBA+BX,eAAe,SAAS,SAAS,WAAW;;;;;;;;;;;;wBAmBtC,0BACpB,SAAS,SACT,UAAU,UACV,UAAS,4BACR,QAAQ;;;;;;;;wBA8HK,mBACd,SAAS,SACT,UAAU,UACV,UAAS,4BACR"}
@@ -62,7 +62,8 @@ async function resolveRequestUserOutcome(request, response, options = {}) {
62
62
  if (!refreshToken) return false;
63
63
  const pair = await authService.renewAutomaticSession(refreshToken, renewalUserType, {
64
64
  overlapMs: options.overlapMs,
65
- maxAgeMs: options.maxAgeMs
65
+ maxAgeMs: options.maxAgeMs,
66
+ request
66
67
  });
67
68
  if (!pair?.refreshToken) return false;
68
69
  authService.setAuthCookie(response, pair.accessToken, {
@@ -132,7 +133,10 @@ async function resolveRequestUserOutcome(request, response, options = {}) {
132
133
  await accessToken.destroy();
133
134
  return fail("invalid");
134
135
  }
135
- if (!await authService.canAuthenticate(currentUser)) return fail("unauthorized");
136
+ if (!await authService.canAuthenticate(currentUser, {
137
+ via: "token",
138
+ request
139
+ })) return fail("unauthorized");
136
140
  return { user: currentUser };
137
141
  }
138
142
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-request-user.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/resolve-request-user.ts"],"sourcesContent":["import { config, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport type { CookieDomainResolver, TokenFrom } from \"../contracts/types\";\nimport { AccessToken } from \"../models/access-token\";\nimport { readAuthCookie } from \"./auth-cookie-names\";\nimport { authService } from \"./auth.service\";\nimport { isInvalidCredentialError, jwt } from \"./jwt\";\n\n/**\n * Decoded access-token claims the resolver reads. The full payload carries\n * more (`created_at`, `tokenType`, `iat`, `exp`) but only these drive routing.\n */\ntype DecodedAccessToken = {\n id: string | number;\n userType?: string;\n};\n\nexport type ResolveRequestUserOptions = {\n /** Where the access token is read from. Defaults to `\"header\"`. */\n tokenFrom?: TokenFrom;\n /** Refresh credential source; enables one automatic renewal per call. */\n refreshCredential?: TokenFrom;\n /** Refresh overlap window forwarded to `authService.renewAutomaticSession`. */\n overlapMs?: number;\n /** User types allowed to pass. Empty means any authenticated type. */\n allowedTypes?: string[];\n /** Absolute family lifetime in ms; rotation never extends a family past it. */\n maxAgeMs?: number;\n /** The single user type a renewal mints for. Required for renewal. */\n renewalUserType?: string;\n /** Select a request-scoped Domain for renewed cookies. */\n cookieDomain?: CookieDomainResolver;\n};\n\n/**\n * Why a request did not resolve to a user. The middleware maps each reason to\n * its own response; `resolveRequestUser` collapses them all to `null`.\n */\nexport type RequestUserFailure = \"missing\" | \"invalid\" | \"forbidden\" | \"unauthorized\";\n\nexport type RequestUserOutcome<TUser = any> =\n | { user: TUser; failure?: undefined }\n | { user: null; failure: RequestUserFailure };\n\n/**\n * Whether the persisted row says the token is dead.\n *\n * The answer belongs to the model (`AccessToken.isExpired`), so a registered\n * override that renames or reshapes its expiry column stays authoritative. A\n * row that cannot answer at all — an override that dropped the getter — is\n * treated as **expired**: a check must never quietly answer \"fine\" when it has\n * nothing to check.\n *\n * This is independent of the `exp` claim required by `jwt.verify`: that guard\n * catches a token whose *claims* carry no deadline; this one catches a token\n * whose *row* says the deadline has passed.\n */\nfunction accessTokenRowIsExpired(accessToken: AccessToken): boolean {\n return typeof accessToken.isExpired === \"boolean\" ? accessToken.isExpired : true;\n}\n\n/**\n * Whether the token's claims name the user its row was issued to. The row is\n * what proves the token was issued and not revoked; the user it resolves to\n * must be that row's user too, never only what the claims say.\n */\nfunction claimsMatchRow(decoded: DecodedAccessToken, accessToken: AccessToken): boolean {\n if (String(decoded.id) !== String(accessToken.userId)) return false;\n\n return decoded.userType === undefined || decoded.userType === accessToken.userType;\n}\n\n/** Read one credential (access or refresh) from the header or a cookie. */\nexport function readCredential(request: Request, tokenFrom: TokenFrom): string {\n if (tokenFrom === \"header\") {\n return request.authorizationValue;\n }\n\n return readAuthCookie(request, tokenFrom.slice(\"cookie:\".length));\n}\n\n/**\n * Resolve a request's credential to a user, reporting WHY it failed.\n *\n * Side effects match what `authMiddleware` always did: `request.locals.user` is\n * cleared on every failure, `request.decodedAccessToken` is set once a token\n * verifies, and stale rows are destroyed. It does NOT set `request.locals.user`\n * on success — the caller decides that.\n *\n * At most one renewal is attempted per call. The renewed access token is\n * checked through the same path; no handler or unsafe request replay happens.\n */\nexport async function resolveRequestUserOutcome(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<RequestUserOutcome> {\n const tokenFrom = options.tokenFrom ?? \"header\";\n const allowedTypes = options.allowedTypes ?? [];\n const { refreshCredential } = options;\n let authorizationValue = readCredential(request, tokenFrom);\n let renewalAttempted = false;\n\n const renew = async (): Promise<boolean> => {\n const { renewalUserType } = options;\n if (!refreshCredential || !renewalUserType || renewalAttempted) return false;\n\n renewalAttempted = true;\n const refreshToken = readCredential(request, refreshCredential);\n if (!refreshToken) return false;\n\n const pair = await authService.renewAutomaticSession(refreshToken, renewalUserType, {\n overlapMs: options.overlapMs,\n maxAgeMs: options.maxAgeMs,\n });\n if (!pair?.refreshToken) return false;\n\n authService.setAuthCookie(response, pair.accessToken, {\n name: tokenFrom.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authService.setAuthCookie(response, pair.refreshToken, {\n name: refreshCredential.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authorizationValue = pair.accessToken.token;\n\n return true;\n };\n\n const fail = (failure: RequestUserFailure): RequestUserOutcome => {\n request.locals.user = undefined;\n\n return { user: null, failure };\n };\n\n let decoded: DecodedAccessToken;\n let accessToken: AccessToken | null;\n\n while (true) {\n if (!authorizationValue) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"missing\");\n }\n\n try {\n decoded = await jwt.verify<DecodedAccessToken>(authorizationValue);\n } catch (error) {\n if (!isInvalidCredentialError(error)) throw error;\n // An expired or garbage token is an ordinary client error that any\n // anonymous caller can produce at will: debug, so it cannot flood the\n // error log.\n log.debug(\"http\", \"auth\", error);\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n request.decodedAccessToken = decoded;\n const AccessTokenModel = config.key(\"auth.accessToken.model\", AccessToken);\n accessToken = await AccessTokenModel.findByToken(authorizationValue);\n\n if (!accessToken) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n if (accessTokenRowIsExpired(accessToken)) {\n await accessToken.destroy();\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n if (!claimsMatchRow(decoded, accessToken)) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n break;\n }\n\n const userType = decoded.userType ?? accessToken.userType;\n\n if (allowedTypes.length && !allowedTypes.includes(userType)) {\n return { user: null, failure: \"forbidden\" };\n }\n\n const UserModel = config.key(`auth.userType.${userType}`);\n\n if (!UserModel) {\n // Configuration, not credentials. Throwing keeps a mis-registered app\n // loudly broken instead of quietly rejecting every request of this type.\n throw new Error(`User type ${userType} is unknown type.`);\n }\n\n const currentUser = await UserModel.find(decoded.id);\n\n if (!currentUser) {\n await accessToken.destroy();\n\n return fail(\"invalid\");\n }\n\n if (!(await authService.canAuthenticate(currentUser))) {\n return fail(\"unauthorized\");\n }\n\n return { user: currentUser };\n}\n\n/**\n * Resolve the request's credential to its user model, or `null` when there is\n * none (missing, invalid, expired, wrong type, or not allowed to authenticate).\n *\n * Includes the middleware's automatic renewal when `options.refreshCredential`\n * is set. Use `resolveRequestUserOutcome` when the failure reason matters.\n */\nexport function resolveRequestUser(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<any> {\n // Single-flight: the PROMISE is stored, so concurrent and repeat callers in\n // one request share one verify, one lookup and at most one renewal. The first\n // caller's options win for the rest of the request.\n if (!request.locals.session) {\n request.locals.session = resolveRequestUserO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AI,CAAC,WAGH,MAAM,IAAI,MAAM,aAAa,SAAS,kBAAkB;CAG1D,MAAM,cAAc,MAAM,UAAU,KAAK,QAAQ,EAAE;CAEnD,IAAI,CAAC,aAAa;EAChB,MAAM,YAAY,QAAQ;EAE1B,OAAO,KAAK,SAAS;CACvB;CAEA,IAAI,CAAE,MAAM,YAAY,gBAAgB,WAAW,GACjD,OAAO,KAAK,cAAc;CAG5B,OAAO,EAAE,MAAM,YAAY;AAC7B;;;;;;;;AASA,SAAgB,mBACd,SACA,UACA,UAAqC,CAAC,GACxB;CAId,IAAI,CAAC,QAAQ,OAAO,SAClB,QAAQ,OAAO,UAAU,0BAA0B,SAAS,UAAU,OAAO,CAAC,CAAC,MAC5E,YAAY,QAAQ,IACvB;CAGF,OAAO,QAAQ,OAAO;AACxB"}
1
+ {"version":3,"file":"resolve-request-user.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/resolve-request-user.ts"],"sourcesContent":["import { config, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport type { CookieDomainResolver, TokenFrom } from \"../contracts/types\";\nimport { AccessToken } from \"../models/access-token\";\nimport { readAuthCookie } from \"./auth-cookie-names\";\nimport { authService } from \"./auth.service\";\nimport { isInvalidCredentialError, jwt } from \"./jwt\";\n\n/**\n * Decoded access-token claims the resolver reads. The full payload carries\n * more (`created_at`, `tokenType`, `iat`, `exp`) but only these drive routing.\n */\ntype DecodedAccessToken = {\n id: string | number;\n userType?: string;\n};\n\nexport type ResolveRequestUserOptions = {\n /** Where the access token is read from. Defaults to `\"header\"`. */\n tokenFrom?: TokenFrom;\n /** Refresh credential source; enables one automatic renewal per call. */\n refreshCredential?: TokenFrom;\n /** Refresh overlap window forwarded to `authService.renewAutomaticSession`. */\n overlapMs?: number;\n /** User types allowed to pass. Empty means any authenticated type. */\n allowedTypes?: string[];\n /** Absolute family lifetime in ms; rotation never extends a family past it. */\n maxAgeMs?: number;\n /** The single user type a renewal mints for. Required for renewal. */\n renewalUserType?: string;\n /** Select a request-scoped Domain for renewed cookies. */\n cookieDomain?: CookieDomainResolver;\n};\n\n/**\n * Why a request did not resolve to a user. The middleware maps each reason to\n * its own response; `resolveRequestUser` collapses them all to `null`.\n */\nexport type RequestUserFailure = \"missing\" | \"invalid\" | \"forbidden\" | \"unauthorized\";\n\nexport type RequestUserOutcome<TUser = any> =\n | { user: TUser; failure?: undefined }\n | { user: null; failure: RequestUserFailure };\n\n/**\n * Whether the persisted row says the token is dead.\n *\n * The answer belongs to the model (`AccessToken.isExpired`), so a registered\n * override that renames or reshapes its expiry column stays authoritative. A\n * row that cannot answer at all — an override that dropped the getter — is\n * treated as **expired**: a check must never quietly answer \"fine\" when it has\n * nothing to check.\n *\n * This is independent of the `exp` claim required by `jwt.verify`: that guard\n * catches a token whose *claims* carry no deadline; this one catches a token\n * whose *row* says the deadline has passed.\n */\nfunction accessTokenRowIsExpired(accessToken: AccessToken): boolean {\n return typeof accessToken.isExpired === \"boolean\" ? accessToken.isExpired : true;\n}\n\n/**\n * Whether the token's claims name the user its row was issued to. The row is\n * what proves the token was issued and not revoked; the user it resolves to\n * must be that row's user too, never only what the claims say.\n */\nfunction claimsMatchRow(decoded: DecodedAccessToken, accessToken: AccessToken): boolean {\n if (String(decoded.id) !== String(accessToken.userId)) return false;\n\n return decoded.userType === undefined || decoded.userType === accessToken.userType;\n}\n\n/** Read one credential (access or refresh) from the header or a cookie. */\nexport function readCredential(request: Request, tokenFrom: TokenFrom): string {\n if (tokenFrom === \"header\") {\n return request.authorizationValue;\n }\n\n return readAuthCookie(request, tokenFrom.slice(\"cookie:\".length));\n}\n\n/**\n * Resolve a request's credential to a user, reporting WHY it failed.\n *\n * Side effects match what `authMiddleware` always did: `request.locals.user` is\n * cleared on every failure, `request.decodedAccessToken` is set once a token\n * verifies, and stale rows are destroyed. It does NOT set `request.locals.user`\n * on success — the caller decides that.\n *\n * At most one renewal is attempted per call. The renewed access token is\n * checked through the same path; no handler or unsafe request replay happens.\n */\nexport async function resolveRequestUserOutcome(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<RequestUserOutcome> {\n const tokenFrom = options.tokenFrom ?? \"header\";\n const allowedTypes = options.allowedTypes ?? [];\n const { refreshCredential } = options;\n let authorizationValue = readCredential(request, tokenFrom);\n let renewalAttempted = false;\n\n const renew = async (): Promise<boolean> => {\n const { renewalUserType } = options;\n if (!refreshCredential || !renewalUserType || renewalAttempted) return false;\n\n renewalAttempted = true;\n const refreshToken = readCredential(request, refreshCredential);\n if (!refreshToken) return false;\n\n const pair = await authService.renewAutomaticSession(refreshToken, renewalUserType, {\n overlapMs: options.overlapMs,\n maxAgeMs: options.maxAgeMs,\n request,\n });\n if (!pair?.refreshToken) return false;\n\n authService.setAuthCookie(response, pair.accessToken, {\n name: tokenFrom.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authService.setAuthCookie(response, pair.refreshToken, {\n name: refreshCredential.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authorizationValue = pair.accessToken.token;\n\n return true;\n };\n\n const fail = (failure: RequestUserFailure): RequestUserOutcome => {\n request.locals.user = undefined;\n\n return { user: null, failure };\n };\n\n let decoded: DecodedAccessToken;\n let accessToken: AccessToken | null;\n\n while (true) {\n if (!authorizationValue) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"missing\");\n }\n\n try {\n decoded = await jwt.verify<DecodedAccessToken>(authorizationValue);\n } catch (error) {\n if (!isInvalidCredentialError(error)) throw error;\n // An expired or garbage token is an ordinary client error that any\n // anonymous caller can produce at will: debug, so it cannot flood the\n // error log.\n log.debug(\"http\", \"auth\", error);\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n request.decodedAccessToken = decoded;\n const AccessTokenModel = config.key(\"auth.accessToken.model\", AccessToken);\n accessToken = await AccessTokenModel.findByToken(authorizationValue);\n\n if (!accessToken) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n if (accessTokenRowIsExpired(accessToken)) {\n await accessToken.destroy();\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n if (!claimsMatchRow(decoded, accessToken)) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n break;\n }\n\n const userType = decoded.userType ?? accessToken.userType;\n\n if (allowedTypes.length && !allowedTypes.includes(userType)) {\n return { user: null, failure: \"forbidden\" };\n }\n\n const UserModel = config.key(`auth.userType.${userType}`);\n\n if (!UserModel) {\n // Configuration, not credentials. Throwing keeps a mis-registered app\n // loudly broken instead of quietly rejecting every request of this type.\n throw new Error(`User type ${userType} is unknown type.`);\n }\n\n const currentUser = await UserModel.find(decoded.id);\n\n if (!currentUser) {\n await accessToken.destroy();\n\n return fail(\"invalid\");\n }\n\n if (!(await authService.canAuthenticate(currentUser, { via: \"token\", request }))) {\n return fail(\"unauthorized\");\n }\n\n return { user: currentUser };\n}\n\n/**\n * Resolve the request's credential to its user model, or `null` when there is\n * none (missing, invalid, expired, wrong type, or not allowed to authenticate).\n *\n * Includes the middleware's automatic renewal when `options.refreshCredential`\n * is set. Use `resolveRequestUserOutcome` when the failure reason matters.\n */\nexport function resolveRequestUser(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<any> {\n // Single-flight: the PROMISE is stored, so concurrent and repeat callers in\n // one request share one verify, one lookup and at most one renewal. The first\n // caller's options win for the rest of the request.\n if (!request.locals.session) {\n request.locals.session = resolveRequestUserOutcome(request, response, options).then(\n (outcome) => outcome.user,\n );\n }\n\n return request.locals.session;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAS,wBAAwB,aAAmC;CAClE,OAAO,OAAO,YAAY,cAAc,YAAY,YAAY,YAAY;AAC9E;;;;;;AAOA,SAAS,eAAe,SAA6B,aAAmC;CACtF,IAAI,OAAO,QAAQ,EAAE,MAAM,OAAO,YAAY,MAAM,GAAG,OAA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AAK,cAAc;CAG5B,OAAO,EAAE,MAAM,YAAY;AAC7B;;;;;;;;AASA,SAAgB,mBACd,SACA,UACA,UAAqC,CAAC,GACxB;CAId,IAAI,CAAC,QAAQ,OAAO,SAClB,QAAQ,OAAO,UAAU,0BAA0B,SAAS,UAAU,OAAO,CAAC,CAAC,MAC5E,YAAY,QAAQ,IACvB;CAGF,OAAO,QAAQ,OAAO;AACxB"}
package/llms-full.txt CHANGED
@@ -512,7 +512,7 @@ abstract class Auth<TSchema> extends Model<TSchema> implements Authenticable {
512
512
  }
513
513
  ```
514
514
 
515
- `userType` is the only required override (an abstract getter — return the type slug). Override `generateAccessToken` if you need a non-default payload.
515
+ `userType` is the only required override (an abstract getter — return the type slug). Override `accessTokenPayload()` to add claims: every access token for the user (login, refresh, automatic renewal) is built from it, with `id`, `userType` and `jti` always set from the user. A one-off `deviceInfo.payload` at login is merged over it but is not stored, so a refresh does not carry it; durable claims belong in `accessTokenPayload()`.
516
516
 
517
517
  `Auth` implements the `Authenticable` contract — that interface mirrors exactly these methods (`userType`, `generateAccessToken`, `generateRefreshToken`, `createTokenPair`, `confirmPassword`), so the class fails to compile if it drifts from the contract. Use `confirmPassword(plaintext)` to check a password against the stored hash (e.g. a "confirm current password" step).
518
518
 
@@ -619,6 +619,10 @@ Identifiers are normalized before the lookup: string values are trimmed and `ema
619
619
 
620
620
  For lower-level credential verification (just check, don't issue tokens), use `authService.attemptLogin(Model, credentials)` — returns the user or null without creating tokens.
621
621
 
622
+ To tell a wrong password from an account the policy refuses, use `authService.verifyCredentials(Model, credentials, request?)`. It returns a `CredentialsVerification`: `{ type: "ok", user }`, `{ type: "invalid" }` (unknown account or wrong password, same timing) or `{ type: "refused", user }` (right password, `auth.canAuthenticate` said no). It emits no events and does not rehash.
623
+
624
+ `auth.canAuthenticate(user, context?)` receives an `AuthenticationContext`: `{ via: AuthenticationMethod; request?: Request }`, where `via` is `"password" | "otp" | "passkey" | "oauth" | "token" | "refresh" | "custom"`. The request is present wherever the call site has one (`login(Model, credentials, deviceInfo, request)`, `authMiddleware`, provider and passkey login, `verifyOtp(..., request)`, automatic renewal); a refresh by token string has none. A policy taking only `(user)` still works.
625
+
622
626
  ## Device info
623
627
 
624
628
  The optional `deviceInfo` carries metadata into the refresh token row:
@@ -750,7 +754,7 @@ const { user, tokens } = await completeProviderLogin(User, "google", request, re
750
754
  authService.setAuthCookie(response, tokens.accessToken); // cookie session, or return tokens as JSON
751
755
  ```
752
756
 
753
- `authService.completeLogin(user, deviceInfo?)` is that shared ending. It applies `auth.canAuthenticate` (403) and issues tokens. Call it only for a user you have already authenticated.
757
+ `authService.completeLogin(user, deviceInfo?)` is that shared ending. It applies `auth.canAuthenticate` (403) and issues tokens. A third argument `{ via, request }` (an `AuthenticationContext`) is handed to the policy; the provider, passkey and OTP helpers set it for you (`verifyOtp(Model, phone, code, deviceInfo?, request?)` takes the request). Call it only for a user you have already authenticated.
754
758
 
755
759
  ## Install
756
760
 
@@ -1129,7 +1133,7 @@ const pair = await authService.createTokenPair(user, deviceInfo);
1129
1133
 
1130
1134
  `createTokenPair` is the typical issuance path. It respects `config.auth.refreshToken.enabled` — if disabled, returns only `accessToken`.
1131
1135
 
1132
- A custom `payload` (`generateAccessToken(user, payload)` / `deviceInfo.payload`) may add claims, but `id` and `userType` are always stamped from `user`; the route gate also refuses a token whose claims name a different user than its row.
1136
+ Claims come from the user model's `accessTokenPayload()` on every issue, refresh and renewal. A custom `payload` (`generateAccessToken(user, payload)` / `deviceInfo.payload`) is merged over them and is not stored for later refreshes. It may add claims, but `id` and `userType` are always stamped from `user`; the route gate also refuses a token whose claims name a different user than its row.
1133
1137
 
1134
1138
  With `auth.hashTokensAtRest: true` the token columns hold SHA-256 digests. `createTokenPair` / `login` still return the raw tokens; the row `createRefreshToken` returns exposes its raw token as `row.plainToken` (`row.get("token")` is the digest).
1135
1139
 
package/package.json CHANGED
@@ -12,13 +12,13 @@
12
12
  "ms": "^2.1.3"
13
13
  },
14
14
  "peerDependencies": {
15
- "@warlock.js/fs": "5.64.0",
16
- "@warlock.js/cache": "5.64.0",
17
- "@warlock.js/cascade": "5.64.0",
18
- "@warlock.js/core": "5.64.0",
19
- "@warlock.js/logger": "5.64.0",
20
- "@warlock.js/seal": "5.64.0",
21
- "@warlock.js/notifications": "5.64.0",
15
+ "@warlock.js/fs": "5.65.0",
16
+ "@warlock.js/cache": "5.65.0",
17
+ "@warlock.js/cascade": "5.65.0",
18
+ "@warlock.js/core": "5.65.0",
19
+ "@warlock.js/logger": "5.65.0",
20
+ "@warlock.js/seal": "5.65.0",
21
+ "@warlock.js/notifications": "5.65.0",
22
22
  "@simplewebauthn/server": "^13.1.0",
23
23
  "jose": "^6.1.0"
24
24
  },
@@ -48,7 +48,7 @@
48
48
  ],
49
49
  "author": "hassanzohdy",
50
50
  "license": "MIT",
51
- "version": "5.64.0",
51
+ "version": "5.65.0",
52
52
  "type": "module",
53
53
  "main": "./esm/index.mjs",
54
54
  "module": "./esm/index.mjs",
@@ -152,7 +152,7 @@ abstract class Auth<TSchema> extends Model<TSchema> implements Authenticable {
152
152
  }
153
153
  ```
154
154
 
155
- `userType` is the only required override (an abstract getter — return the type slug). Override `generateAccessToken` if you need a non-default payload.
155
+ `userType` is the only required override (an abstract getter — return the type slug). Override `accessTokenPayload()` to add claims: every access token for the user (login, refresh, automatic renewal) is built from it, with `id`, `userType` and `jti` always set from the user. A one-off `deviceInfo.payload` at login is merged over it but is not stored, so a refresh does not carry it; durable claims belong in `accessTokenPayload()`.
156
156
 
157
157
  `Auth` implements the `Authenticable` contract — that interface mirrors exactly these methods (`userType`, `generateAccessToken`, `generateRefreshToken`, `createTokenPair`, `confirmPassword`), so the class fails to compile if it drifts from the contract. Use `confirmPassword(plaintext)` to check a password against the stored hash (e.g. a "confirm current password" step).
158
158
 
@@ -85,6 +85,10 @@ Identifiers are normalized before the lookup: string values are trimmed and `ema
85
85
 
86
86
  For lower-level credential verification (just check, don't issue tokens), use `authService.attemptLogin(Model, credentials)` — returns the user or null without creating tokens.
87
87
 
88
+ To tell a wrong password from an account the policy refuses, use `authService.verifyCredentials(Model, credentials, request?)`. It returns a `CredentialsVerification`: `{ type: "ok", user }`, `{ type: "invalid" }` (unknown account or wrong password, same timing) or `{ type: "refused", user }` (right password, `auth.canAuthenticate` said no). It emits no events and does not rehash.
89
+
90
+ `auth.canAuthenticate(user, context?)` receives an `AuthenticationContext`: `{ via: AuthenticationMethod; request?: Request }`, where `via` is `"password" | "otp" | "passkey" | "oauth" | "token" | "refresh" | "custom"`. The request is present wherever the call site has one (`login(Model, credentials, deviceInfo, request)`, `authMiddleware`, provider and passkey login, `verifyOtp(..., request)`, automatic renewal); a refresh by token string has none. A policy taking only `(user)` still works.
91
+
88
92
  ## Device info
89
93
 
90
94
  The optional `deviceInfo` carries metadata into the refresh token row:
@@ -12,7 +12,7 @@ const { user, tokens } = await completeProviderLogin(User, "google", request, re
12
12
  authService.setAuthCookie(response, tokens.accessToken); // cookie session, or return tokens as JSON
13
13
  ```
14
14
 
15
- `authService.completeLogin(user, deviceInfo?)` is that shared ending. It applies `auth.canAuthenticate` (403) and issues tokens. Call it only for a user you have already authenticated.
15
+ `authService.completeLogin(user, deviceInfo?)` is that shared ending. It applies `auth.canAuthenticate` (403) and issues tokens. A third argument `{ via, request }` (an `AuthenticationContext`) is handed to the policy; the provider, passkey and OTP helpers set it for you (`verifyOtp(Model, phone, code, deviceInfo?, request?)` takes the request). Call it only for a user you have already authenticated.
16
16
 
17
17
  ## Install
18
18
 
@@ -36,7 +36,7 @@ const pair = await authService.createTokenPair(user, deviceInfo);
36
36
 
37
37
  `createTokenPair` is the typical issuance path. It respects `config.auth.refreshToken.enabled` — if disabled, returns only `accessToken`.
38
38
 
39
- A custom `payload` (`generateAccessToken(user, payload)` / `deviceInfo.payload`) may add claims, but `id` and `userType` are always stamped from `user`; the route gate also refuses a token whose claims name a different user than its row.
39
+ Claims come from the user model's `accessTokenPayload()` on every issue, refresh and renewal. A custom `payload` (`generateAccessToken(user, payload)` / `deviceInfo.payload`) is merged over them and is not stored for later refreshes. It may add claims, but `id` and `userType` are always stamped from `user`; the route gate also refuses a token whose claims name a different user than its row.
40
40
 
41
41
  With `auth.hashTokensAtRest: true` the token columns hold SHA-256 digests. `createTokenPair` / `login` still return the raw tokens; the row `createRefreshToken` returns exposes its raw token as `row.plainToken` (`row.get("token")` is the digest).
42
42