@warlock.js/auth 5.51.0 → 5.52.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.
- package/CHANGELOG.md +10 -0
- package/esm/contracts/index.d.mts +2 -2
- package/esm/contracts/types.d.mts +18 -0
- package/esm/contracts/types.d.mts.map +1 -1
- package/esm/contracts/types.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
- package/esm/middleware/login-throttle.middleware.mjs +2 -1
- package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
- package/esm/services/auth-config.mjs +3 -0
- package/esm/services/auth-config.mjs.map +1 -1
- package/esm/services/auth.service.d.mts +6 -0
- package/esm/services/auth.service.d.mts.map +1 -1
- package/esm/services/auth.service.mjs +17 -1
- package/esm/services/auth.service.mjs.map +1 -1
- package/esm/utils/normalize-credentials.mjs +32 -0
- package/esm/utils/normalize-credentials.mjs.map +1 -0
- package/llms-full.txt +2 -0
- package/package.json +8 -8
- package/skills/handle-login-and-logout/SKILL.md +2 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,16 @@ All notable changes to `@warlock.js/auth` are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `@warlock.js/*` packages are released in lockstep — every package shares the same version number, so a version below may list only the changes that affected this package.
|
|
6
6
|
|
|
7
|
+
## 5.52.0 - 2026-11-11
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `auth.normalizeCredentials` config option: a function `(identifiers) => identifiers` that rewrites login identifiers before the lookup, or `false` for exact matching. Exports the `NormalizeCredentials` type.
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- Email sign-in is no longer case- and whitespace-sensitive. `authService.login()`, `attemptLogin()` and `loginWithSessionCookies()` trim identifier values and lower-case `email` before the lookup, so `Sara@x.io` finds `sara@x.io`. When nothing matches, the lookup is retried once with the value as sent (trimmed), so accounts stored with capitals keep working. The login throttle uses the same normalization, so its bucket and the account lookup always agree.
|
|
16
|
+
|
|
7
17
|
## 5.35.0 - 2026-10-21
|
|
8
18
|
|
|
9
19
|
### Fixed
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AppleProviderConfig, AuthProvider, DiscordProviderConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LinkedInProviderConfig, OtpConfig, OtpMessage, OtpSender, PasskeysConfig, ProviderAuthorizationState, ProviderCallbackParams, ProviderProfile, ProviderUserCreator, ProvidersConfig, XProviderConfig } from "./providers.mjs";
|
|
2
|
-
import { AccessTokenConfig, AccessTokenOutput, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthRefreshCredentialDescriptor, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, EmailVerificationConfig, LegacyJwtConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, PageAuthConfig, PasswordResetConfig, PasswordSetter, RefreshTokenConfig, SetAuthCookieOptions, TokenFrom, TokenPair } from "./types.mjs";
|
|
2
|
+
import { AccessTokenConfig, AccessTokenOutput, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthRefreshCredentialDescriptor, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, EmailVerificationConfig, LegacyJwtConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, PageAuthConfig, PasswordResetConfig, PasswordSetter, RefreshTokenConfig, SetAuthCookieOptions, TokenFrom, TokenPair } from "./types.mjs";
|
|
3
3
|
import { Authenticable } from "./auth-contract.mjs";
|
|
4
4
|
import { RequestUser } from "./request-locals.mjs";
|
|
5
|
-
export { AccessTokenConfig, AccessTokenOutput, AppleProviderConfig, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthRefreshCredentialDescriptor, Authenticable, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, DiscordProviderConfig, EmailVerificationConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LegacyJwtConfig, LinkedInProviderConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAuthorizationState, ProviderCallbackParams, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshTokenConfig, RequestUser, SetAuthCookieOptions, TokenFrom, TokenPair, XProviderConfig };
|
|
5
|
+
export { AccessTokenConfig, AccessTokenOutput, AppleProviderConfig, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthRefreshCredentialDescriptor, Authenticable, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, DiscordProviderConfig, EmailVerificationConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LegacyJwtConfig, LinkedInProviderConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAuthorizationState, ProviderCallbackParams, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshTokenConfig, RequestUser, SetAuthCookieOptions, TokenFrom, TokenPair, XProviderConfig };
|
|
@@ -72,6 +72,11 @@ export type CanAuthenticate = (user: Auth) => boolean | Promise<boolean>;
|
|
|
72
72
|
export type AuthCredentials = Record<string, unknown> & {
|
|
73
73
|
password: string;
|
|
74
74
|
};
|
|
75
|
+
/**
|
|
76
|
+
* Rewrites the identity fields of a login (everything except `password`)
|
|
77
|
+
* before the user lookup.
|
|
78
|
+
*/
|
|
79
|
+
export type NormalizeCredentials = (identifiers: Omit<AuthCredentials, "password">) => Omit<AuthCredentials, "password">;
|
|
75
80
|
/**
|
|
76
81
|
* Access-token configuration.
|
|
77
82
|
*
|
|
@@ -279,6 +284,19 @@ export type AuthConfigurations = {
|
|
|
279
284
|
* @default () => true
|
|
280
285
|
*/
|
|
281
286
|
canAuthenticate?: CanAuthenticate;
|
|
287
|
+
/**
|
|
288
|
+
* How login identifiers are normalized before the user lookup. Default:
|
|
289
|
+
* string values are trimmed and the `email` field is lower-cased, so
|
|
290
|
+
* `" Sara@x.io"` finds the account stored as `sara@x.io`. If that finds no
|
|
291
|
+
* user and the normalized value differs from what was sent (trimmed), the
|
|
292
|
+
* lookup is retried once with the value as sent, so rows stored with capitals
|
|
293
|
+
* keep working. Pass a function to normalize your own way (the retry still
|
|
294
|
+
* applies), or `false` for exact matching.
|
|
295
|
+
*
|
|
296
|
+
* The login throttle buckets `email` by trimmed, lower-cased value either way.
|
|
297
|
+
* @default trim string values, lower-case `email`
|
|
298
|
+
*/
|
|
299
|
+
normalizeCredentials?: false | NormalizeCredentials;
|
|
282
300
|
/**
|
|
283
301
|
* Access-token configuration (secret, expiry, algorithm, model override).
|
|
284
302
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA4Ba;;;;;;YAOD;;YAGA;;iBAGK;EACf;EACA;;;iBAIe,wCAAwC;;EAEvD;;;iBAIe,8BAA8B,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EAMf,WAAW;;;;;;EAMX,SAAS;;;;EAIT,OAAO;;;;EAIP,eAAe;;;;EAIf,gBAAgB;;;;EAIhB,eAAe;;;;EAIf,YAAY;;;;EAIZ,WAAW;;;;EAIX,MAAM;;;;EAIN,MAAM;;YAGI;;;;EAIV;;;;EAIA;;;;;YAMU;;;;EAIV,aAAa;;;;EAIb,eAAe;;;;;YAML;;;;EAIV;;;;EAIA;;;;EAIA;;;;;EAKA;;;;EAIA,UAAU;;YAGA,YAAY,iBAAiB;EACvC,MAAM;EACN,QAAQ;;;YAIE,wBAAwB,SAAS;;;;;;;;;YAUjC;;;;;;EAMV;;;;;EAKA;;;;;EAKA;;EAEA,eAAe;;;;;;YAOL;;;;;;EAMV;;;;;;;;YASU;;EAEV;;EAEA;;EAEA;;;;;;;EAOA;;;YAIU;;EAEV;;EAEA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"sourcesContent":["import { type ChildModel } from \"@warlock.js/cascade\";\nimport type { Request } from \"@warlock.js/core\";\nimport { type Algorithm } from \"fast-jwt\";\nimport type { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport type { OneTimeToken } from \"../models/one-time-token\";\nimport type { OtpConfig, PasskeysConfig, ProvidersConfig } from \"./providers\";\nimport type { RefreshToken } from \"../models/refresh-token\";\n\n/**\n * Symbol to indicate no expiration for tokens\n * Use this when you explicitly want tokens to never expire\n *\n * @example\n * ```typescript\n * // src/config/auth.ts\n * import { NO_EXPIRATION, type AuthConfigurations } from \"@warlock.js/auth\";\n *\n * const authConfigurations: AuthConfigurations = {\n * accessToken: {\n * secret: env(\"JWT_SECRET\"),\n * expiresIn: NO_EXPIRATION, // Token expires within 100 years\n * },\n * };\n *\n * export default authConfigurations;\n * ```\n */\nexport const NO_EXPIRATION = \"100y\";\n\n/**\n * Behavior when logout is called without a refresh token\n * - \"revoke-all\": Revoke all refresh tokens for the user (secure default)\n * - \"error\": Return an error requiring the refresh token\n */\nexport type LogoutWithoutTokenBehavior = \"revoke-all\" | \"error\";\n\n/** The single request credential source an auth middleware instance accepts. */\nexport type TokenFrom = \"header\" | `cookie:${string}`;\n\n/** One explicitly named credential location accepted by auth middleware. */\nexport interface AuthCredentialDescriptor {\n source: \"header\" | \"cookie\";\n key?: string;\n}\n\n/** Cookie credential and bounded duplicate window for automatic renewal. */\nexport interface AuthRefreshCredentialDescriptor extends AuthCredentialDescriptor {\n /** Milliseconds; the service clamps this to the 0–10 second range (default 5 seconds). */\n overlapMs?: number;\n}\n\n/** Per-route authentication behavior for the object middleware overload. */\nexport interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor> {\n optional?: boolean;\n /**\n * Accept both a header and a cookie credential (at most one of each).\n * Precedence is fixed and independent of array order: a present\n * `Authorization` header wins, an invalid header rejects and never falls back\n * to the cookie, and renewal plus the CSRF Origin check apply only when the\n * cookie is the credential actually used. Cannot be combined with `source`.\n */\n sources?: AuthCredentialDescriptor[];\n /** Opt-in automatic renewal credential. Cookie sources only. */\n refresh?: AuthRefreshCredentialDescriptor;\n redirect?: { to: string; returnUrlParam?: string };\n}\n\n/** Application policy that decides whether a resolved user may authenticate. */\nexport type CanAuthenticate = (user: Auth) => boolean | Promise<boolean>;\n\n/** Password credentials plus the application-defined identity fields. */\nexport type AuthCredentials = Record<string, unknown> & {\n password: string;\n};\n\n/**\n * Access-token configuration.\n *\n * `secret` may also be supplied via the deprecated `jwt.secret` (resolved by a\n * backward-compatible shim); one of the two is required at runtime.\n */\nexport type AccessTokenConfig = {\n /**\n * Override the persisted access-token model — extend {@link AccessToken} to\n * add columns (e.g. a tenant key) or rename them, then register the subclass\n * here. Defaults to the package's `AccessToken`.\n */\n model?: typeof AccessToken;\n /**\n * Secret used to sign access tokens.\n */\n secret?: string;\n /**\n * JWT algorithm.\n * @default \"HS256\"\n */\n algorithm?: Algorithm;\n /**\n * Access-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\n * first token issue: each of them would otherwise sign a token with no `exp`\n * claim at all.\n * @example \"1h\" or NO_EXPIRATION\n * @default \"1h\"\n */\n expiresIn?: string;\n};\n\n/**\n * Refresh-token configuration.\n */\nexport type RefreshTokenConfig = {\n /**\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\n * Defaults to the package's `RefreshToken`.\n */\n model?: typeof RefreshToken;\n /**\n * Enable refresh tokens.\n * @default true\n */\n enabled?: boolean;\n /**\n * Separate secret for refresh tokens (recommended for security). Falls back\n * to the access-token secret when omitted.\n */\n secret?: string;\n /**\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds; an unusable value throws naming this key on issue\n * (see {@link AccessTokenConfig.expiresIn}).\n * @example \"7d\" or \"1w\"\n * @default \"7d\"\n */\n expiresIn?: string;\n /**\n * Rotate the refresh token on each use (old token revoked, replay detected).\n * @default true\n */\n rotation?: boolean;\n /**\n * Maximum active refresh tokens per user; the oldest are revoked past it.\n * @default 5\n */\n maxPerUser?: number;\n /**\n * Behavior when logout is called without a refresh token.\n * @default \"revoke-all\"\n */\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n};\n\n/**\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\n * deprecation warning.\n *\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\n */\nexport type LegacyJwtConfig = {\n secret?: string;\n algorithm?: Algorithm;\n expiresIn?: string;\n refresh?: {\n secret?: string;\n enabled?: boolean;\n expiresIn?: string;\n rotation?: boolean;\n maxPerUser?: number;\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n };\n};\n\n/**\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\n * to a login page instead of returning the API-style JSON 401.\n *\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\n * always keep the JSON 401 contract regardless of this setting.\n */\nexport type PageAuthConfig = {\n /**\n * Login path a guarded page route redirects a logged-out browser to (e.g.\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\n * behavior is opt-in and backward-compatible.\n */\n loginPath?: string;\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed.\n * @default \"returnUrl\"\n */\n returnUrlParam?: string;\n};\n\n/**\n * Data every email-verification / password-reset notification receives.\n */\nexport type OneTimeTokenNotificationData = {\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\n token: string;\n /** When the token stops working. */\n expiresAt: Date;\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\n url?: string;\n};\n\n/**\n * Anything auth can deliver a token through — a `defineNotification(...)`\n * result satisfies it, as does any object with a compatible `send`.\n */\nexport type AuthNotification = {\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\n};\n\n/** Builds the link a token notification points at. */\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\n\n/** Persists a new plaintext password for a user during a password reset. */\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\n\n/**\n * Email-verification configuration (`auth.verification`).\n */\nexport type EmailVerificationConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"24h\"\n */\n expiresIn?: string;\n /**\n * User attribute stamped with the verification `Date`. Declare it in the\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\n * @default \"emailVerifiedAt\"\n */\n field?: string;\n /** Replace the default verification email. */\n notification?: AuthNotification;\n /** Build the verification link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n};\n\n/**\n * Password-reset configuration (`auth.passwordReset`).\n */\nexport type PasswordResetConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"60m\"\n */\n expiresIn?: string;\n /**\n * User attribute `requestPasswordReset` looks the account up by.\n * @default \"email\"\n */\n identifierField?: string;\n /** Replace the default reset email. */\n notification?: AuthNotification;\n /** Build the reset link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n /**\n * Persist the new password yourself. By default auth saves a hash made by\n * the same `hashPassword` login verifies against, and falls back to the\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\n * the stored value with `verifyPassword` either way.\n */\n setPassword?: PasswordSetter;\n};\n\n/**\n * One-time token storage configuration (`auth.oneTimeToken`).\n */\nexport type OneTimeTokenConfig = {\n /** Override the persisted model — extend {@link OneTimeToken}. */\n model?: typeof OneTimeToken;\n};\n\nexport type AuthConfigurations = {\n /**\n * Define all user types — maps a user-type slug to its `Auth` model class so\n * tokens and the middleware can resolve the right model.\n */\n userType: {\n [userType: string]: ChildModel<Auth>;\n };\n /** Default user type used by `authMiddleware()` and options-only overloads. */\n defaultUserType?: string;\n /**\n * Decide whether a resolved user may authenticate or receive new tokens.\n * @default () => true\n */\n canAuthenticate?: CanAuthenticate;\n /**\n * Access-token configuration (secret, expiry, algorithm, model override).\n */\n accessToken?: AccessTokenConfig;\n /**\n * Refresh-token configuration (rotation, lifetime, cap, model override).\n */\n refreshToken?: RefreshTokenConfig;\n /**\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\n */\n pageAuth?: PageAuthConfig;\n /**\n * Cookie auth session config — read by `authService.setAuthCookie` /\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\n */\n cookie?: CookieAuthConfig;\n /**\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\n */\n csrf?: CsrfConfig;\n /**\n * Email verification — token lifetime, verified field, notification override.\n */\n verification?: EmailVerificationConfig;\n /**\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\n */\n passwordReset?: PasswordResetConfig;\n /**\n * One-time token (verification / reset) storage — model override.\n */\n oneTimeToken?: OneTimeTokenConfig;\n /**\n * Redirect login providers (`google`, `custom`) and account-linking policy.\n */\n providers?: ProvidersConfig;\n /**\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\n */\n passkeys?: PasskeysConfig;\n /**\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\n */\n otp?: OtpConfig;\n /**\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\n */\n jwt?: LegacyJwtConfig;\n};\n\nexport type AccessTokenOutput = {\n /**\n * JWT Token\n */\n token: string;\n /**\n * Exprie time in ISO format UTC time\n */\n expiresAt: string;\n};\n\n/**\n * Token pair returned after login or token refresh\n */\nexport type TokenPair = {\n /**\n * JWT access token (short-lived)\n */\n accessToken: AccessTokenOutput;\n /**\n * JWT refresh token (long-lived)\n */\n refreshToken?: AccessTokenOutput;\n};\n\n/**\n * Device information for session tracking\n */\nexport type DeviceInfo = {\n /**\n * User agent string from request\n */\n userAgent?: string;\n /**\n * Client IP address\n */\n ip?: string;\n /**\n * Optional device identifier\n */\n deviceId?: string;\n /**\n * Token family ID (for rotation tracking)\n * @internal\n */\n familyId?: string;\n /**\n * Access token payload\n */\n payload?: Record<string, unknown>;\n};\n\nexport type LoginResult<UserType extends Auth> = {\n user: UserType;\n tokens: TokenPair;\n};\n\n/** Selects a cookie Domain for one request; return `undefined` for a host-only cookie. */\nexport type CookieDomainResolver = (request: Request) => string | undefined;\n\n/**\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\n * configurable here — they come from core's `secureCookieDefaults()`, the\n * same floor every `response.cookie()` call gets, so a cookie auth session can\n * never be weakened to a laxer policy than the framework default.\n */\nexport type CookieAuthConfig = {\n /**\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\n * `cookie:<name>` token source must match to read it back.\n * @default \"access_token\"\n */\n name?: string;\n /**\n * Cookie name the session helpers write and clear for the refresh token.\n * @default \"refresh_token\"\n */\n refreshName?: string;\n /**\n * Cookie `Path` attribute.\n * @default \"/\"\n */\n path?: string;\n /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */\n cookieDomain?: CookieDomainResolver;\n};\n\n/**\n * CSRF Origin-check configuration. Read via\n * `authConfig.csrf.allowedOrigins()`.\n */\nexport type CsrfConfig = {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * in addition to the request's own origin.\n * @default []\n */\n allowedOrigins?: string[];\n};\n\n/**\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\n * falls back to `auth.cookie.*` config, then the package default. Cookie\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\n * see {@link CookieAuthConfig}.\n */\nexport type SetAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\n path?: string;\n /** Cookie `Domain` attribute. Omit for a host-only cookie. */\n domain?: string;\n /**\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\n * bare token string with no `maxAge` produces a session cookie (cleared\n * when the browser closes).\n */\n maxAge?: number;\n};\n\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\nexport type ClearAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\n path?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
|
|
1
|
+
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"sourcesContent":["import { type ChildModel } from \"@warlock.js/cascade\";\nimport type { Request } from \"@warlock.js/core\";\nimport { type Algorithm } from \"fast-jwt\";\nimport type { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport type { OneTimeToken } from \"../models/one-time-token\";\nimport type { OtpConfig, PasskeysConfig, ProvidersConfig } from \"./providers\";\nimport type { RefreshToken } from \"../models/refresh-token\";\n\n/**\n * Symbol to indicate no expiration for tokens\n * Use this when you explicitly want tokens to never expire\n *\n * @example\n * ```typescript\n * // src/config/auth.ts\n * import { NO_EXPIRATION, type AuthConfigurations } from \"@warlock.js/auth\";\n *\n * const authConfigurations: AuthConfigurations = {\n * accessToken: {\n * secret: env(\"JWT_SECRET\"),\n * expiresIn: NO_EXPIRATION, // Token expires within 100 years\n * },\n * };\n *\n * export default authConfigurations;\n * ```\n */\nexport const NO_EXPIRATION = \"100y\";\n\n/**\n * Behavior when logout is called without a refresh token\n * - \"revoke-all\": Revoke all refresh tokens for the user (secure default)\n * - \"error\": Return an error requiring the refresh token\n */\nexport type LogoutWithoutTokenBehavior = \"revoke-all\" | \"error\";\n\n/** The single request credential source an auth middleware instance accepts. */\nexport type TokenFrom = \"header\" | `cookie:${string}`;\n\n/** One explicitly named credential location accepted by auth middleware. */\nexport interface AuthCredentialDescriptor {\n source: \"header\" | \"cookie\";\n key?: string;\n}\n\n/** Cookie credential and bounded duplicate window for automatic renewal. */\nexport interface AuthRefreshCredentialDescriptor extends AuthCredentialDescriptor {\n /** Milliseconds; the service clamps this to the 0–10 second range (default 5 seconds). */\n overlapMs?: number;\n}\n\n/** Per-route authentication behavior for the object middleware overload. */\nexport interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor> {\n optional?: boolean;\n /**\n * Accept both a header and a cookie credential (at most one of each).\n * Precedence is fixed and independent of array order: a present\n * `Authorization` header wins, an invalid header rejects and never falls back\n * to the cookie, and renewal plus the CSRF Origin check apply only when the\n * cookie is the credential actually used. Cannot be combined with `source`.\n */\n sources?: AuthCredentialDescriptor[];\n /** Opt-in automatic renewal credential. Cookie sources only. */\n refresh?: AuthRefreshCredentialDescriptor;\n redirect?: { to: string; returnUrlParam?: string };\n}\n\n/** Application policy that decides whether a resolved user may authenticate. */\nexport type CanAuthenticate = (user: Auth) => boolean | Promise<boolean>;\n\n/** Password credentials plus the application-defined identity fields. */\nexport type AuthCredentials = Record<string, unknown> & {\n password: string;\n};\n\n/**\n * Rewrites the identity fields of a login (everything except `password`)\n * before the user lookup.\n */\nexport type NormalizeCredentials = (\n identifiers: Omit<AuthCredentials, \"password\">,\n) => Omit<AuthCredentials, \"password\">;\n\n/**\n * Access-token configuration.\n *\n * `secret` may also be supplied via the deprecated `jwt.secret` (resolved by a\n * backward-compatible shim); one of the two is required at runtime.\n */\nexport type AccessTokenConfig = {\n /**\n * Override the persisted access-token model — extend {@link AccessToken} to\n * add columns (e.g. a tenant key) or rename them, then register the subclass\n * here. Defaults to the package's `AccessToken`.\n */\n model?: typeof AccessToken;\n /**\n * Secret used to sign access tokens.\n */\n secret?: string;\n /**\n * JWT algorithm.\n * @default \"HS256\"\n */\n algorithm?: Algorithm;\n /**\n * Access-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\n * first token issue: each of them would otherwise sign a token with no `exp`\n * claim at all.\n * @example \"1h\" or NO_EXPIRATION\n * @default \"1h\"\n */\n expiresIn?: string;\n};\n\n/**\n * Refresh-token configuration.\n */\nexport type RefreshTokenConfig = {\n /**\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\n * Defaults to the package's `RefreshToken`.\n */\n model?: typeof RefreshToken;\n /**\n * Enable refresh tokens.\n * @default true\n */\n enabled?: boolean;\n /**\n * Separate secret for refresh tokens (recommended for security). Falls back\n * to the access-token secret when omitted.\n */\n secret?: string;\n /**\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds; an unusable value throws naming this key on issue\n * (see {@link AccessTokenConfig.expiresIn}).\n * @example \"7d\" or \"1w\"\n * @default \"7d\"\n */\n expiresIn?: string;\n /**\n * Rotate the refresh token on each use (old token revoked, replay detected).\n * @default true\n */\n rotation?: boolean;\n /**\n * Maximum active refresh tokens per user; the oldest are revoked past it.\n * @default 5\n */\n maxPerUser?: number;\n /**\n * Behavior when logout is called without a refresh token.\n * @default \"revoke-all\"\n */\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n};\n\n/**\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\n * deprecation warning.\n *\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\n */\nexport type LegacyJwtConfig = {\n secret?: string;\n algorithm?: Algorithm;\n expiresIn?: string;\n refresh?: {\n secret?: string;\n enabled?: boolean;\n expiresIn?: string;\n rotation?: boolean;\n maxPerUser?: number;\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n };\n};\n\n/**\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\n * to a login page instead of returning the API-style JSON 401.\n *\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\n * always keep the JSON 401 contract regardless of this setting.\n */\nexport type PageAuthConfig = {\n /**\n * Login path a guarded page route redirects a logged-out browser to (e.g.\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\n * behavior is opt-in and backward-compatible.\n */\n loginPath?: string;\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed.\n * @default \"returnUrl\"\n */\n returnUrlParam?: string;\n};\n\n/**\n * Data every email-verification / password-reset notification receives.\n */\nexport type OneTimeTokenNotificationData = {\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\n token: string;\n /** When the token stops working. */\n expiresAt: Date;\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\n url?: string;\n};\n\n/**\n * Anything auth can deliver a token through — a `defineNotification(...)`\n * result satisfies it, as does any object with a compatible `send`.\n */\nexport type AuthNotification = {\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\n};\n\n/** Builds the link a token notification points at. */\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\n\n/** Persists a new plaintext password for a user during a password reset. */\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\n\n/**\n * Email-verification configuration (`auth.verification`).\n */\nexport type EmailVerificationConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"24h\"\n */\n expiresIn?: string;\n /**\n * User attribute stamped with the verification `Date`. Declare it in the\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\n * @default \"emailVerifiedAt\"\n */\n field?: string;\n /** Replace the default verification email. */\n notification?: AuthNotification;\n /** Build the verification link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n};\n\n/**\n * Password-reset configuration (`auth.passwordReset`).\n */\nexport type PasswordResetConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"60m\"\n */\n expiresIn?: string;\n /**\n * User attribute `requestPasswordReset` looks the account up by.\n * @default \"email\"\n */\n identifierField?: string;\n /** Replace the default reset email. */\n notification?: AuthNotification;\n /** Build the reset link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n /**\n * Persist the new password yourself. By default auth saves a hash made by\n * the same `hashPassword` login verifies against, and falls back to the\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\n * the stored value with `verifyPassword` either way.\n */\n setPassword?: PasswordSetter;\n};\n\n/**\n * One-time token storage configuration (`auth.oneTimeToken`).\n */\nexport type OneTimeTokenConfig = {\n /** Override the persisted model — extend {@link OneTimeToken}. */\n model?: typeof OneTimeToken;\n};\n\nexport type AuthConfigurations = {\n /**\n * Define all user types — maps a user-type slug to its `Auth` model class so\n * tokens and the middleware can resolve the right model.\n */\n userType: {\n [userType: string]: ChildModel<Auth>;\n };\n /** Default user type used by `authMiddleware()` and options-only overloads. */\n defaultUserType?: string;\n /**\n * Decide whether a resolved user may authenticate or receive new tokens.\n * @default () => true\n */\n canAuthenticate?: CanAuthenticate;\n /**\n * How login identifiers are normalized before the user lookup. Default:\n * string values are trimmed and the `email` field is lower-cased, so\n * `\" Sara@x.io\"` finds the account stored as `sara@x.io`. If that finds no\n * user and the normalized value differs from what was sent (trimmed), the\n * lookup is retried once with the value as sent, so rows stored with capitals\n * keep working. Pass a function to normalize your own way (the retry still\n * applies), or `false` for exact matching.\n *\n * The login throttle buckets `email` by trimmed, lower-cased value either way.\n * @default trim string values, lower-case `email`\n */\n normalizeCredentials?: false | NormalizeCredentials;\n /**\n * Access-token configuration (secret, expiry, algorithm, model override).\n */\n accessToken?: AccessTokenConfig;\n /**\n * Refresh-token configuration (rotation, lifetime, cap, model override).\n */\n refreshToken?: RefreshTokenConfig;\n /**\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\n */\n pageAuth?: PageAuthConfig;\n /**\n * Cookie auth session config — read by `authService.setAuthCookie` /\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\n */\n cookie?: CookieAuthConfig;\n /**\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\n */\n csrf?: CsrfConfig;\n /**\n * Email verification — token lifetime, verified field, notification override.\n */\n verification?: EmailVerificationConfig;\n /**\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\n */\n passwordReset?: PasswordResetConfig;\n /**\n * One-time token (verification / reset) storage — model override.\n */\n oneTimeToken?: OneTimeTokenConfig;\n /**\n * Redirect login providers (`google`, `custom`) and account-linking policy.\n */\n providers?: ProvidersConfig;\n /**\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\n */\n passkeys?: PasskeysConfig;\n /**\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\n */\n otp?: OtpConfig;\n /**\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\n */\n jwt?: LegacyJwtConfig;\n};\n\nexport type AccessTokenOutput = {\n /**\n * JWT Token\n */\n token: string;\n /**\n * Exprie time in ISO format UTC time\n */\n expiresAt: string;\n};\n\n/**\n * Token pair returned after login or token refresh\n */\nexport type TokenPair = {\n /**\n * JWT access token (short-lived)\n */\n accessToken: AccessTokenOutput;\n /**\n * JWT refresh token (long-lived)\n */\n refreshToken?: AccessTokenOutput;\n};\n\n/**\n * Device information for session tracking\n */\nexport type DeviceInfo = {\n /**\n * User agent string from request\n */\n userAgent?: string;\n /**\n * Client IP address\n */\n ip?: string;\n /**\n * Optional device identifier\n */\n deviceId?: string;\n /**\n * Token family ID (for rotation tracking)\n * @internal\n */\n familyId?: string;\n /**\n * Access token payload\n */\n payload?: Record<string, unknown>;\n};\n\nexport type LoginResult<UserType extends Auth> = {\n user: UserType;\n tokens: TokenPair;\n};\n\n/** Selects a cookie Domain for one request; return `undefined` for a host-only cookie. */\nexport type CookieDomainResolver = (request: Request) => string | undefined;\n\n/**\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\n * configurable here — they come from core's `secureCookieDefaults()`, the\n * same floor every `response.cookie()` call gets, so a cookie auth session can\n * never be weakened to a laxer policy than the framework default.\n */\nexport type CookieAuthConfig = {\n /**\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\n * `cookie:<name>` token source must match to read it back.\n * @default \"access_token\"\n */\n name?: string;\n /**\n * Cookie name the session helpers write and clear for the refresh token.\n * @default \"refresh_token\"\n */\n refreshName?: string;\n /**\n * Cookie `Path` attribute.\n * @default \"/\"\n */\n path?: string;\n /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */\n cookieDomain?: CookieDomainResolver;\n};\n\n/**\n * CSRF Origin-check configuration. Read via\n * `authConfig.csrf.allowedOrigins()`.\n */\nexport type CsrfConfig = {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * in addition to the request's own origin.\n * @default []\n */\n allowedOrigins?: string[];\n};\n\n/**\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\n * falls back to `auth.cookie.*` config, then the package default. Cookie\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\n * see {@link CookieAuthConfig}.\n */\nexport type SetAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\n path?: string;\n /** Cookie `Domain` attribute. Omit for a host-only cookie. */\n domain?: string;\n /**\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\n * bare token string with no `maxAge` produces a session cookie (cleared\n * when the browser closes).\n */\n maxAge?: number;\n};\n\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\nexport type ClearAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\n path?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
|
package/esm/index.d.mts
CHANGED
|
@@ -5,7 +5,7 @@ import { Auth } from "./models/auth.model.mjs";
|
|
|
5
5
|
import { AccessToken, accessTokenSchema } from "./models/access-token/access-token.model.mjs";
|
|
6
6
|
import { OneTimeToken, OneTimeTokenPurpose, oneTimeTokenSchema } from "./models/one-time-token/one-time-token.model.mjs";
|
|
7
7
|
import { AppleProviderConfig, AuthProvider, DiscordProviderConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LinkedInProviderConfig, OtpConfig, OtpMessage, OtpSender, PasskeysConfig, ProviderAuthorizationState, ProviderCallbackParams, ProviderProfile, ProviderUserCreator, ProvidersConfig, XProviderConfig } from "./contracts/providers.mjs";
|
|
8
|
-
import { AccessTokenConfig, AccessTokenOutput, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthRefreshCredentialDescriptor, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, EmailVerificationConfig, LegacyJwtConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, PageAuthConfig, PasswordResetConfig, PasswordSetter, RefreshTokenConfig, SetAuthCookieOptions, TokenFrom, TokenPair } from "./contracts/types.mjs";
|
|
8
|
+
import { AccessTokenConfig, AccessTokenOutput, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthRefreshCredentialDescriptor, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, EmailVerificationConfig, LegacyJwtConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, PageAuthConfig, PasswordResetConfig, PasswordSetter, RefreshTokenConfig, SetAuthCookieOptions, TokenFrom, TokenPair } from "./contracts/types.mjs";
|
|
9
9
|
import { RefreshToken, RefreshTokenIssueOptions, refreshTokenSchema } from "./models/refresh-token/refresh-token.model.mjs";
|
|
10
10
|
import { Authenticable } from "./contracts/auth-contract.mjs";
|
|
11
11
|
import { RequestUser } from "./contracts/request-locals.mjs";
|
|
@@ -62,5 +62,5 @@ import { PageSessionOptions, PageSessionResolver, SessionMiddlewareOptions, Sess
|
|
|
62
62
|
import "./session/index.mjs";
|
|
63
63
|
import { safeEqual } from "./utils/safe-equal.mjs";
|
|
64
64
|
import { isNeverExpiring, isUsableExpiry, tokenHasExpClaim } from "./utils/token-expiry.mjs";
|
|
65
|
-
export { APPLE_AUTH_FEATURE, AUTH_MIDDLEWARE_DESCRIPTOR, AccessToken, AccessTokenConfig, AccessTokenOutput, AppleJoseModule, AppleProvider, AppleProviderConfig, Auth, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthErrorCodes, AuthErrorTranslations, AuthEventCallback, AuthEventName, AuthEventPayloads, AuthMiddlewareDescriptor, AuthMiddlewareDescriptorSource, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthProviderSdkMissingError, AuthRefreshCredentialDescriptor, AuthTokenFamily, AuthTranslations, Authenticable, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainRequestRequiredError, CookieDomainResolver, CsrfConfig, CsrfOriginMismatchError, CsrfOriginMismatchReason, DeviceInfo, DiscordProvider, DiscordProviderConfig, EmailNotVerifiedError, EmailVerificationConfig, FacebookProvider, FacebookProviderConfig, GOOGLE_AUTH_FEATURE, GitHubProvider, GitHubProviderConfig, GoogleProvider, GoogleProviderConfig, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, IssuedOneTimeToken, JoseModule, LINKEDIN_AUTH_FEATURE, LegacyJwtConfig, LinkedInProvider, LinkedInProviderConfig, LoginResult, LoginThrottleIdentifier, LoginThrottleOptions, LogoutWithoutTokenBehavior, NO_EXPIRATION, NotificationsUnavailableError, OneTimeToken, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenPurpose, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PageSessionOptions, PageSessionResolver, PasskeyCredential, type PasskeyOptionsJSON, type PasskeyResponseJSON, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAccount, ProviderAuthorizationState, ProviderCallbackParams, ProviderEmailNotVerifiedError, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshToken, RefreshTokenConfig, RefreshTokenIssueOptions, RequestUser, RequestUserFailure, RequestUserOutcome, ResolveRequestUserOptions, SessionMiddlewareOptions, SessionResolverOptions, SessionSource, SetAuthCookieOptions, TokenFrom, TokenPair, TokenType, TokenTypeError, XProvider, XProviderConfig, accessTokenSchema, assertCsrfOriginAllowed, authDefaultTranslations, authEvents, authMiddleware, authMigrations, authService, authTokenFamilySchema, completeProviderLogin, consumeOneTimeToken, currentUser, generateJWTSecret, generatePasskeyAuthenticationOptions, generatePasskeyRegistrationOptions, hashOneTimeToken, isEmailVerified, isInvalidCredentialError, isNeverExpiring, isUsableExpiry, issueOneTimeToken, jwt, loginThrottleMiddleware, oneTimeTokenModel, oneTimeTokenSchema, otpRequestThrottleMiddleware, otpVerifyThrottleMiddleware, pageSession, passkeyCredentialSchema, pkceChallenge, providerAccountSchema, readCredential, refreshTokenSchema, registerAuthCleanupCommand, registerAuthPurgeNeverExpiringCommand, registerAuthTranslations, registerJWTSecretGeneratorCommand, requestOtp, requestPasswordReset, requireVerifiedEmail, requiresCsrfOriginCheck, resetPassword, resolveAuthProvider, resolveRequestUser, resolveRequestUserOutcome, safeEqual, sendEmailVerification, sessionMiddleware, startProviderLogin, throttleIdentifierHash, tokenConsumeThrottleMiddleware, tokenHasExpClaim, tokenIssueThrottleMiddleware, verifyEmail, verifyOtp, verifyPasskeyAuthentication, verifyPasskeyRegistration };
|
|
65
|
+
export { APPLE_AUTH_FEATURE, AUTH_MIDDLEWARE_DESCRIPTOR, AccessToken, AccessTokenConfig, AccessTokenOutput, AppleJoseModule, AppleProvider, AppleProviderConfig, Auth, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthErrorCodes, AuthErrorTranslations, AuthEventCallback, AuthEventName, AuthEventPayloads, AuthMiddlewareDescriptor, AuthMiddlewareDescriptorSource, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthProviderSdkMissingError, AuthRefreshCredentialDescriptor, AuthTokenFamily, AuthTranslations, Authenticable, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainRequestRequiredError, CookieDomainResolver, CsrfConfig, CsrfOriginMismatchError, CsrfOriginMismatchReason, DeviceInfo, DiscordProvider, DiscordProviderConfig, EmailNotVerifiedError, EmailVerificationConfig, FacebookProvider, FacebookProviderConfig, GOOGLE_AUTH_FEATURE, GitHubProvider, GitHubProviderConfig, GoogleProvider, GoogleProviderConfig, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, IssuedOneTimeToken, JoseModule, LINKEDIN_AUTH_FEATURE, LegacyJwtConfig, LinkedInProvider, LinkedInProviderConfig, LoginResult, LoginThrottleIdentifier, LoginThrottleOptions, LogoutWithoutTokenBehavior, NO_EXPIRATION, NormalizeCredentials, NotificationsUnavailableError, OneTimeToken, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenPurpose, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PageSessionOptions, PageSessionResolver, PasskeyCredential, type PasskeyOptionsJSON, type PasskeyResponseJSON, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAccount, ProviderAuthorizationState, ProviderCallbackParams, ProviderEmailNotVerifiedError, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshToken, RefreshTokenConfig, RefreshTokenIssueOptions, RequestUser, RequestUserFailure, RequestUserOutcome, ResolveRequestUserOptions, SessionMiddlewareOptions, SessionResolverOptions, SessionSource, SetAuthCookieOptions, TokenFrom, TokenPair, TokenType, TokenTypeError, XProvider, XProviderConfig, accessTokenSchema, assertCsrfOriginAllowed, authDefaultTranslations, authEvents, authMiddleware, authMigrations, authService, authTokenFamilySchema, completeProviderLogin, consumeOneTimeToken, currentUser, generateJWTSecret, generatePasskeyAuthenticationOptions, generatePasskeyRegistrationOptions, hashOneTimeToken, isEmailVerified, isInvalidCredentialError, isNeverExpiring, isUsableExpiry, issueOneTimeToken, jwt, loginThrottleMiddleware, oneTimeTokenModel, oneTimeTokenSchema, otpRequestThrottleMiddleware, otpVerifyThrottleMiddleware, pageSession, passkeyCredentialSchema, pkceChallenge, providerAccountSchema, readCredential, refreshTokenSchema, registerAuthCleanupCommand, registerAuthPurgeNeverExpiringCommand, registerAuthTranslations, registerJWTSecretGeneratorCommand, requestOtp, requestPasswordReset, requireVerifiedEmail, requiresCsrfOriginCheck, resetPassword, resolveAuthProvider, resolveRequestUser, resolveRequestUserOutcome, safeEqual, sendEmailVerification, sessionMiddleware, startProviderLogin, throttleIdentifierHash, tokenConsumeThrottleMiddleware, tokenHasExpClaim, tokenIssueThrottleMiddleware, verifyEmail, verifyOtp, verifyPasskeyAuthentication, verifyPasskeyRegistration };
|
|
66
66
|
import "./contracts/request-locals.mjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login-throttle.middleware.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"login-throttle.middleware.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;YAmBY;;;;;;;;;;;YAYA;;;;;;EAMV;;;;;;EAOA;;;;;;EAOA;;;;;;EAOA,KAAK;;;;;;;;EASL;;;;EAKA;;;;;;;;EASA,aAAa,UAAU;;;;;;EAOvB,YAAY,SAAS;;;;;;;;;;;;;;;;wBAwCP,uBAAuB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA0IrC,wBAAwB,UAAS,uBAA4B"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AuthErrorCodes } from "../utils/auth-error-codes.mjs";
|
|
2
|
+
import { normalizeEmailIdentifier } from "../utils/normalize-credentials.mjs";
|
|
2
3
|
import { authConfig } from "../services/auth-config.mjs";
|
|
3
4
|
import { t } from "@warlock.js/core";
|
|
4
5
|
import { createHash, createHmac } from "node:crypto";
|
|
@@ -40,7 +41,7 @@ function throttleHashKey() {
|
|
|
40
41
|
* Exported for tests and for apps that inspect throttle keys.
|
|
41
42
|
*/
|
|
42
43
|
function throttleIdentifierHash(kind, value) {
|
|
43
|
-
const normalized = `${kind}:${value
|
|
44
|
+
const normalized = `${kind}:${normalizeEmailIdentifier(value)}`;
|
|
44
45
|
const key = throttleHashKey();
|
|
45
46
|
return key ? createHmac("sha256", key).update(normalized).digest("hex") : createHash("sha256").update(normalized).digest("hex");
|
|
46
47
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport { cache } from \"@warlock.js/cache\";\nimport { t, type Middleware, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport { authConfig } from \"../services/auth-config\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * Built-in identifier kinds the throttle knows how to extract from a request.\n *\n * - `\"email\"` tracks per-account, so an attacker can't spray one user from\n * many IPs.\n * - `\"ip\"` tracks per-source, so an attacker can't stuff many accounts from\n * one IP.\n *\n * Lockout trips when ANY tracked identifier crosses `max` — defense-in-depth.\n */\nexport type LoginThrottleIdentifier = \"email\" | \"ip\";\n\n/**\n * Options for {@link loginThrottleMiddleware}.\n *\n * Failure-aware by design: only counts requests whose response is non-2xx\n * (or whatever `isFailure` says) and resets on success, so a user who types\n * a wrong password three times then the right one is not penalised.\n *\n * @example\n * loginThrottleMiddleware({ max: 5, window: \"15m\", lockoutDuration: \"15m\" });\n */\nexport type LoginThrottleOptions = {\n /**\n * Failures allowed within the window before the identifier is locked.\n *\n * @default 5\n */\n max?: number;\n\n /**\n * Counting window. `ms`-format string (`\"15m\"`, `\"1h\"`) or seconds as a number.\n *\n * @default \"15m\"\n */\n window?: string | number;\n\n /**\n * Lockout duration once the threshold is tripped. `ms`-format string or seconds.\n *\n * @default \"15m\"\n */\n lockoutDuration?: string | number;\n\n /**\n * Identifiers tracked. Each is counted and locked independently.\n *\n * @default [\"email\", \"ip\"]\n */\n by?: LoginThrottleIdentifier[];\n\n /**\n * Credential field consulted when `\"email\"` is tracked. Switch to\n * `\"username\"` (or any other input field) for systems that don't\n * authenticate by email.\n *\n * @default \"email\"\n */\n identifierKey?: string;\n\n /**\n * Override the default error message returned with the 429 response.\n */\n errorMessage?: string;\n\n /**\n * Decide whether the response represents a failed login. Defaults to\n * \"non-2xx is a failure\"; override if your controller signals failure\n * through a 200-style body.\n *\n * @default (response) => !response.isOk\n */\n isFailure?: (response: Response) => boolean;\n\n /**\n * Compute the identifiers tracked for this request. Override to derive the\n * account key from a header, a JWT subject, or any other shape that does\n * not match the built-in `email` / `ip` extraction.\n */\n identify?: (request: Request) => string[];\n};\n\nconst COUNTER_PREFIX = \"auth.throttle.count.\";\nconst LOCK_PREFIX = \"auth.throttle.lock.\";\n\nconst counterKey = (identifier: string): string => `${COUNTER_PREFIX}${identifier}`;\nconst lockKey = (identifier: string): string => `${LOCK_PREFIX}${identifier}`;\n\n/**\n * The key a throttle identifier is hashed with: an HMAC key derived from\n * `auth.accessToken.secret` (the same root the OTP code MAC uses), or\n * `undefined` when no secret is configured.\n */\nfunction throttleHashKey(): Buffer | undefined {\n let secret: string | undefined;\n\n try {\n secret = authConfig.accessToken.secret();\n } catch {\n return undefined;\n }\n\n return createHmac(\"sha256\", secret).update(\"@warlock.js/auth:throttle\").digest();\n}\n\n/**\n * Hash of a throttle identifier (`kind` is `\"email\"`, `\"ip\"`, ...). The value\n * is trimmed and lower-cased first, so `\" Sara@x.io\"` and `\"sara@x.io\"` share\n * one bucket.\n *\n * Identifiers become part of cache keys, and cache drivers log their keys: a\n * raw email or IP there is personal data in a log line. A plain SHA-256 of an\n * email is reversible by anyone with a list of addresses, so the hash is\n * keyed (HMAC) with a key derived from `auth.accessToken.secret`. Without a\n * configured secret it falls back to SHA-256, which still keeps the address\n * out of the key.\n *\n * Exported for tests and for apps that inspect throttle keys.\n */\nexport function throttleIdentifierHash(kind: string, value: string): string {\n const normalized = `${kind}:${value.trim().toLowerCase()}`;\n const key = throttleHashKey();\n\n return key\n ? createHmac(\"sha256\", key).update(normalized).digest(\"hex\")\n : createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\nlet warnedNullDriver = false;\n\n/**\n * The `null` cache driver stores nothing: every count reads back as 1 and no\n * lock is ever found, so the throttle silently never trips. Say so once.\n */\nfunction warnIfNullDriver(): void {\n if (warnedNullDriver) return;\n\n const driverName = (cache as { currentDriver?: { name?: string } }).currentDriver?.name;\n\n if (driverName !== \"null\") return;\n\n warnedNullDriver = true;\n log.warn(\n \"auth\",\n \"login-throttle\",\n \"The cache driver is `null`, so login, token and OTP throttles never lock. Use a real cache driver (redis, pg, or memory for one process).\",\n );\n}\n\n/**\n * A lock value is the lockout deadline (epoch ms). `true`, written by 5.29\n * and earlier, still counts as locked until the key expires.\n */\nfunction isLocked(value: unknown): boolean {\n if (typeof value === \"number\") {\n return value > Date.now();\n }\n\n return Boolean(value);\n}\n\n/**\n * `ms`'s honest runtime signature (see `services/auth-config.ts`): it returns\n * `undefined` for text it cannot parse and throws for `\"\"`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * `\"15m\"` / `\"1h\"` / seconds as a number → seconds, or `undefined` when the\n * value cannot be parsed (the cache rejects such a TTL anyway).\n */\nfunction durationSeconds(duration: string | number): number | undefined {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? duration : undefined;\n }\n\n let milliseconds: number | string | undefined;\n\n try {\n milliseconds = parseMs(duration);\n } catch {\n milliseconds = undefined;\n }\n\n return typeof milliseconds === \"number\" && Number.isFinite(milliseconds) && milliseconds > 0\n ? milliseconds / 1000\n : undefined;\n}\n\n/**\n * Built-in identifier extractor — reads the configured credential field from\n * the request body for the per-account key, and `request.detectIp()` for the\n * per-source key. Untruthy values are dropped; a request that yields zero\n * identifiers is left untracked so the middleware no-ops for it.\n */\nfunction buildDefaultIdentifiers(\n request: Request,\n tracked: LoginThrottleIdentifier[],\n credentialField: string,\n): string[] {\n const identifiers: string[] = [];\n\n if (tracked.includes(\"email\")) {\n const value = request.input(credentialField);\n\n if (typeof value === \"string\" && value.trim().length > 0) {\n identifiers.push(`email.${throttleIdentifierHash(\"email\", value)}`);\n }\n }\n\n if (tracked.includes(\"ip\")) {\n const ip = request.detectIp();\n\n if (ip) {\n identifiers.push(`ip.${throttleIdentifierHash(\"ip\", ip)}`);\n }\n }\n\n return identifiers;\n}\n\n/**\n * Failure-aware login throttle. Locks an identifier (account, IP, or both)\n * after too many failed login attempts within a window — without penalising\n * a user who eventually types the right password.\n *\n * Mechanism (per identifier):\n *\n * 1. **Before the controller** — reject with `429` if a lock key is set,\n * skipping the DB lookup AND the bcrypt verify (this also neutralises the\n * CPU-DoS angle of brute-forcing).\n * 2. **After the controller** — observe the outcome via `response.onSent`.\n * On failure (non-2xx by default), bump a fixed-window counter; once it\n * reaches `max`, set a lock key with `lockoutDuration` TTL. On success,\n * clear both the counter and the lock for that identifier.\n *\n * Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,\n * transitively guaranteed via `@warlock.js/core`). Lockout state is shared\n * across replicas — correct security model, because an attacker can't bypass\n * by round-robin to a different pod. Every cache call is guarded so a\n * misconfigured driver fails open (a throttle outage must never escalate\n * into a full auth outage).\n *\n * @example\n * import { loginThrottleMiddleware } from \"@warlock.js/auth\";\n * import { router } from \"@warlock.js/core\";\n *\n * router.post(\"/auth/login\", loginController, {\n * middleware: [loginThrottleMiddleware({ max: 5, window: \"15m\" })],\n * });\n *\n * @example\n * // Per-IP only — avoid account-lockout-as-DoS on anonymous-attack vectors\n * router.post(\"/auth/refresh-token\", refreshController, {\n * middleware: [loginThrottleMiddleware({ by: [\"ip\"], max: 10, window: \"1m\" })],\n * });\n */\nexport function loginThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n const max = options.max ?? 5;\n const window = options.window ?? \"15m\";\n const lockoutDuration = options.lockoutDuration ?? \"15m\";\n const tracked = options.by ?? [\"email\", \"ip\"];\n const credentialField = options.identifierKey ?? \"email\";\n\n return async ({ request, response }) => {\n const identifiers = options.identify\n ? options.identify(request)\n : buildDefaultIdentifiers(request, tracked, credentialField);\n\n if (identifiers.length === 0) return;\n\n warnIfNullDriver();\n\n try {\n for (const identifier of identifiers) {\n const locked = isLocked(await cache.get(lockKey(identifier)));\n\n if (locked) {\n return response.tooManyRequests({\n error: options.errorMessage ?? t(\"auth.errors.tooManyAttempts\"),\n errorCode: AuthErrorCodes.TooManyAttempts,\n });\n }\n }\n } catch (error) {\n // Fail open — a cache outage (driver not initialised, network blip)\n // must never escalate into a full auth outage. Log and let the request\n // through; the onSent recorder below is independently guarded so an\n // outage there is also harmless.\n log.error(\"auth\", \"login-throttle\", error);\n\n return;\n }\n\n response.onSent(async (resolvedResponse: Response) => {\n try {\n const failed = options.isFailure\n ? options.isFailure(resolvedResponse)\n : !resolvedResponse.isOk;\n\n if (!failed) {\n for (const identifier of identifiers) {\n await cache.remove(counterKey(identifier));\n await cache.remove(lockKey(identifier));\n }\n\n return;\n }\n\n for (const identifier of identifiers) {\n const key = counterKey(identifier);\n\n // Open the window on the first failure: the create-only write means\n // only one of several racing servers sets the TTL, and an existing\n // window keeps its deadline (fixed window). The bump itself is an\n // atomic increment, so concurrent failures across servers are never\n // lost (redis INCRBY / pg upsert keep the window's TTL). Passing\n // the TTL on the bump also expires a key recreated after the seed.\n await cache.set(key, 0, { ttl: window, onConflict: \"create\" });\n const count = await cache.increment(key, 1, { ttl: window });\n\n if (count >= max) {\n const lockSeconds = durationSeconds(lockoutDuration);\n\n // The lock stores its own deadline: a driver with sliding\n // expiration (`memoryExtended`) pushes the key's TTL forward on\n // every read, but the deadline in the value does not move, so a\n // client that keeps retrying is still released after\n // `lockoutDuration`.\n await cache.set(\n lockKey(identifier),\n lockSeconds === undefined ? true : Date.now() + lockSeconds * 1000,\n { ttl: lockoutDuration },\n );\n }\n }\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;AA0FA,MAAM,iBAA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AAW,UAAU,CAAC;MACzC,MAAM,MAAM,OAAO,QAAQ,UAAU,CAAC;KACxC;KAEA;IACF;IAEA,KAAK,MAAM,cAAc,aAAa;KACpC,MAAM,MAAM,WAAW,UAAU;KAQjC,MAAM,MAAM,IAAI,KAAK,GAAG;MAAE,KAAK;MAAQ,YAAY;KAAS,CAAC;KAG7D,IAAI,MAFgB,MAAM,UAAU,KAAK,GAAG,EAAE,KAAK,OAAO,CAAC,KAE9C,KAAK;MAChB,MAAM,cAAc,gBAAgB,eAAe;MAOnD,MAAM,MAAM,IACV,QAAQ,UAAU,GAClB,gBAAgB,SAAY,OAAO,KAAK,IAAI,IAAI,cAAc,KAC9D,EAAE,KAAK,gBAAgB,CACzB;KACF;IACF;GACF,SAAS,OAAO;IACd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAC3C;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"login-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport { cache } from \"@warlock.js/cache\";\nimport { t, type Middleware, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport { authConfig } from \"../services/auth-config\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport { normalizeEmailIdentifier } from \"../utils/normalize-credentials\";\n\n/**\n * Built-in identifier kinds the throttle knows how to extract from a request.\n *\n * - `\"email\"` tracks per-account, so an attacker can't spray one user from\n * many IPs.\n * - `\"ip\"` tracks per-source, so an attacker can't stuff many accounts from\n * one IP.\n *\n * Lockout trips when ANY tracked identifier crosses `max` — defense-in-depth.\n */\nexport type LoginThrottleIdentifier = \"email\" | \"ip\";\n\n/**\n * Options for {@link loginThrottleMiddleware}.\n *\n * Failure-aware by design: only counts requests whose response is non-2xx\n * (or whatever `isFailure` says) and resets on success, so a user who types\n * a wrong password three times then the right one is not penalised.\n *\n * @example\n * loginThrottleMiddleware({ max: 5, window: \"15m\", lockoutDuration: \"15m\" });\n */\nexport type LoginThrottleOptions = {\n /**\n * Failures allowed within the window before the identifier is locked.\n *\n * @default 5\n */\n max?: number;\n\n /**\n * Counting window. `ms`-format string (`\"15m\"`, `\"1h\"`) or seconds as a number.\n *\n * @default \"15m\"\n */\n window?: string | number;\n\n /**\n * Lockout duration once the threshold is tripped. `ms`-format string or seconds.\n *\n * @default \"15m\"\n */\n lockoutDuration?: string | number;\n\n /**\n * Identifiers tracked. Each is counted and locked independently.\n *\n * @default [\"email\", \"ip\"]\n */\n by?: LoginThrottleIdentifier[];\n\n /**\n * Credential field consulted when `\"email\"` is tracked. Switch to\n * `\"username\"` (or any other input field) for systems that don't\n * authenticate by email.\n *\n * @default \"email\"\n */\n identifierKey?: string;\n\n /**\n * Override the default error message returned with the 429 response.\n */\n errorMessage?: string;\n\n /**\n * Decide whether the response represents a failed login. Defaults to\n * \"non-2xx is a failure\"; override if your controller signals failure\n * through a 200-style body.\n *\n * @default (response) => !response.isOk\n */\n isFailure?: (response: Response) => boolean;\n\n /**\n * Compute the identifiers tracked for this request. Override to derive the\n * account key from a header, a JWT subject, or any other shape that does\n * not match the built-in `email` / `ip` extraction.\n */\n identify?: (request: Request) => string[];\n};\n\nconst COUNTER_PREFIX = \"auth.throttle.count.\";\nconst LOCK_PREFIX = \"auth.throttle.lock.\";\n\nconst counterKey = (identifier: string): string => `${COUNTER_PREFIX}${identifier}`;\nconst lockKey = (identifier: string): string => `${LOCK_PREFIX}${identifier}`;\n\n/**\n * The key a throttle identifier is hashed with: an HMAC key derived from\n * `auth.accessToken.secret` (the same root the OTP code MAC uses), or\n * `undefined` when no secret is configured.\n */\nfunction throttleHashKey(): Buffer | undefined {\n let secret: string | undefined;\n\n try {\n secret = authConfig.accessToken.secret();\n } catch {\n return undefined;\n }\n\n return createHmac(\"sha256\", secret).update(\"@warlock.js/auth:throttle\").digest();\n}\n\n/**\n * Hash of a throttle identifier (`kind` is `\"email\"`, `\"ip\"`, ...). The value\n * is trimmed and lower-cased first, so `\" Sara@x.io\"` and `\"sara@x.io\"` share\n * one bucket.\n *\n * Identifiers become part of cache keys, and cache drivers log their keys: a\n * raw email or IP there is personal data in a log line. A plain SHA-256 of an\n * email is reversible by anyone with a list of addresses, so the hash is\n * keyed (HMAC) with a key derived from `auth.accessToken.secret`. Without a\n * configured secret it falls back to SHA-256, which still keeps the address\n * out of the key.\n *\n * Exported for tests and for apps that inspect throttle keys.\n */\nexport function throttleIdentifierHash(kind: string, value: string): string {\n const normalized = `${kind}:${normalizeEmailIdentifier(value)}`;\n const key = throttleHashKey();\n\n return key\n ? createHmac(\"sha256\", key).update(normalized).digest(\"hex\")\n : createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\nlet warnedNullDriver = false;\n\n/**\n * The `null` cache driver stores nothing: every count reads back as 1 and no\n * lock is ever found, so the throttle silently never trips. Say so once.\n */\nfunction warnIfNullDriver(): void {\n if (warnedNullDriver) return;\n\n const driverName = (cache as { currentDriver?: { name?: string } }).currentDriver?.name;\n\n if (driverName !== \"null\") return;\n\n warnedNullDriver = true;\n log.warn(\n \"auth\",\n \"login-throttle\",\n \"The cache driver is `null`, so login, token and OTP throttles never lock. Use a real cache driver (redis, pg, or memory for one process).\",\n );\n}\n\n/**\n * A lock value is the lockout deadline (epoch ms). `true`, written by 5.29\n * and earlier, still counts as locked until the key expires.\n */\nfunction isLocked(value: unknown): boolean {\n if (typeof value === \"number\") {\n return value > Date.now();\n }\n\n return Boolean(value);\n}\n\n/**\n * `ms`'s honest runtime signature (see `services/auth-config.ts`): it returns\n * `undefined` for text it cannot parse and throws for `\"\"`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * `\"15m\"` / `\"1h\"` / seconds as a number → seconds, or `undefined` when the\n * value cannot be parsed (the cache rejects such a TTL anyway).\n */\nfunction durationSeconds(duration: string | number): number | undefined {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? duration : undefined;\n }\n\n let milliseconds: number | string | undefined;\n\n try {\n milliseconds = parseMs(duration);\n } catch {\n milliseconds = undefined;\n }\n\n return typeof milliseconds === \"number\" && Number.isFinite(milliseconds) && milliseconds > 0\n ? milliseconds / 1000\n : undefined;\n}\n\n/**\n * Built-in identifier extractor — reads the configured credential field from\n * the request body for the per-account key, and `request.detectIp()` for the\n * per-source key. Untruthy values are dropped; a request that yields zero\n * identifiers is left untracked so the middleware no-ops for it.\n */\nfunction buildDefaultIdentifiers(\n request: Request,\n tracked: LoginThrottleIdentifier[],\n credentialField: string,\n): string[] {\n const identifiers: string[] = [];\n\n if (tracked.includes(\"email\")) {\n const value = request.input(credentialField);\n\n if (typeof value === \"string\" && value.trim().length > 0) {\n identifiers.push(`email.${throttleIdentifierHash(\"email\", value)}`);\n }\n }\n\n if (tracked.includes(\"ip\")) {\n const ip = request.detectIp();\n\n if (ip) {\n identifiers.push(`ip.${throttleIdentifierHash(\"ip\", ip)}`);\n }\n }\n\n return identifiers;\n}\n\n/**\n * Failure-aware login throttle. Locks an identifier (account, IP, or both)\n * after too many failed login attempts within a window — without penalising\n * a user who eventually types the right password.\n *\n * Mechanism (per identifier):\n *\n * 1. **Before the controller** — reject with `429` if a lock key is set,\n * skipping the DB lookup AND the bcrypt verify (this also neutralises the\n * CPU-DoS angle of brute-forcing).\n * 2. **After the controller** — observe the outcome via `response.onSent`.\n * On failure (non-2xx by default), bump a fixed-window counter; once it\n * reaches `max`, set a lock key with `lockoutDuration` TTL. On success,\n * clear both the counter and the lock for that identifier.\n *\n * Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,\n * transitively guaranteed via `@warlock.js/core`). Lockout state is shared\n * across replicas — correct security model, because an attacker can't bypass\n * by round-robin to a different pod. Every cache call is guarded so a\n * misconfigured driver fails open (a throttle outage must never escalate\n * into a full auth outage).\n *\n * @example\n * import { loginThrottleMiddleware } from \"@warlock.js/auth\";\n * import { router } from \"@warlock.js/core\";\n *\n * router.post(\"/auth/login\", loginController, {\n * middleware: [loginThrottleMiddleware({ max: 5, window: \"15m\" })],\n * });\n *\n * @example\n * // Per-IP only — avoid account-lockout-as-DoS on anonymous-attack vectors\n * router.post(\"/auth/refresh-token\", refreshController, {\n * middleware: [loginThrottleMiddleware({ by: [\"ip\"], max: 10, window: \"1m\" })],\n * });\n */\nexport function loginThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n const max = options.max ?? 5;\n const window = options.window ?? \"15m\";\n const lockoutDuration = options.lockoutDuration ?? \"15m\";\n const tracked = options.by ?? [\"email\", \"ip\"];\n const credentialField = options.identifierKey ?? \"email\";\n\n return async ({ request, response }) => {\n const identifiers = options.identify\n ? options.identify(request)\n : buildDefaultIdentifiers(request, tracked, credentialField);\n\n if (identifiers.length === 0) return;\n\n warnIfNullDriver();\n\n try {\n for (const identifier of identifiers) {\n const locked = isLocked(await cache.get(lockKey(identifier)));\n\n if (locked) {\n return response.tooManyRequests({\n error: options.errorMessage ?? t(\"auth.errors.tooManyAttempts\"),\n errorCode: AuthErrorCodes.TooManyAttempts,\n });\n }\n }\n } catch (error) {\n // Fail open — a cache outage (driver not initialised, network blip)\n // must never escalate into a full auth outage. Log and let the request\n // through; the onSent recorder below is independently guarded so an\n // outage there is also harmless.\n log.error(\"auth\", \"login-throttle\", error);\n\n return;\n }\n\n response.onSent(async (resolvedResponse: Response) => {\n try {\n const failed = options.isFailure\n ? options.isFailure(resolvedResponse)\n : !resolvedResponse.isOk;\n\n if (!failed) {\n for (const identifier of identifiers) {\n await cache.remove(counterKey(identifier));\n await cache.remove(lockKey(identifier));\n }\n\n return;\n }\n\n for (const identifier of identifiers) {\n const key = counterKey(identifier);\n\n // Open the window on the first failure: the create-only write means\n // only one of several racing servers sets the TTL, and an existing\n // window keeps its deadline (fixed window). The bump itself is an\n // atomic increment, so concurrent failures across servers are never\n // lost (redis INCRBY / pg upsert keep the window's TTL). Passing\n // the TTL on the bump also expires a key recreated after the seed.\n await cache.set(key, 0, { ttl: window, onConflict: \"create\" });\n const count = await cache.increment(key, 1, { ttl: window });\n\n if (count >= max) {\n const lockSeconds = durationSeconds(lockoutDuration);\n\n // The lock stores its own deadline: a driver with sliding\n // expiration (`memoryExtended`) pushes the key's TTL forward on\n // every read, but the deadline in the value does not move, so a\n // client that keeps retrying is still released after\n // `lockoutDuration`.\n await cache.set(\n lockKey(identifier),\n lockSeconds === undefined ? true : Date.now() + lockSeconds * 1000,\n { ttl: lockoutDuration },\n );\n }\n }\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AA2FA,MAAM,iBAAiB;AACvB,MAAM,cAAc;AAEpB,MAAM,cAAc,eAA+B,GAAG,iBAAiB;AACvE,MAAM,WAAW,eAA+B,GAAG,cAAc;;;;;;AAOjE,SAAS,kBAAsC;CAC7C,IAAI;CAEJ,IAAI;EACF,SAAS,WAAW,YAAY,OAAO;CACzC,QAAQ;EACN;CACF;CAEA,OAAO,WAAW,UAAU,MAAM,CAAC,CAAC,OAAO,2BAA2B,CAAC,CAAC,OAAO;AACjF;;;;;;;;;;;;;;;AAgBA,SAAgB,uBAAuB,MAAc,OAAuB;CAC1E,MAAM,aAAa,GAAG,KAAK,GAAG,yBAAyB,KAAK;CAC5D,MAAM,MAAM,gBAAgB;CAE5B,OAAO,MACH,WAAW,UAAU,GAAG,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK,IACzD,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK;AAC1D;AAEA,IAAI,mBAAmB;;;;;AAMvB,SAAS,mBAAyB;CAChC,IAAI,kBAAkB;CAItB,IAFoB,MAAgD,eAAe,SAEhE,QAAQ;CAE3B,mBAAmB;CACnB,IAAI,KACF,QACA,kBACA,2IACF;AACF;;;;;AAMA,SAAS,SAAS,OAAyB;CACzC,IAAI,OAAO,UAAU,UACnB,OAAO,QAAQ,KAAK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Ac,aAGvB,IAFe,SAAS,MAAM,MAAM,IAAI,QAAQ,UAAU,CAAC,CAElD,GACP,OAAO,SAAS,gBAAgB;IAC9B,OAAO,QAAQ,gBAAgB,EAAE,6BAA6B;IAC9D;GACF,CAAC;EAGP,SAAS,OAAO;GAKd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAEzC;EACF;EAEA,SAAS,OAAO,OAAO,qBAA+B;GACpD,IAAI;IAKF,IAAI,EAJW,QAAQ,YACnB,QAAQ,UAAU,gBAAgB,IAClC,CAAC,iBAAiB,OAET;KACX,KAAK,MAAM,cAAc,aAAa;MACpC,MAAM,MAAM,OAAO,WAAW,UAAU,CAAC;MACzC,MAAM,MAAM,OAAO,QAAQ,UAAU,CAAC;KACxC;KAEA;IACF;IAEA,KAAK,MAAM,cAAc,aAAa;KACpC,MAAM,MAAM,WAAW,UAAU;KAQjC,MAAM,MAAM,IAAI,KAAK,GAAG;MAAE,KAAK;MAAQ,YAAY;KAAS,CAAC;KAG7D,IAAI,MAFgB,MAAM,UAAU,KAAK,GAAG,EAAE,KAAK,OAAO,CAAC,KAE9C,KAAK;MAChB,MAAM,cAAc,gBAAgB,eAAe;MAOnD,MAAM,MAAM,IACV,QAAQ,UAAU,GAClB,gBAAgB,SAAY,OAAO,KAAK,IAAI,IAAI,cAAc,KAC9D,EAAE,KAAK,gBAAgB,CACzB;KACF;IACF;GACF,SAAS,OAAO;IACd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAC3C;EACF,CAAC;CACH;AACF"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { defaultNormalizeCredentials } from "../utils/normalize-credentials.mjs";
|
|
1
2
|
import { config } from "@warlock.js/core";
|
|
2
3
|
import { log } from "@warlock.js/logger";
|
|
3
4
|
import ms from "ms";
|
|
@@ -82,6 +83,8 @@ const authConfig = {
|
|
|
82
83
|
canAuthenticate: async (user) => {
|
|
83
84
|
return config.key("auth.canAuthenticate", permitAuthentication)(user);
|
|
84
85
|
},
|
|
86
|
+
/** Login identifier normalizer, or `false` for exact matching. */
|
|
87
|
+
normalizeCredentials: () => config.key("auth.normalizeCredentials", defaultNormalizeCredentials),
|
|
85
88
|
accessToken: {
|
|
86
89
|
/** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */
|
|
87
90
|
secret: () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport { type Algorithm } from \"fast-jwt\";\nimport ms from \"ms\";\nimport type {\n AuthNotification,\n CanAuthenticate,\n LogoutWithoutTokenBehavior,\n OneTimeTokenUrlBuilder,\n PasswordSetter,\n} from \"../contracts/types\";\nimport type {\n AppleProviderConfig,\n AuthProvider,\n DiscordProviderConfig,\n FacebookProviderConfig,\n GitHubProviderConfig,\n GoogleProviderConfig,\n LinkedInProviderConfig,\n OtpSender,\n PasskeysConfig,\n ProviderUserCreator,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport type { Auth } from \"../models/auth.model\";\n\nconst warnedLegacyKeys = new Set<string>();\n\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\n\n/**\n * `ms` accepts anything at runtime and answers `undefined` for a string it\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\n * `(value: ms.StringValue) => number`, which is exactly what let an\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\n * here, so every caller is forced to deal with the `undefined`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * Turn a configured lifetime into a positive number of milliseconds, or throw\n * naming the key.\n *\n * A token lifetime is a security boundary, so an unusable value is a hard error\n * rather than a silent fallback: substituting a default would trade one\n * unintended lifetime for another, just as quietly — and quiet is the whole\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\n *\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\n * claim** and an `Invalid Date` written to the token row.\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\n * emits with **no `exp` claim** — it survives any guard that only rejects\n * `undefined`. `\"-1h\"` signs an already-expired token.\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\n */\nfunction parseDuration(key: string, raw: unknown): number {\n let parsed: number | string | undefined;\n\n try {\n parsed = parseMs(raw);\n } catch {\n // ms throws (rather than returning undefined) for \"\" and non-strings\n parsed = undefined;\n }\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\n );\n }\n\n return parsed;\n}\n\n/** Email-verification token lifetime used when nothing is configured. */\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\n\n/** Password-reset token lifetime used when nothing is configured. */\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\n\n/** Passkey challenge lifetime used when nothing is configured. */\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\n\n/** OTP lifetime used when nothing is configured. */\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\n\n/** Access-token lifetime used when nothing is configured. */\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\n\n/**\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\n *\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\n * keep working after the config split.\n */\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\n const fromNew = config.key(`auth.${newKey}`);\n\n if (fromNew !== undefined && fromNew !== null) {\n return fromNew as T;\n }\n\n const fromLegacy = config.key(`auth.${legacyKey}`);\n\n if (fromLegacy !== undefined && fromLegacy !== null) {\n if (!warnedLegacyKeys.has(legacyKey)) {\n warnedLegacyKeys.add(legacyKey);\n log.warn(\n \"auth\",\n \"config-deprecation\",\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\n );\n }\n\n return fromLegacy as T;\n }\n\n return fallback as T;\n}\n\n/**\n * Typed, backward-compatible access to auth configuration. The service and the\n * jwt signer read configuration exclusively through here, so the new split\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\n */\nexport const authConfig = {\n canAuthenticate: async (user: Auth): Promise<boolean> => {\n const canAuthenticate = config.key<CanAuthenticate>(\n \"auth.canAuthenticate\",\n permitAuthentication,\n );\n\n return canAuthenticate(user);\n },\n accessToken: {\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\n secret: (): string => {\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\n\n if (!secret) {\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\n }\n\n return secret;\n },\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\n * to 1 hour when unset; throws naming the key when the configured value is\n * not a positive `ms` duration. See {@link parseDuration}.\n */\n expiresInMs: (): number =>\n parseDuration(\n \"accessToken.expiresIn\",\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\n ),\n },\n pageAuth: {\n /**\n * Login path a guarded PAGE route redirects a logged-out browser to.\n *\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\n * to opt a browser-facing app into login-redirect UX: a logged-out human\n * navigating to a guarded page lands on the login screen instead of reading\n * a raw JSON error blob. Finding b9ab9804.\n */\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed. Defaults to\n * `\"returnUrl\"`.\n */\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\n },\n cookie: {\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\n /** Select the request-scoped cookie Domain; undefined keeps it host-only. */\n cookieDomain: (): CookieDomainResolver | undefined => config.key(\"auth.cookie.cookieDomain\"),\n },\n csrf: {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * beyond the request's own origin. @default []\n */\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\n },\n verification: {\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\n expiresInMs: (): number =>\n parseDuration(\n \"verification.expiresIn\",\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\n ),\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\n /** App notification replacing the default verification email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\n },\n passwordReset: {\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\n expiresInMs: (): number =>\n parseDuration(\n \"passwordReset.expiresIn\",\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\n ),\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\n /** App notification replacing the default reset email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\n /** App-owned password writer replacing the default. */\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\n },\n providers: {\n /** `auth.providers.google`, when configured. */\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\n /** `auth.providers.github`, when configured. */\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\n /** `auth.providers.discord`, when configured. */\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\n /** `auth.providers.linkedin`, when configured. */\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\n /** `auth.providers.apple`, when configured. */\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\n /** `auth.providers.facebook`, when configured. */\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\n /** `auth.providers.x`, when configured. */\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\n /** An app-registered provider under `auth.providers.custom.<name>`. */\n custom: (name: string): AuthProvider | undefined => {\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\n\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\n },\n /** User attribute a verified provider email is matched against. @default \"email\" */\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\n /** App-owned user creation for a first provider login. */\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\n },\n passkeys: {\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\n settings: (): PasskeysConfig => {\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\n\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\n throw new Error(\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\n );\n }\n\n return settings;\n },\n /** Allowed ceremony origins, as a list. */\n origins: (): string[] => {\n const { origin } = authConfig.passkeys.settings();\n\n return Array.isArray(origin) ? origin : [origin];\n },\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n challengeExpiresInMs: (): number =>\n parseDuration(\n \"passkeys.challengeExpiresIn\",\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\n ),\n },\n otp: {\n /** Notifications channel the code is sent through. @default \"sms\" */\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\n /** User attribute holding the phone number. @default \"phone\" */\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n expiresInMs: (): number =>\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\n /** Verify attempts before the code is invalidated. @default 5 */\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\n /** The message text for a code. */\n message: (code: string): string => {\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\n\n return build ? build(code) : `Your verification code is ${code}`;\n },\n /** App-owned delivery replacing the notifications channel send. */\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\n },\n refreshToken: {\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\n secret: (): string | undefined => resolve(\"refreshToken.secret\", \"jwt.refresh.secret\"),\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\n * naming the key when the configured value is not a positive `ms` duration.\n */\n expiresInMs: (): number =>\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\n },\n};\n"],"mappings":";;;;;AA2BA,MAAM,mCAAmB,IAAI,IAAY;AAEzC,MAAM,6BAAuD;;;;;;;;;;AAW7D,MAAM,UAAU;;;;;;;;;;;;;;;;;;AAmBhB,SAAS,cAAc,KAAa,KAAsB;CACxD,IAAI;CAEJ,IAAI;EACF,SAAS,QAAQ,GAAG;CACtB,QAAQ;EAEN,SAAS;CACX;CAEA,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,QAAQ,IAAI,IAAI,KAAK,UAAU,GAAG,EAAE,mGAEtC;CAGF,OAAO;AACT;;AAGA,MAAM,kCAAkC;;AAGxC,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AI,oCAAoC,oCAAoC,CACrF;CACJ;CACA,KAAK;;EAEH,eAAuB,OAAO,IAAI,oBAAoB,KAAK;;EAE3D,kBAA0B,OAAO,IAAI,uBAAuB,OAAO;;EAEnE,mBACE,cAAc,iBAAiB,OAAO,IAAI,sBAAsB,sBAAsB,CAAC;;EAEzF,mBAA2B,OAAO,IAAI,wBAAwB,CAAC;;EAE/D,UAAU,SAAyB;GACjC,MAAM,QAAQ,OAAO,IAA4C,kBAAkB;GAEnF,OAAO,QAAQ,MAAM,IAAI,IAAI,6BAA6B;EAC5D;;EAEA,YAAmC,OAAO,IAAI,eAAe;CAC/D;CACA,cAAc;;EAEZ,cAAkC,QAAQ,uBAAuB,oBAAoB;;EAErF,eAAwB,QAAQ,wBAAwB,uBAAuB,IAAI;;EAEnF,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
|
|
1
|
+
{"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport { type Algorithm } from \"fast-jwt\";\nimport ms from \"ms\";\nimport type {\n AuthNotification,\n CanAuthenticate,\n NormalizeCredentials,\n LogoutWithoutTokenBehavior,\n OneTimeTokenUrlBuilder,\n PasswordSetter,\n} from \"../contracts/types\";\nimport type {\n AppleProviderConfig,\n AuthProvider,\n DiscordProviderConfig,\n FacebookProviderConfig,\n GitHubProviderConfig,\n GoogleProviderConfig,\n LinkedInProviderConfig,\n OtpSender,\n PasskeysConfig,\n ProviderUserCreator,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport type { Auth } from \"../models/auth.model\";\nimport { defaultNormalizeCredentials } from \"../utils/normalize-credentials\";\n\nconst warnedLegacyKeys = new Set<string>();\n\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\n\n/**\n * `ms` accepts anything at runtime and answers `undefined` for a string it\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\n * `(value: ms.StringValue) => number`, which is exactly what let an\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\n * here, so every caller is forced to deal with the `undefined`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * Turn a configured lifetime into a positive number of milliseconds, or throw\n * naming the key.\n *\n * A token lifetime is a security boundary, so an unusable value is a hard error\n * rather than a silent fallback: substituting a default would trade one\n * unintended lifetime for another, just as quietly — and quiet is the whole\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\n *\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\n * claim** and an `Invalid Date` written to the token row.\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\n * emits with **no `exp` claim** — it survives any guard that only rejects\n * `undefined`. `\"-1h\"` signs an already-expired token.\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\n */\nfunction parseDuration(key: string, raw: unknown): number {\n let parsed: number | string | undefined;\n\n try {\n parsed = parseMs(raw);\n } catch {\n // ms throws (rather than returning undefined) for \"\" and non-strings\n parsed = undefined;\n }\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\n );\n }\n\n return parsed;\n}\n\n/** Email-verification token lifetime used when nothing is configured. */\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\n\n/** Password-reset token lifetime used when nothing is configured. */\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\n\n/** Passkey challenge lifetime used when nothing is configured. */\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\n\n/** OTP lifetime used when nothing is configured. */\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\n\n/** Access-token lifetime used when nothing is configured. */\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\n\n/**\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\n *\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\n * keep working after the config split.\n */\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\n const fromNew = config.key(`auth.${newKey}`);\n\n if (fromNew !== undefined && fromNew !== null) {\n return fromNew as T;\n }\n\n const fromLegacy = config.key(`auth.${legacyKey}`);\n\n if (fromLegacy !== undefined && fromLegacy !== null) {\n if (!warnedLegacyKeys.has(legacyKey)) {\n warnedLegacyKeys.add(legacyKey);\n log.warn(\n \"auth\",\n \"config-deprecation\",\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\n );\n }\n\n return fromLegacy as T;\n }\n\n return fallback as T;\n}\n\n/**\n * Typed, backward-compatible access to auth configuration. The service and the\n * jwt signer read configuration exclusively through here, so the new split\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\n */\nexport const authConfig = {\n canAuthenticate: async (user: Auth): Promise<boolean> => {\n const canAuthenticate = config.key<CanAuthenticate>(\n \"auth.canAuthenticate\",\n permitAuthentication,\n );\n\n return canAuthenticate(user);\n },\n /** Login identifier normalizer, or `false` for exact matching. */\n normalizeCredentials: (): false | NormalizeCredentials =>\n config.key<false | NormalizeCredentials>(\n \"auth.normalizeCredentials\",\n defaultNormalizeCredentials,\n ),\n accessToken: {\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\n secret: (): string => {\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\n\n if (!secret) {\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\n }\n\n return secret;\n },\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\n * to 1 hour when unset; throws naming the key when the configured value is\n * not a positive `ms` duration. See {@link parseDuration}.\n */\n expiresInMs: (): number =>\n parseDuration(\n \"accessToken.expiresIn\",\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\n ),\n },\n pageAuth: {\n /**\n * Login path a guarded PAGE route redirects a logged-out browser to.\n *\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\n * to opt a browser-facing app into login-redirect UX: a logged-out human\n * navigating to a guarded page lands on the login screen instead of reading\n * a raw JSON error blob. Finding b9ab9804.\n */\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed. Defaults to\n * `\"returnUrl\"`.\n */\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\n },\n cookie: {\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\n /** Select the request-scoped cookie Domain; undefined keeps it host-only. */\n cookieDomain: (): CookieDomainResolver | undefined => config.key(\"auth.cookie.cookieDomain\"),\n },\n csrf: {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * beyond the request's own origin. @default []\n */\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\n },\n verification: {\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\n expiresInMs: (): number =>\n parseDuration(\n \"verification.expiresIn\",\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\n ),\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\n /** App notification replacing the default verification email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\n },\n passwordReset: {\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\n expiresInMs: (): number =>\n parseDuration(\n \"passwordReset.expiresIn\",\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\n ),\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\n /** App notification replacing the default reset email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\n /** App-owned password writer replacing the default. */\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\n },\n providers: {\n /** `auth.providers.google`, when configured. */\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\n /** `auth.providers.github`, when configured. */\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\n /** `auth.providers.discord`, when configured. */\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\n /** `auth.providers.linkedin`, when configured. */\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\n /** `auth.providers.apple`, when configured. */\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\n /** `auth.providers.facebook`, when configured. */\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\n /** `auth.providers.x`, when configured. */\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\n /** An app-registered provider under `auth.providers.custom.<name>`. */\n custom: (name: string): AuthProvider | undefined => {\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\n\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\n },\n /** User attribute a verified provider email is matched against. @default \"email\" */\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\n /** App-owned user creation for a first provider login. */\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\n },\n passkeys: {\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\n settings: (): PasskeysConfig => {\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\n\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\n throw new Error(\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\n );\n }\n\n return settings;\n },\n /** Allowed ceremony origins, as a list. */\n origins: (): string[] => {\n const { origin } = authConfig.passkeys.settings();\n\n return Array.isArray(origin) ? origin : [origin];\n },\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n challengeExpiresInMs: (): number =>\n parseDuration(\n \"passkeys.challengeExpiresIn\",\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\n ),\n },\n otp: {\n /** Notifications channel the code is sent through. @default \"sms\" */\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\n /** User attribute holding the phone number. @default \"phone\" */\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n expiresInMs: (): number =>\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\n /** Verify attempts before the code is invalidated. @default 5 */\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\n /** The message text for a code. */\n message: (code: string): string => {\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\n\n return build ? build(code) : `Your verification code is ${code}`;\n },\n /** App-owned delivery replacing the notifications channel send. */\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\n },\n refreshToken: {\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\n secret: (): string | undefined => resolve(\"refreshToken.secret\", \"jwt.refresh.secret\"),\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\n * naming the key when the configured value is not a positive `ms` duration.\n */\n expiresInMs: (): number =>\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\n },\n};\n"],"mappings":";;;;;;AA6BA,MAAM,mCAAmB,IAAI,IAAY;AAEzC,MAAM,6BAAuD;;;;;;;;;;AAW7D,MAAM,UAAU;;;;;;;;;;;;;;;;;;AAmBhB,SAAS,cAAc,KAAa,KAAsB;CACxD,IAAI;CAEJ,IAAI;EACF,SAAS,QAAQ,GAAG;CACtB,QAAQ;EAEN,SAAS;CACX;CAEA,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,QAAQ,IAAI,IAAI,KAAK,UAAU,GAAG,EAAE,mGAEtC;CAGF,OAAO;AACT;;AAGA,MAAM,kCAAkC;;AAGxC,MAAM,oCAAoC;;AAG1C,MAAM,uCAAuC;;AAG7C,MAAM,yBAAyB;;AAG/B,MAAM,kCAAkC;;;;;;;;;AAUxC,SAAS,QAAW,QAAgB,WAAmB,UAAiB;CACtE,MAAM,UAAU,OAAO,IAAI,QAAQ,QAAQ;CAE3C,IAAI,YAAY,UAAa,YAAY,MACvC,OAAO;CAGT,MAAM,aAAa,OAAO,IAAI,QAAQ,WAAW;CAEjD,IAAI,eAAe,UAAa,eAAe,MAAM;EACnD,IAAI,CAAC,iBAAiB,IAAI,SAAS,GAAG;GACpC,iBAAiB,IAAI,SAAS;GAC9B,IAAI,KACF,QACA,sBACA,QAAQ,UAAU,4BAA4B,QAChD;EACF;EAEA,OAAO;CACT;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,aAAa;CACxB,iBAAiB,OAAO,SAAiC;EAMvD,O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F,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
|
|
@@ -94,6 +94,12 @@ declare class AuthService {
|
|
|
94
94
|
* Hash a plaintext password.
|
|
95
95
|
*/
|
|
96
96
|
hashPassword(password: string): Promise<string>;
|
|
97
|
+
/**
|
|
98
|
+
* Look a user up by login identifiers: normalized first (see
|
|
99
|
+
* `auth.normalizeCredentials`), then once more with the values as sent
|
|
100
|
+
* (trimmed) when that differs, so legacy rows stored with capitals still match.
|
|
101
|
+
*/
|
|
102
|
+
private findLoginUser;
|
|
97
103
|
/**
|
|
98
104
|
* Resolve a user by credentials, verifying the password. Returns `null` on a
|
|
99
105
|
* missing user or a wrong password, emitting `login.failed` either way.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.service.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth.service.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"auth.service.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth.service.ts"],"mappings":";;;;;;;;;;qBAqCa,yCAAyC;EACpD,YAAmB;;cAQf;;;;;;;cAOQ;;;;cAOA;;;;cAOA;;;;EAOL,wBAAwB,MAAM,OAAO;;EAS/B,gBAAgB,MAAM,OAAO;UAI5B;UAMA;;;;;;EA0BD,oBACX,MAAM,MACN,UAAU,0BACT,QAAQ;UAMG;;;;;;;UA0CA;;;;;EAgCD,mBACX,MAAM,MACN,aAAa,aACZ,QAAQ;UAcG;;;;EAqDD,gBAAgB,MAAM,MAAM,aAAa,aAAa,QAAQ;;;;;;EAiB9D,cACX,4BACA,aAAa,aACZ,QAAQ;;;;;;EA0F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KACxD,UAAU;;;;;EA0BL,oBACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,UAAU;;qBAcD,aAAW"}
|
|
@@ -7,6 +7,7 @@ import { OneTimeToken } from "../models/one-time-token/one-time-token.model.mjs"
|
|
|
7
7
|
import "../models/one-time-token/index.mjs";
|
|
8
8
|
import { RefreshToken } from "../models/refresh-token/refresh-token.model.mjs";
|
|
9
9
|
import "../models/refresh-token/index.mjs";
|
|
10
|
+
import { trimIdentifiers } from "../utils/normalize-credentials.mjs";
|
|
10
11
|
import { authConfig } from "./auth-config.mjs";
|
|
11
12
|
import { authEvents } from "./auth-events.mjs";
|
|
12
13
|
import { isInvalidCredentialError, jwt } from "./jwt.mjs";
|
|
@@ -337,13 +338,28 @@ var AuthService = class {
|
|
|
337
338
|
return hashPassword(password);
|
|
338
339
|
}
|
|
339
340
|
/**
|
|
341
|
+
* Look a user up by login identifiers: normalized first (see
|
|
342
|
+
* `auth.normalizeCredentials`), then once more with the values as sent
|
|
343
|
+
* (trimmed) when that differs, so legacy rows stored with capitals still match.
|
|
344
|
+
*/
|
|
345
|
+
async findLoginUser(Model, identifiers) {
|
|
346
|
+
const normalize = authConfig.normalizeCredentials();
|
|
347
|
+
if (normalize === false) return await Model.first(identifiers);
|
|
348
|
+
const normalized = normalize(identifiers);
|
|
349
|
+
const user = await Model.first(normalized);
|
|
350
|
+
if (user) return user;
|
|
351
|
+
const asSent = trimIdentifiers(identifiers);
|
|
352
|
+
if (JSON.stringify(asSent) === JSON.stringify(normalized)) return null;
|
|
353
|
+
return await Model.first(asSent);
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
340
356
|
* Resolve a user by credentials, verifying the password. Returns `null` on a
|
|
341
357
|
* missing user or a wrong password, emitting `login.failed` either way.
|
|
342
358
|
*/
|
|
343
359
|
async attemptLogin(Model, data) {
|
|
344
360
|
const { password, ...otherData } = data;
|
|
345
361
|
authEvents.emit("login.attempt", otherData);
|
|
346
|
-
const user = await
|
|
362
|
+
const user = await this.findLoginUser(Model, otherData);
|
|
347
363
|
if (!user) {
|
|
348
364
|
authEvents.emit("login.failed", otherData, "User not found");
|
|
349
365
|
return null;
|
|
@@ -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 { randomUUID } from \"node:crypto\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport {\n config,\n ForbiddenError,\n hashPassword,\n type Request,\n type Response,\n verifyPassword,\n} from \"@warlock.js/core\";\nimport type {\n AccessTokenOutput,\n AuthCredentials,\n ClearAuthCookieOptions,\n DeviceInfo,\n LoginResult,\n SetAuthCookieOptions,\n TokenPair,\n} from \"../contracts/types\";\nimport { assertCsrfOriginAllowed } from \"../middleware/csrf-origin-check\";\nimport { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport { AuthTokenFamily } from \"../models/auth-token-family\";\nimport { OneTimeToken } from \"../models/one-time-token\";\nimport { RefreshToken } from \"../models/refresh-token\";\nimport { authConfig } from \"./auth-config\";\nimport { authEvents } from \"./auth-events\";\nimport { isInvalidCredentialError, jwt } from \"./jwt\";\nimport {\n afterTokenFamilyOperation,\n runTokenFamilyOperation,\n TokenFamilyUnavailableError,\n} from \"./token-family-operation\";\n\n/** Thrown when a request-scoped cookie Domain cannot be resolved safely. */\nexport class CookieDomainRequestRequiredError extends Error {\n public constructor(method: string) {\n super(\n `${method} requires the request when auth.cookie.cookieDomain is configured because the cookie Domain must be resolved for that request.`,\n );\n this.name = \"CookieDomainRequestRequiredError\";\n }\n}\n\nclass AuthService {\n /**\n * Resolve the active access-token model — the package default, or a subclass\n * an app registered under `config.auth.accessToken.model` (e.g. to add a\n * tenant column). The service never references the concrete class directly so\n * an override is a pure config change.\n */\n private get accessTokenModel(): typeof AccessToken {\n return config.key(\"auth.accessToken.model\", AccessToken);\n }\n\n /**\n * Resolve the active refresh-token model (default or registered override).\n */\n private get refreshTokenModel(): typeof RefreshToken {\n return config.key(\"auth.refreshToken.model\", RefreshToken);\n }\n\n /**\n * Resolve the active one-time-token model (default or registered override).\n */\n private get oneTimeTokenModel(): typeof OneTimeToken {\n return config.key(\"auth.oneTimeToken.model\", OneTimeToken);\n }\n\n /**\n * Build the default access-token JWT payload from a user.\n */\n public buildAccessTokenPayload(user: Auth): Record<string, unknown> {\n return {\n id: user.id,\n userType: user.userType,\n created_at: Date.now(),\n };\n }\n\n /** One policy seam keeps account-state checks identical across all auth paths. */\n public async canAuthenticate(user: Auth): Promise<boolean> {\n return authConfig.canAuthenticate(user);\n }\n\n private async assertCanAuthenticate(user: Auth): Promise<void> {\n if (!(await this.canAuthenticate(user))) {\n throw new ForbiddenError(\"This user cannot authenticate.\");\n }\n }\n\n private async issueAccessToken(\n user: Auth,\n payload?: Record<string, unknown>,\n familyId?: string,\n ): Promise<AccessTokenOutput> {\n const data = { ...(payload || this.buildAccessTokenPayload(user)), jti: randomUUID() };\n // Validate before signing so an unusable lifetime cannot mint an immortal token.\n const expiresIn = authConfig.accessToken.expiresInMs();\n\n const token = await jwt.generate(data, { expiresIn });\n const expiresAt = new Date(Date.now() + expiresIn);\n\n if (familyId) {\n await this.accessTokenModel.issue(user, token, expiresAt, familyId);\n } else {\n await this.accessTokenModel.issue(user, token, expiresAt);\n }\n\n return { token, expiresAt: expiresAt.toISOString() };\n }\n\n /**\n * Sign + persist an access token for the user and return the token with its\n * expiry. The expiry is computed locally from `expiresIn` rather than by\n * re-verifying the token we just signed.\n */\n public async generateAccessToken(\n user: Auth,\n payload?: Record<string, unknown>,\n ): Promise<AccessTokenOutput> {\n await this.assertCanAuthenticate(user);\n\n return this.issueAccessToken(user, payload);\n }\n\n private async issueRefreshToken(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ensuredFamily?: AuthTokenFamily,\n ): Promise<RefreshToken | undefined> {\n if (!authConfig.refreshToken.enabled()) return;\n\n // Validate the lifetime first — before the per-user cap is enforced, before\n // anything is signed — so a bad value can never revoke a user's oldest\n // session on its way to failing.\n const expiresIn = authConfig.refreshToken.expiresInMs();\n\n const familyId = deviceInfo?.familyId || Random.string(32);\n\n const family = ensuredFamily ?? (await AuthTokenFamily.ensure(user, familyId));\n\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n const payload = {\n userId: user.id,\n userType: user.userType,\n familyId,\n jti: randomUUID(),\n };\n\n const expiresAt = new Date(Date.now() + expiresIn).toISOString();\n\n await this.refreshTokenModel.enforceMax(user, authConfig.refreshToken.maxPerUser());\n\n const token = await jwt.generateRefreshToken(payload, { expiresIn });\n\n return this.refreshTokenModel.issue(user, token, { familyId, expiresAt, deviceInfo });\n }\n\n /**\n * Keep issuance into an explicitly reused family in the same durable\n * transition boundary as rotation and revocation. A new, caller-unspecified\n * family has no concurrent session to protect and retains the lightweight\n * issuance path.\n */\n private async issueInSuppliedFamily<T>(\n user: Auth,\n familyId: string,\n issue: (family: AuthTokenFamily) => Promise<T>,\n ): Promise<T> {\n // Preserve the established error for a family that was already revoked\n // before issuance started. The coordinator covers a revoke that races\n // after this observation.\n const family = await AuthTokenFamily.ensure(user, familyId);\n\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n try {\n return await runTokenFamilyOperation(familyId, issue);\n } catch (error) {\n // Do not expose a timing-dependent error shape to callers: a family\n // revoked between ensure() and the transaction is the same unusable\n // family condition as one found above.\n if (error instanceof TokenFamilyUnavailableError) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n throw error;\n }\n }\n\n /**\n * Sign + persist a refresh token for the user (enforcing the per-user cap\n * first). Resolves to `undefined` when refresh tokens are disabled in config.\n */\n public async createRefreshToken(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ): Promise<RefreshToken | undefined> {\n if (!authConfig.refreshToken.enabled()) return;\n\n await this.assertCanAuthenticate(user);\n\n if (deviceInfo?.familyId) {\n return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) =>\n this.issueRefreshToken(user, deviceInfo, family),\n );\n }\n\n return this.issueRefreshToken(user, deviceInfo);\n }\n\n private async issueTokenPair(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ensuredFamily?: AuthTokenFamily,\n ): Promise<TokenPair> {\n const refreshEnabled = authConfig.refreshToken.enabled();\n const familyId = deviceInfo?.familyId || Random.string(32);\n\n const family = refreshEnabled\n ? (ensuredFamily ?? (await AuthTokenFamily.ensure(user, familyId)))\n : undefined;\n\n if (family) {\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n }\n\n const accessToken = await this.issueAccessToken(\n user,\n deviceInfo?.payload,\n refreshEnabled ? familyId : undefined,\n );\n const refreshToken = await this.issueRefreshToken(\n user,\n refreshEnabled ? { ...deviceInfo, familyId } : deviceInfo,\n family,\n );\n\n const tokenPair: TokenPair = {\n accessToken,\n refreshToken: refreshToken\n ? {\n token: refreshToken.get(\"token\"),\n expiresAt: refreshToken.get(\"expires_at\"),\n }\n : undefined,\n };\n\n afterTokenFamilyOperation(() => authEvents.emit(\"token.created\", user, tokenPair));\n\n if (refreshToken) {\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"session.created\", user, refreshToken, deviceInfo),\n );\n }\n\n return tokenPair;\n }\n\n /**\n * Issue both an access and a refresh token, emitting the creation events.\n */\n public async createTokenPair(user: Auth, deviceInfo?: DeviceInfo): Promise<TokenPair> {\n await this.assertCanAuthenticate(user);\n\n if (authConfig.refreshToken.enabled() && deviceInfo?.familyId) {\n return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) =>\n this.issueTokenPair(user, deviceInfo, family),\n );\n }\n\n return this.issueTokenPair(user, deviceInfo);\n }\n\n /**\n * Exchange a refresh token for a new token pair, with rotation + replay\n * detection. A concurrent reuse of the same token loses the atomic revoke and\n * is treated as a breach — the whole family is revoked and the request fails.\n */\n public async refreshTokens(\n refreshTokenString: string,\n deviceInfo?: DeviceInfo,\n ): Promise<TokenPair | null> {\n let decoded: {\n userId: number;\n userType: string;\n familyId: string;\n } | null;\n\n try {\n decoded = await jwt.verifyRefreshToken<{\n userId: number;\n userType: string;\n familyId: string;\n }>(refreshTokenString);\n } catch (error) {\n if (isInvalidCredentialError(error)) return null;\n\n throw error;\n }\n\n if (!decoded) return null;\n\n const presentedToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n\n if (!presentedToken || !this.refreshIdentityMatches(presentedToken, decoded)) return null;\n\n await AuthTokenFamily.ensure(\n { id: decoded.userId, userType: decoded.userType } as Auth,\n presentedToken.familyId,\n );\n return runTokenFamilyOperation(presentedToken.familyId, async () => {\n // Each serializable attempt must read the current row in its own snapshot.\n const refreshToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!refreshToken || !this.refreshIdentityMatches(refreshToken, decoded)) return null;\n if (!refreshToken.isValid) {\n // An already-invalid token may be a replay of a rotated credential.\n if (refreshToken) {\n await this.revokeTokenFamily(refreshToken.familyId);\n }\n\n return null;\n }\n\n const UserModel = config.key(`auth.userType.${decoded.userType}`);\n\n if (!UserModel) {\n throw new Error(`User type ${decoded.userType} is unknown type.`);\n }\n\n const user = (await UserModel.find(decoded.userId)) as Auth | null;\n\n if (!user) return null;\n\n if (!(await this.canAuthenticate(user))) return null;\n\n const rotationEnabled = authConfig.refreshToken.rotation();\n\n if (rotationEnabled) {\n const won = await refreshToken.revokeIfActive();\n\n if (!won) {\n // A concurrent request already rotated this token.\n await this.revokeTokenFamily(refreshToken.familyId);\n\n return null;\n }\n } else {\n await refreshToken.markAsUsed();\n }\n\n const newTokenPair = await this.issueTokenPair(user, {\n ...deviceInfo,\n familyId: refreshToken.familyId,\n });\n\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.refreshed\", user, newTokenPair, refreshToken),\n );\n\n return newTokenPair;\n }).catch((error) => {\n if (error instanceof TokenFamilyUnavailableError) return null;\n throw error;\n });\n }\n\n /**\n * Opt-in browser-session renewal. Unlike {@link refreshTokens}, this permits\n * a short duplicate presentation to receive the exact committed successor\n * pair. It is deliberately not used by the legacy/public refresh API.\n */\n public async renewAutomaticSession(\n refreshTokenString: string,\n expectedUserType: string,\n options: { overlapMs?: number; deviceInfo?: DeviceInfo; maxAgeMs?: number } = {},\n ): Promise<TokenPair | null> {\n let decoded: { userId: number; userType: string; familyId: string } | null;\n try {\n decoded = await jwt.verifyRefreshToken<{\n userId: number;\n userType: string;\n familyId: string;\n }>(refreshTokenString);\n } catch (error) {\n if (isInvalidCredentialError(error)) return null;\n throw error;\n }\n\n if (!decoded || decoded.userType !== expectedUserType) return null;\n const presentedToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!presentedToken || !this.refreshIdentityMatches(presentedToken, decoded)) return null;\n\n await AuthTokenFamily.ensure(\n { id: decoded.userId, userType: decoded.userType } as Auth,\n presentedToken.familyId,\n );\n return runTokenFamilyOperation(presentedToken.familyId, async () => {\n // A retry can follow another process's committed rotation. Never reuse\n // a model captured before the transaction or before a failed attempt.\n const oldToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!oldToken || !this.refreshIdentityMatches(oldToken, decoded)) return null;\n if (!oldToken.isValid) {\n const successor = await this.readAutomaticSuccessor(oldToken, decoded, options.overlapMs);\n if (successor) return successor;\n if (\n this.isAutomaticOverlapOpen(oldToken, options.overlapMs) &&\n this.hasSuccessor(oldToken)\n ) {\n return null;\n }\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n // Rotation never extends a family past `maxAgeMs` from its first issue.\n if (\n options.maxAgeMs !== undefined &&\n (await this.familyExceedsMaxAge(oldToken.familyId, options.maxAgeMs))\n ) {\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n const UserModel = config.key(`auth.userType.${decoded.userType}`);\n if (!UserModel) throw new Error(`User type ${decoded.userType} is unknown type.`);\n const user = (await UserModel.find(decoded.userId)) as Auth | null;\n if (!user || !(await this.canAuthenticate(user))) return null;\n\n if (!(await oldToken.revokeIfActive())) {\n // A newer successor is never substituted here. A stale automatic\n // response must fail quietly rather than revoke a legitimate family.\n const currentToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!currentToken) return null;\n const successor = await this.readAutomaticSuccessor(\n currentToken,\n decoded,\n options.overlapMs,\n );\n if (successor) return successor;\n if (\n this.isAutomaticOverlapOpen(currentToken, options.overlapMs) &&\n this.hasSuccessor(currentToken)\n )\n return null;\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n const pair = await this.issueTokenPair(user, {\n ...options.deviceInfo,\n familyId: oldToken.familyId,\n });\n const successorAccess = await this.accessTokenModel.findByToken(pair.accessToken.token);\n const successorRefresh = pair.refreshToken\n ? await this.refreshTokenModel.findByToken(pair.refreshToken.token)\n : null;\n if (!successorAccess || !successorRefresh) {\n throw new Error(\"Automatic renewal did not persist a complete successor pair\");\n }\n\n // `revokeIfActive()` updates the database, not this hydrated instance.\n // Saving that stale instance would write its old `revoked_at: null` back\n // and reopen the predecessor. Update only the successor columns instead.\n const linked = await this.refreshTokenModel.atomic(\n { id: oldToken.id },\n {\n $set: {\n successor_access_token_id: successorAccess.id,\n successor_refresh_token_id: successorRefresh.id,\n },\n },\n );\n if (linked !== 1) throw new Error(\"Automatic renewal could not link its successor pair\");\n afterTokenFamilyOperation(() => authEvents.emit(\"token.refreshed\", user, pair, oldToken));\n return pair;\n }).catch((error) => {\n if (error instanceof TokenFamilyUnavailableError) return null;\n throw error;\n });\n }\n\n /**\n * Whether the family's first issue is older than `maxAgeMs`. The start is the\n * family row's `created_at`, falling back to its oldest refresh token when\n * the row carries none (an upserted legacy family).\n */\n private async familyExceedsMaxAge(familyId: string, maxAgeMs: number): Promise<boolean> {\n const family = await AuthTokenFamily.findByFamilyId(familyId);\n let started: unknown = family?.get(\"created_at\");\n\n if (!started) {\n const oldest = await this.refreshTokenModel\n .query()\n .where({ family_id: familyId })\n .orderBy(\"created_at\", \"asc\")\n .first();\n\n started = oldest?.get(\"created_at\");\n }\n\n const startedAt = started ? new Date(started as string | number | Date).getTime() : NaN;\n\n // Unknown start: nothing to measure against, so the cap cannot apply.\n if (!Number.isFinite(startedAt)) return false;\n\n return Date.now() - startedAt > maxAgeMs;\n }\n\n private automaticOverlapMs(overlapMs: number | undefined): number {\n return typeof overlapMs === \"number\" && Number.isFinite(overlapMs)\n ? Math.max(0, Math.min(10_000, overlapMs))\n : 5000;\n }\n\n private refreshIdentityMatches(\n token: RefreshToken,\n decoded: { userId: string | number; userType: string; familyId: string },\n ): boolean {\n return (\n token.familyId === decoded.familyId &&\n token.get(\"user_id\") === decoded.userId &&\n token.get(\"user_type\") === decoded.userType\n );\n }\n\n private hasSuccessor(oldToken: RefreshToken): boolean {\n return Boolean(\n oldToken.get(\"successor_access_token_id\") && oldToken.get(\"successor_refresh_token_id\"),\n );\n }\n\n private isAutomaticOverlapOpen(oldToken: RefreshToken, overlapMs: number | undefined): boolean {\n const revokedAt = oldToken.get<Date | undefined>(\"revoked_at\");\n const window = this.automaticOverlapMs(overlapMs);\n const elapsed = revokedAt ? Date.now() - new Date(revokedAt).getTime() : NaN;\n return window > 0 && elapsed >= 0 && elapsed <= window;\n }\n\n private async readAutomaticSuccessor(\n oldToken: RefreshToken,\n decoded: { userId: number; userType: string; familyId: string },\n overlapMs: number | undefined,\n ): Promise<TokenPair | null> {\n if (!this.isAutomaticOverlapOpen(oldToken, overlapMs)) return null;\n const accessId = oldToken.get<string | undefined>(\"successor_access_token_id\");\n const refreshId = oldToken.get<string | undefined>(\"successor_refresh_token_id\");\n if (!accessId || !refreshId) return null;\n const [access, refresh] = await Promise.all([\n this.accessTokenModel.find(accessId),\n this.refreshTokenModel.find(refreshId),\n ]);\n if (!access || access.isExpired || !refresh?.isValid) return null;\n if (\n access.get(\"family_id\") !== decoded.familyId ||\n refresh.get(\"family_id\") !== decoded.familyId ||\n access.get(\"user_id\") !== decoded.userId ||\n refresh.get(\"user_id\") !== decoded.userId ||\n access.get(\"user_type\") !== decoded.userType ||\n refresh.get(\"user_type\") !== decoded.userType\n )\n return null;\n const accessExpiry = new Date(access.get(\"expires_at\")).getTime();\n if (!Number.isFinite(accessExpiry) || accessExpiry <= Date.now()) return null;\n return {\n accessToken: { token: access.get(\"token\"), expiresAt: access.get(\"expires_at\") },\n refreshToken: { token: refresh.get(\"token\"), expiresAt: refresh.get(\"expires_at\") },\n };\n }\n\n /**\n * Verify a plaintext password against a stored hash.\n */\n public async verifyPassword(plainPassword: string, hashedPassword: string): Promise<boolean> {\n return verifyPassword(plainPassword, hashedPassword);\n }\n\n /**\n * Hash a plaintext password.\n */\n public async hashPassword(password: string): Promise<string> {\n return hashPassword(password);\n }\n\n /**\n * Resolve a user by credentials, verifying the password. Returns `null` on a\n * missing user or a wrong password, emitting `login.failed` either way.\n */\n public async attemptLogin<T extends Auth>(\n Model: ChildModel<T>,\n data: AuthCredentials,\n ): Promise<T | null> {\n const { password, ...otherData } = data;\n\n authEvents.emit(\"login.attempt\", otherData);\n\n const user = (await Model.first(otherData)) as T | null;\n\n if (!user) {\n authEvents.emit(\"login.failed\", otherData, \"User not found\");\n\n return null;\n }\n\n if (!(await this.verifyPassword(password, user.string(\"password\")!))) {\n authEvents.emit(\"login.failed\", otherData, \"Invalid password\");\n\n return null;\n }\n\n if (!(await this.canAuthenticate(user))) {\n authEvents.emit(\"login.failed\", otherData, \"Authentication not allowed\");\n\n return null;\n }\n\n return user;\n }\n\n /**\n * Full login flow: validate credentials, issue tokens, emit events. Returns\n * the user + token pair on success, `null` on failure.\n */\n public async login<T extends Auth>(\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T> | null> {\n const user = await this.attemptLogin(Model, credentials);\n\n if (!user) {\n return null;\n }\n\n return this.finalizeLogin(user, deviceInfo);\n }\n\n /**\n * Log in a user some OTHER method already authenticated — a provider\n * callback, a passkey assertion, a one-time code. Applies the\n * `auth.canAuthenticate` policy (403 on refusal), then produces exactly\n * what {@link login} produces: the same tokens, rows and events. Pair with\n * {@link setAuthCookie} for a cookie session, as with password login.\n *\n * Never call this for a user you have not authenticated.\n */\n public async completeLogin<T extends Auth>(\n user: T,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T>> {\n await this.assertCanAuthenticate(user);\n\n return this.finalizeLogin(user, deviceInfo);\n }\n\n /**\n * Cookie login for a browser: same-origin check, credential login, then both\n * session cookies. Unlike the default CSRF guard, the Origin/Referer check\n * runs even when the request carries no cookies (login CSRF): a missing or\n * cross-site Origin/Referer throws `CsrfOriginMismatchError` before any\n * credential is looked at. Returns `null` on bad credentials.\n */\n public async loginWithSessionCookies<T extends Auth>(\n request: Request,\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T> | null> {\n assertCsrfOriginAllowed(request);\n\n const result = await this.login(Model, credentials, deviceInfo);\n\n if (!result) return null;\n\n if (result.tokens.refreshToken) {\n this.setSessionCookies(\n response,\n {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n },\n request,\n );\n } else {\n this.setAuthCookie(response, result.tokens.accessToken, {\n domain: this.cookieDomainFor(\"loginWithSessionCookies\", request),\n });\n }\n\n return result;\n }\n\n /** The one token-issuing tail every login method shares. */\n private async finalizeLogin<T extends Auth>(\n user: T,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T>> {\n if (!authConfig.refreshToken.enabled()) {\n const accessToken = await this.issueAccessToken(user, deviceInfo?.payload);\n\n return { user, tokens: { accessToken } };\n }\n\n const tokens = await this.issueTokenPair(user, deviceInfo);\n\n authEvents.emit(\"login.success\", user, tokens, deviceInfo);\n\n return { user, tokens };\n }\n\n /**\n * Log a user out.\n *\n * @param accessToken - access token string to revoke (optional)\n * @param refreshToken - refresh token string to revoke (optional)\n *\n * When no refresh token is supplied, `config.auth.refreshToken.logoutWithoutToken`\n * decides the behavior: `\"revoke-all\"` (default, fail-safe) revokes every\n * refresh token; `\"error\"` requires the caller to pass one.\n */\n public async logout(user: Auth, accessToken?: string, refreshToken?: string): Promise<void> {\n if (accessToken) {\n await this.removeAccessToken(user, accessToken);\n }\n\n if (refreshToken) {\n const token = await this.refreshTokenModel.findForUser(user, refreshToken);\n\n if (token) {\n await this.revokeTokenFamily(token.familyId);\n authEvents.emit(\"session.destroyed\", user, token);\n }\n } else {\n const behavior = authConfig.refreshToken.logoutWithoutToken();\n\n if (behavior === \"error\") {\n throw new Error(\"Refresh token required for logout\");\n }\n\n await this.revokeAllTokens(user);\n authEvents.emit(\"logout.failsafe\", user);\n }\n\n authEvents.emit(\"logout\", user);\n }\n\n /**\n * Remove a specific access token belonging to the user.\n */\n public async removeAccessToken(user: Auth, token: string): Promise<void> {\n await this.accessTokenModel.deleteForUser(user, token);\n }\n\n /**\n * Remove every access token belonging to the user.\n */\n public async removeAllAccessTokens(user: Auth): Promise<void> {\n await this.accessTokenModel.deleteAllForUser(user);\n }\n\n /**\n * Remove a specific refresh token belonging to the user.\n */\n public async removeRefreshToken(user: Auth, token: string): Promise<void> {\n await this.refreshTokenModel.deleteForUser(user, token);\n }\n\n /**\n * Revoke every active refresh token for the user and delete their access\n * tokens — \"log out of all devices\". Each durable family is first marked through its revision coordinator; an\n * event fires per revoked token.\n */\n public async revokeAllTokens(user: Auth): Promise<void> {\n // Upgrade existing installations lazily before the family scan. Include\n // revoked rows: a rotation may have revoked its predecessor while its\n // durable family still needs logout's marker.\n const existingRows = await this.refreshTokenModel.familiesForUser(user);\n\n for (const token of existingRows) {\n await AuthTokenFamily.ensure(user, token.familyId);\n }\n\n const families = await AuthTokenFamily.activeFor(user);\n\n for (const family of families) {\n await this.revokeTokenFamily(family.get<string>(\"family_id\"));\n }\n\n // A deployment can still have rows created before the additive migration\n // ran; retain the old bulk cleanup as a final conservative backstop.\n const legacyTokens = await this.refreshTokenModel.revokeAllFor(user);\n\n for (const token of legacyTokens) {\n authEvents.emit(\"token.revoked\", user, token);\n }\n await this.removeAllAccessTokens(user);\n\n authEvents.emit(\"logout.all\", user);\n }\n\n /**\n * Revoke an entire token family — rotation breach containment.\n */\n public async revokeTokenFamily(familyId: string): Promise<void> {\n let family = await AuthTokenFamily.findByFamilyId(familyId);\n\n if (!family) {\n const legacyToken = await this.refreshTokenModel.findInFamily(familyId);\n\n if (!legacyToken) return;\n\n family = await AuthTokenFamily.ensure(\n {\n id: legacyToken.get(\"user_id\"),\n userType: legacyToken.get<string>(\"user_type\"),\n } as Auth,\n familyId,\n );\n }\n\n const user = {\n id: family.get(\"user_id\"),\n userType: family.get<string>(\"user_type\"),\n } as Auth;\n\n if (family.isRevoked) {\n // Logout and replay containment are idempotent. Re-run cleanup because a\n // request that lost the original race may have observed stale rows.\n const revokedTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(user, familyId);\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.familyRevoked\", familyId, revokedTokens),\n );\n\n return;\n }\n\n let revokedTokens: RefreshToken[];\n try {\n revokedTokens = await runTokenFamilyOperation(familyId, async (currentFamily) => {\n const familyUser = {\n id: currentFamily.get(\"user_id\"),\n userType: currentFamily.get<string>(\"user_type\"),\n } as Auth;\n const revision = currentFamily.get<number>(\"revision\");\n const revoked = await AuthTokenFamily.revoke(familyId, revision);\n\n if (revoked !== 1) {\n throw new Error(\"Token family revoke lost its revision transition\");\n }\n\n const familyTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(familyUser, familyId);\n\n return familyTokens;\n });\n } catch (error) {\n if (!(error instanceof TokenFamilyUnavailableError)) throw error;\n\n // Another request committed the revoke between the read above and its\n // CAS. A second logout is successful after idempotent cleanup.\n revokedTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(user, familyId);\n }\n\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.familyRevoked\", familyId, revokedTokens),\n );\n }\n\n /**\n * Delete expired tokens (refresh + access) and spent one-time tokens\n * (expired or consumed verification/reset/OTP/passkey rows). Emits `token.expired` per refresh\n * token and `cleanup.completed` with the refresh count. Drives the\n * `auth.cleanup` CLI command.\n */\n public async cleanupExpiredTokens(): Promise<number> {\n const expiredTokens = await this.refreshTokenModel.purgeExpired();\n\n for (const token of expiredTokens) {\n authEvents.emit(\"token.expired\", token);\n }\n\n await this.accessTokenModel.purgeExpired();\n await this.oneTimeTokenModel.purgeSpent();\n\n authEvents.emit(\"cleanup.completed\", expiredTokens.length);\n\n return expiredTokens.length;\n }\n\n /**\n * Find every persisted token — access and refresh — that can never retire\n * itself: an unusable `expires_at`, or a token carrying no `exp` claim.\n *\n * This is the remediation read for the pre-4.12.0 `expiresIn` defect (#25).\n * Nothing else surfaces these rows: `auth.cleanup` selects `expires_at < now`,\n * which an `Invalid Date` never satisfies, and a row whose date column is\n * perfectly fine can still hold a token with no deadline in it. Read-only —\n * pair with {@link purgeNeverExpiringTokens} to act on the answer.\n */\n public async findNeverExpiringTokens(): Promise<{\n accessTokens: AccessToken[];\n refreshTokens: RefreshToken[];\n }> {\n return {\n accessTokens: await this.accessTokenModel.findNeverExpiring(),\n refreshTokens: await this.refreshTokenModel.findNeverExpiring(),\n };\n }\n\n /**\n * Revoke every never-expiring token by deleting its row, emitting\n * `token.revoked` per refresh token. Drives `warlock auth.purge-never-expiring`.\n *\n * Access tokens first: deleting one is immediate revocation, while a refresh\n * token left in place for a moment can only mint an access token through a\n * verifier that now rejects it for the missing `exp`.\n */\n public async purgeNeverExpiringTokens(): Promise<{\n accessTokens: number;\n refreshTokens: number;\n }> {\n const accessTokens = await this.accessTokenModel.purgeNeverExpiring();\n const refreshTokens = await this.refreshTokenModel.purgeNeverExpiring();\n\n // `token.expired` (the event `auth.cleanup` already emits for a removed\n // refresh token) rather than `token.revoked`, which carries a loaded `Auth`\n // this batch path has no reason to fetch a user row for.\n for (const token of refreshTokens) {\n authEvents.emit(\"token.expired\", token);\n }\n\n return { accessTokens: accessTokens.length, refreshTokens: refreshTokens.length };\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public async getActiveSessions(user: Auth): Promise<RefreshToken[]> {\n return this.refreshTokenModel.activeFor(user);\n }\n\n /**\n * `Max-Age` (seconds) `setAuthCookie` should apply, derived from an\n * `AccessTokenOutput`'s `expiresAt` — or `undefined` for a bare token\n * string (a session cookie) or an unparseable `expiresAt`.\n */\n private cookieMaxAgeFromToken(token: string | AccessTokenOutput): number | undefined {\n if (typeof token === \"string\") return undefined;\n\n const expiresAt = new Date(token.expiresAt).getTime();\n\n if (Number.isNaN(expiresAt)) return undefined;\n\n return Math.max(0, Math.round((expiresAt - Date.now()) / 1000));\n }\n\n private cookieDomainFor(method: string, request?: Request): string | undefined {\n const resolver = authConfig.cookie.cookieDomain();\n\n if (!resolver) {\n return undefined;\n }\n\n if (!request) {\n throw new CookieDomainRequestRequiredError(method);\n }\n\n return resolver(request);\n }\n\n /**\n * Write the auth cookie on `response` — the write side of the `cookie:<name>`\n * token source `authMiddleware([], \"cookie:<name>\")` already reads. An explicit\n * app-controller call, never a side effect of {@link login}, so an existing\n * bearer-only app never starts emitting `Set-Cookie` just by upgrading.\n *\n * Attribute flags (`HttpOnly`, `SameSite=Lax`, `Secure` outside dev) come\n * from `response.cookie()`'s own `secureCookieDefaults()` floor — this\n * method never overrides them, only `name`/`path`/`maxAge`. `raw: true`\n * writes the token unquoted, so the same string a `cookie:<name>` source\n * reads back is exactly what was issued, not a JSON-wrapped copy.\n *\n * @param token - the token string, or an `AccessTokenOutput` (e.g. from\n * {@link login}) whose `expiresAt` sets `Max-Age` automatically when\n * `options.maxAge` is not given. A bare string with no `options.maxAge`\n * produces a session cookie.\n *\n * @example\n * const { user, tokens } = await authService.login(User, credentials);\n * authService.setAuthCookie(response, tokens.accessToken);\n */\n public setAuthCookie(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n token: string | AccessTokenOutput,\n options: SetAuthCookieOptions = {},\n ): void {\n const name = options.name ?? authConfig.cookie.name();\n const path = options.path ?? authConfig.cookie.path();\n const tokenValue = typeof token === \"string\" ? token : token.token;\n const maxAge = options.maxAge ?? this.cookieMaxAgeFromToken(token);\n\n response.cookie(name, tokenValue, {\n raw: true,\n path,\n ...(options.domain !== undefined ? { domain: options.domain } : {}),\n ...(maxAge !== undefined ? { maxAge } : {}),\n });\n }\n\n /**\n * Clear the auth cookie {@link setAuthCookie} wrote. An explicit\n * app-controller call — pair it with {@link logout} after the token row is\n * revoked. `path` must match what the cookie was set with, or the browser\n * silently ignores the clear (see `response.clearCookie`'s own doc comment).\n *\n * @example\n * await authService.logout(user, accessToken, refreshToken);\n * authService.clearAuthCookie(response);\n */\n public clearAuthCookie(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n options: ClearAuthCookieOptions = {},\n request?: Request,\n ): void {\n const name = options.name ?? authConfig.cookie.name();\n const path = options.path ?? authConfig.cookie.path();\n const domain = this.cookieDomainFor(\"clearAuthCookie\", request);\n\n if (domain !== undefined) {\n response.clearCookie(name, { path, domain });\n }\n\n response.clearCookie(name, { path });\n }\n\n /**\n * Write the access and refresh cookies of a browser session. Both are\n * `HttpOnly`, `SameSite=Lax`, `Path=/` (the refresh cookie must reach every\n * page) and `Secure` outside development, named by `auth.cookie.name` and\n * `auth.cookie.refreshName`. Each `Max-Age` is derived from its token's\n * `expiresAt`, so the cookie lives exactly as long as the token.\n *\n * @example\n * const { tokens } = await authService.login(User, credentials);\n * authService.setSessionCookies(response, tokens);\n */\n public setSessionCookies(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n tokens: { accessToken: AccessTokenOutput; refreshToken: AccessTokenOutput },\n request?: Request,\n ): void {\n const domain = this.cookieDomainFor(\"setSessionCookies\", request);\n const cookies = [\n [authConfig.cookie.name(), tokens.accessToken],\n [authConfig.cookie.refreshName(), tokens.refreshToken],\n ] as const;\n\n for (const [name, token] of cookies) {\n const maxAge = this.cookieMaxAgeFromToken(token);\n\n response.cookie(name, token.token, {\n raw: true,\n httpOnly: true,\n sameSite: \"lax\",\n path: \"/\",\n ...(domain !== undefined ? { domain } : {}),\n ...(maxAge !== undefined ? { maxAge } : {}),\n });\n }\n }\n\n /**\n * Clear both session cookies {@link setSessionCookies} wrote, on `Path=/`.\n * Pair it with {@link logout} after the token rows are revoked.\n */\n public clearSessionCookies(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n request?: Request,\n ): void {\n const domain = this.cookieDomainFor(\"clearSessionCookies\", request);\n\n for (const name of [authConfig.cookie.name(), authConfig.cookie.refreshName()]) {\n if (domain !== undefined) {\n response.clearCookie(name, { path: \"/\", domain });\n }\n\n response.clearCookie(name, { path: \"/\" });\n }\n }\n}\n\nexport const authService = new AuthService();\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,IAAa,mCAAb,cAAsD,MAAM;CAC1D,AAAO,YAAY,QAAgB;EACjC,MACE,GAAG,OAAO,+HACZ;EACA,KAAK,OAAO;CACd;AACF;AAEA,IAAM,cAAN,MAAkB;;;;;;;CAOhB,IAAY,mBAAuC;EACjD,OAAO,OAAO,IAAI,0BAA0B,WAAW;CACzD;;;;CAKA,IAAY,oBAAyC;EACnD,OAAO,OAAO,IAAI,2BAA2B,YAAY;CAC3D;;;;CAKA,IAAY,oBAAyC;EACnD,OAAO,OAAO,IAAI,2BAA2B,YAAY;CAC3D;;;;CAKA,AAAO,wBAAwB,MAAqC;EAClE,OAAO;GACL,IAAI,KAAK;GACT,UAAU,KAAK;GACf,YAAY,KAAK,IAAI;EACvB;CACF;;CAGA,MAAa,gBAAgB,MAA8B;EACzD,OAAO,WAAW,gBAAgB,IAAI;CACxC;CAEA,MAAc,sBAAsB,MAA2B;EAC7D,IAAI,CAAE,MAAM,KAAK,gBAAgB,IAAI,GACnC,M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AAO,oBACL,UACA,SACM;EACN,MAAM,SAAS,KAAK,gBAAgB,uBAAuB,OAAO;EAElE,KAAK,MAAM,QAAQ,CAAC,WAAW,OAAO,KAAK,GAAG,WAAW,OAAO,YAAY,CAAC,GAAG;GAC9E,IAAI,WAAW,QACb,SAAS,YAAY,MAAM;IAAE,MAAM;IAAK;GAAO,CAAC;GAGlD,SAAS,YAAY,MAAM,EAAE,MAAM,IAAI,CAAC;EAC1C;CACF;AACF;AAEA,MAAa,cAAc,IAAI,YAAY"}
|
|
1
|
+
{"version":3,"file":"auth.service.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth.service.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\nimport { randomUUID } from \"node:crypto\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport {\n config,\n ForbiddenError,\n hashPassword,\n type Request,\n type Response,\n verifyPassword,\n} from \"@warlock.js/core\";\nimport type {\n AccessTokenOutput,\n AuthCredentials,\n ClearAuthCookieOptions,\n DeviceInfo,\n LoginResult,\n SetAuthCookieOptions,\n TokenPair,\n} from \"../contracts/types\";\nimport { assertCsrfOriginAllowed } from \"../middleware/csrf-origin-check\";\nimport { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport { AuthTokenFamily } from \"../models/auth-token-family\";\nimport { OneTimeToken } from \"../models/one-time-token\";\nimport { RefreshToken } from \"../models/refresh-token\";\nimport { authConfig } from \"./auth-config\";\nimport { type AuthIdentifiers, trimIdentifiers } from \"../utils/normalize-credentials\";\nimport { authEvents } from \"./auth-events\";\nimport { isInvalidCredentialError, jwt } from \"./jwt\";\nimport {\n afterTokenFamilyOperation,\n runTokenFamilyOperation,\n TokenFamilyUnavailableError,\n} from \"./token-family-operation\";\n\n/** Thrown when a request-scoped cookie Domain cannot be resolved safely. */\nexport class CookieDomainRequestRequiredError extends Error {\n public constructor(method: string) {\n super(\n `${method} requires the request when auth.cookie.cookieDomain is configured because the cookie Domain must be resolved for that request.`,\n );\n this.name = \"CookieDomainRequestRequiredError\";\n }\n}\n\nclass AuthService {\n /**\n * Resolve the active access-token model — the package default, or a subclass\n * an app registered under `config.auth.accessToken.model` (e.g. to add a\n * tenant column). The service never references the concrete class directly so\n * an override is a pure config change.\n */\n private get accessTokenModel(): typeof AccessToken {\n return config.key(\"auth.accessToken.model\", AccessToken);\n }\n\n /**\n * Resolve the active refresh-token model (default or registered override).\n */\n private get refreshTokenModel(): typeof RefreshToken {\n return config.key(\"auth.refreshToken.model\", RefreshToken);\n }\n\n /**\n * Resolve the active one-time-token model (default or registered override).\n */\n private get oneTimeTokenModel(): typeof OneTimeToken {\n return config.key(\"auth.oneTimeToken.model\", OneTimeToken);\n }\n\n /**\n * Build the default access-token JWT payload from a user.\n */\n public buildAccessTokenPayload(user: Auth): Record<string, unknown> {\n return {\n id: user.id,\n userType: user.userType,\n created_at: Date.now(),\n };\n }\n\n /** One policy seam keeps account-state checks identical across all auth paths. */\n public async canAuthenticate(user: Auth): Promise<boolean> {\n return authConfig.canAuthenticate(user);\n }\n\n private async assertCanAuthenticate(user: Auth): Promise<void> {\n if (!(await this.canAuthenticate(user))) {\n throw new ForbiddenError(\"This user cannot authenticate.\");\n }\n }\n\n private async issueAccessToken(\n user: Auth,\n payload?: Record<string, unknown>,\n familyId?: string,\n ): Promise<AccessTokenOutput> {\n const data = { ...(payload || this.buildAccessTokenPayload(user)), jti: randomUUID() };\n // Validate before signing so an unusable lifetime cannot mint an immortal token.\n const expiresIn = authConfig.accessToken.expiresInMs();\n\n const token = await jwt.generate(data, { expiresIn });\n const expiresAt = new Date(Date.now() + expiresIn);\n\n if (familyId) {\n await this.accessTokenModel.issue(user, token, expiresAt, familyId);\n } else {\n await this.accessTokenModel.issue(user, token, expiresAt);\n }\n\n return { token, expiresAt: expiresAt.toISOString() };\n }\n\n /**\n * Sign + persist an access token for the user and return the token with its\n * expiry. The expiry is computed locally from `expiresIn` rather than by\n * re-verifying the token we just signed.\n */\n public async generateAccessToken(\n user: Auth,\n payload?: Record<string, unknown>,\n ): Promise<AccessTokenOutput> {\n await this.assertCanAuthenticate(user);\n\n return this.issueAccessToken(user, payload);\n }\n\n private async issueRefreshToken(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ensuredFamily?: AuthTokenFamily,\n ): Promise<RefreshToken | undefined> {\n if (!authConfig.refreshToken.enabled()) return;\n\n // Validate the lifetime first — before the per-user cap is enforced, before\n // anything is signed — so a bad value can never revoke a user's oldest\n // session on its way to failing.\n const expiresIn = authConfig.refreshToken.expiresInMs();\n\n const familyId = deviceInfo?.familyId || Random.string(32);\n\n const family = ensuredFamily ?? (await AuthTokenFamily.ensure(user, familyId));\n\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n const payload = {\n userId: user.id,\n userType: user.userType,\n familyId,\n jti: randomUUID(),\n };\n\n const expiresAt = new Date(Date.now() + expiresIn).toISOString();\n\n await this.refreshTokenModel.enforceMax(user, authConfig.refreshToken.maxPerUser());\n\n const token = await jwt.generateRefreshToken(payload, { expiresIn });\n\n return this.refreshTokenModel.issue(user, token, { familyId, expiresAt, deviceInfo });\n }\n\n /**\n * Keep issuance into an explicitly reused family in the same durable\n * transition boundary as rotation and revocation. A new, caller-unspecified\n * family has no concurrent session to protect and retains the lightweight\n * issuance path.\n */\n private async issueInSuppliedFamily<T>(\n user: Auth,\n familyId: string,\n issue: (family: AuthTokenFamily) => Promise<T>,\n ): Promise<T> {\n // Preserve the established error for a family that was already revoked\n // before issuance started. The coordinator covers a revoke that races\n // after this observation.\n const family = await AuthTokenFamily.ensure(user, familyId);\n\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n try {\n return await runTokenFamilyOperation(familyId, issue);\n } catch (error) {\n // Do not expose a timing-dependent error shape to callers: a family\n // revoked between ensure() and the transaction is the same unusable\n // family condition as one found above.\n if (error instanceof TokenFamilyUnavailableError) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n\n throw error;\n }\n }\n\n /**\n * Sign + persist a refresh token for the user (enforcing the per-user cap\n * first). Resolves to `undefined` when refresh tokens are disabled in config.\n */\n public async createRefreshToken(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ): Promise<RefreshToken | undefined> {\n if (!authConfig.refreshToken.enabled()) return;\n\n await this.assertCanAuthenticate(user);\n\n if (deviceInfo?.familyId) {\n return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) =>\n this.issueRefreshToken(user, deviceInfo, family),\n );\n }\n\n return this.issueRefreshToken(user, deviceInfo);\n }\n\n private async issueTokenPair(\n user: Auth,\n deviceInfo?: DeviceInfo,\n ensuredFamily?: AuthTokenFamily,\n ): Promise<TokenPair> {\n const refreshEnabled = authConfig.refreshToken.enabled();\n const familyId = deviceInfo?.familyId || Random.string(32);\n\n const family = refreshEnabled\n ? (ensuredFamily ?? (await AuthTokenFamily.ensure(user, familyId)))\n : undefined;\n\n if (family) {\n if (family.isRevoked) {\n throw new Error(\"Cannot issue tokens for a revoked token family\");\n }\n }\n\n const accessToken = await this.issueAccessToken(\n user,\n deviceInfo?.payload,\n refreshEnabled ? familyId : undefined,\n );\n const refreshToken = await this.issueRefreshToken(\n user,\n refreshEnabled ? { ...deviceInfo, familyId } : deviceInfo,\n family,\n );\n\n const tokenPair: TokenPair = {\n accessToken,\n refreshToken: refreshToken\n ? {\n token: refreshToken.get(\"token\"),\n expiresAt: refreshToken.get(\"expires_at\"),\n }\n : undefined,\n };\n\n afterTokenFamilyOperation(() => authEvents.emit(\"token.created\", user, tokenPair));\n\n if (refreshToken) {\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"session.created\", user, refreshToken, deviceInfo),\n );\n }\n\n return tokenPair;\n }\n\n /**\n * Issue both an access and a refresh token, emitting the creation events.\n */\n public async createTokenPair(user: Auth, deviceInfo?: DeviceInfo): Promise<TokenPair> {\n await this.assertCanAuthenticate(user);\n\n if (authConfig.refreshToken.enabled() && deviceInfo?.familyId) {\n return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) =>\n this.issueTokenPair(user, deviceInfo, family),\n );\n }\n\n return this.issueTokenPair(user, deviceInfo);\n }\n\n /**\n * Exchange a refresh token for a new token pair, with rotation + replay\n * detection. A concurrent reuse of the same token loses the atomic revoke and\n * is treated as a breach — the whole family is revoked and the request fails.\n */\n public async refreshTokens(\n refreshTokenString: string,\n deviceInfo?: DeviceInfo,\n ): Promise<TokenPair | null> {\n let decoded: {\n userId: number;\n userType: string;\n familyId: string;\n } | null;\n\n try {\n decoded = await jwt.verifyRefreshToken<{\n userId: number;\n userType: string;\n familyId: string;\n }>(refreshTokenString);\n } catch (error) {\n if (isInvalidCredentialError(error)) return null;\n\n throw error;\n }\n\n if (!decoded) return null;\n\n const presentedToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n\n if (!presentedToken || !this.refreshIdentityMatches(presentedToken, decoded)) return null;\n\n await AuthTokenFamily.ensure(\n { id: decoded.userId, userType: decoded.userType } as Auth,\n presentedToken.familyId,\n );\n return runTokenFamilyOperation(presentedToken.familyId, async () => {\n // Each serializable attempt must read the current row in its own snapshot.\n const refreshToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!refreshToken || !this.refreshIdentityMatches(refreshToken, decoded)) return null;\n if (!refreshToken.isValid) {\n // An already-invalid token may be a replay of a rotated credential.\n if (refreshToken) {\n await this.revokeTokenFamily(refreshToken.familyId);\n }\n\n return null;\n }\n\n const UserModel = config.key(`auth.userType.${decoded.userType}`);\n\n if (!UserModel) {\n throw new Error(`User type ${decoded.userType} is unknown type.`);\n }\n\n const user = (await UserModel.find(decoded.userId)) as Auth | null;\n\n if (!user) return null;\n\n if (!(await this.canAuthenticate(user))) return null;\n\n const rotationEnabled = authConfig.refreshToken.rotation();\n\n if (rotationEnabled) {\n const won = await refreshToken.revokeIfActive();\n\n if (!won) {\n // A concurrent request already rotated this token.\n await this.revokeTokenFamily(refreshToken.familyId);\n\n return null;\n }\n } else {\n await refreshToken.markAsUsed();\n }\n\n const newTokenPair = await this.issueTokenPair(user, {\n ...deviceInfo,\n familyId: refreshToken.familyId,\n });\n\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.refreshed\", user, newTokenPair, refreshToken),\n );\n\n return newTokenPair;\n }).catch((error) => {\n if (error instanceof TokenFamilyUnavailableError) return null;\n throw error;\n });\n }\n\n /**\n * Opt-in browser-session renewal. Unlike {@link refreshTokens}, this permits\n * a short duplicate presentation to receive the exact committed successor\n * pair. It is deliberately not used by the legacy/public refresh API.\n */\n public async renewAutomaticSession(\n refreshTokenString: string,\n expectedUserType: string,\n options: { overlapMs?: number; deviceInfo?: DeviceInfo; maxAgeMs?: number } = {},\n ): Promise<TokenPair | null> {\n let decoded: { userId: number; userType: string; familyId: string } | null;\n try {\n decoded = await jwt.verifyRefreshToken<{\n userId: number;\n userType: string;\n familyId: string;\n }>(refreshTokenString);\n } catch (error) {\n if (isInvalidCredentialError(error)) return null;\n throw error;\n }\n\n if (!decoded || decoded.userType !== expectedUserType) return null;\n const presentedToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!presentedToken || !this.refreshIdentityMatches(presentedToken, decoded)) return null;\n\n await AuthTokenFamily.ensure(\n { id: decoded.userId, userType: decoded.userType } as Auth,\n presentedToken.familyId,\n );\n return runTokenFamilyOperation(presentedToken.familyId, async () => {\n // A retry can follow another process's committed rotation. Never reuse\n // a model captured before the transaction or before a failed attempt.\n const oldToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!oldToken || !this.refreshIdentityMatches(oldToken, decoded)) return null;\n if (!oldToken.isValid) {\n const successor = await this.readAutomaticSuccessor(oldToken, decoded, options.overlapMs);\n if (successor) return successor;\n if (\n this.isAutomaticOverlapOpen(oldToken, options.overlapMs) &&\n this.hasSuccessor(oldToken)\n ) {\n return null;\n }\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n // Rotation never extends a family past `maxAgeMs` from its first issue.\n if (\n options.maxAgeMs !== undefined &&\n (await this.familyExceedsMaxAge(oldToken.familyId, options.maxAgeMs))\n ) {\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n const UserModel = config.key(`auth.userType.${decoded.userType}`);\n if (!UserModel) throw new Error(`User type ${decoded.userType} is unknown type.`);\n const user = (await UserModel.find(decoded.userId)) as Auth | null;\n if (!user || !(await this.canAuthenticate(user))) return null;\n\n if (!(await oldToken.revokeIfActive())) {\n // A newer successor is never substituted here. A stale automatic\n // response must fail quietly rather than revoke a legitimate family.\n const currentToken = await this.refreshTokenModel.findByToken(refreshTokenString);\n if (!currentToken) return null;\n const successor = await this.readAutomaticSuccessor(\n currentToken,\n decoded,\n options.overlapMs,\n );\n if (successor) return successor;\n if (\n this.isAutomaticOverlapOpen(currentToken, options.overlapMs) &&\n this.hasSuccessor(currentToken)\n )\n return null;\n await this.revokeTokenFamily(oldToken.familyId);\n return null;\n }\n\n const pair = await this.issueTokenPair(user, {\n ...options.deviceInfo,\n familyId: oldToken.familyId,\n });\n const successorAccess = await this.accessTokenModel.findByToken(pair.accessToken.token);\n const successorRefresh = pair.refreshToken\n ? await this.refreshTokenModel.findByToken(pair.refreshToken.token)\n : null;\n if (!successorAccess || !successorRefresh) {\n throw new Error(\"Automatic renewal did not persist a complete successor pair\");\n }\n\n // `revokeIfActive()` updates the database, not this hydrated instance.\n // Saving that stale instance would write its old `revoked_at: null` back\n // and reopen the predecessor. Update only the successor columns instead.\n const linked = await this.refreshTokenModel.atomic(\n { id: oldToken.id },\n {\n $set: {\n successor_access_token_id: successorAccess.id,\n successor_refresh_token_id: successorRefresh.id,\n },\n },\n );\n if (linked !== 1) throw new Error(\"Automatic renewal could not link its successor pair\");\n afterTokenFamilyOperation(() => authEvents.emit(\"token.refreshed\", user, pair, oldToken));\n return pair;\n }).catch((error) => {\n if (error instanceof TokenFamilyUnavailableError) return null;\n throw error;\n });\n }\n\n /**\n * Whether the family's first issue is older than `maxAgeMs`. The start is the\n * family row's `created_at`, falling back to its oldest refresh token when\n * the row carries none (an upserted legacy family).\n */\n private async familyExceedsMaxAge(familyId: string, maxAgeMs: number): Promise<boolean> {\n const family = await AuthTokenFamily.findByFamilyId(familyId);\n let started: unknown = family?.get(\"created_at\");\n\n if (!started) {\n const oldest = await this.refreshTokenModel\n .query()\n .where({ family_id: familyId })\n .orderBy(\"created_at\", \"asc\")\n .first();\n\n started = oldest?.get(\"created_at\");\n }\n\n const startedAt = started ? new Date(started as string | number | Date).getTime() : NaN;\n\n // Unknown start: nothing to measure against, so the cap cannot apply.\n if (!Number.isFinite(startedAt)) return false;\n\n return Date.now() - startedAt > maxAgeMs;\n }\n\n private automaticOverlapMs(overlapMs: number | undefined): number {\n return typeof overlapMs === \"number\" && Number.isFinite(overlapMs)\n ? Math.max(0, Math.min(10_000, overlapMs))\n : 5000;\n }\n\n private refreshIdentityMatches(\n token: RefreshToken,\n decoded: { userId: string | number; userType: string; familyId: string },\n ): boolean {\n return (\n token.familyId === decoded.familyId &&\n token.get(\"user_id\") === decoded.userId &&\n token.get(\"user_type\") === decoded.userType\n );\n }\n\n private hasSuccessor(oldToken: RefreshToken): boolean {\n return Boolean(\n oldToken.get(\"successor_access_token_id\") && oldToken.get(\"successor_refresh_token_id\"),\n );\n }\n\n private isAutomaticOverlapOpen(oldToken: RefreshToken, overlapMs: number | undefined): boolean {\n const revokedAt = oldToken.get<Date | undefined>(\"revoked_at\");\n const window = this.automaticOverlapMs(overlapMs);\n const elapsed = revokedAt ? Date.now() - new Date(revokedAt).getTime() : NaN;\n return window > 0 && elapsed >= 0 && elapsed <= window;\n }\n\n private async readAutomaticSuccessor(\n oldToken: RefreshToken,\n decoded: { userId: number; userType: string; familyId: string },\n overlapMs: number | undefined,\n ): Promise<TokenPair | null> {\n if (!this.isAutomaticOverlapOpen(oldToken, overlapMs)) return null;\n const accessId = oldToken.get<string | undefined>(\"successor_access_token_id\");\n const refreshId = oldToken.get<string | undefined>(\"successor_refresh_token_id\");\n if (!accessId || !refreshId) return null;\n const [access, refresh] = await Promise.all([\n this.accessTokenModel.find(accessId),\n this.refreshTokenModel.find(refreshId),\n ]);\n if (!access || access.isExpired || !refresh?.isValid) return null;\n if (\n access.get(\"family_id\") !== decoded.familyId ||\n refresh.get(\"family_id\") !== decoded.familyId ||\n access.get(\"user_id\") !== decoded.userId ||\n refresh.get(\"user_id\") !== decoded.userId ||\n access.get(\"user_type\") !== decoded.userType ||\n refresh.get(\"user_type\") !== decoded.userType\n )\n return null;\n const accessExpiry = new Date(access.get(\"expires_at\")).getTime();\n if (!Number.isFinite(accessExpiry) || accessExpiry <= Date.now()) return null;\n return {\n accessToken: { token: access.get(\"token\"), expiresAt: access.get(\"expires_at\") },\n refreshToken: { token: refresh.get(\"token\"), expiresAt: refresh.get(\"expires_at\") },\n };\n }\n\n /**\n * Verify a plaintext password against a stored hash.\n */\n public async verifyPassword(plainPassword: string, hashedPassword: string): Promise<boolean> {\n return verifyPassword(plainPassword, hashedPassword);\n }\n\n /**\n * Hash a plaintext password.\n */\n public async hashPassword(password: string): Promise<string> {\n return hashPassword(password);\n }\n\n /**\n * 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\n if (!user) {\n authEvents.emit(\"login.failed\", otherData, \"User not found\");\n\n return null;\n }\n\n if (!(await this.verifyPassword(password, user.string(\"password\")!))) {\n authEvents.emit(\"login.failed\", otherData, \"Invalid password\");\n\n return null;\n }\n\n if (!(await this.canAuthenticate(user))) {\n authEvents.emit(\"login.failed\", otherData, \"Authentication not allowed\");\n\n return null;\n }\n\n return user;\n }\n\n /**\n * Full login flow: validate credentials, issue tokens, emit events. Returns\n * the user + token pair on success, `null` on failure.\n */\n public async login<T extends Auth>(\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T> | null> {\n const user = await this.attemptLogin(Model, credentials);\n\n if (!user) {\n return null;\n }\n\n return this.finalizeLogin(user, deviceInfo);\n }\n\n /**\n * Log in a user some OTHER method already authenticated — a provider\n * callback, a passkey assertion, a one-time code. Applies the\n * `auth.canAuthenticate` policy (403 on refusal), then produces exactly\n * what {@link login} produces: the same tokens, rows and events. Pair with\n * {@link setAuthCookie} for a cookie session, as with password login.\n *\n * Never call this for a user you have not authenticated.\n */\n public async completeLogin<T extends Auth>(\n user: T,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T>> {\n await this.assertCanAuthenticate(user);\n\n return this.finalizeLogin(user, deviceInfo);\n }\n\n /**\n * Cookie login for a browser: same-origin check, credential login, then both\n * session cookies. Unlike the default CSRF guard, the Origin/Referer check\n * runs even when the request carries no cookies (login CSRF): a missing or\n * cross-site Origin/Referer throws `CsrfOriginMismatchError` before any\n * credential is looked at. Returns `null` on bad credentials.\n */\n public async loginWithSessionCookies<T extends Auth>(\n request: Request,\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n Model: ChildModel<T>,\n credentials: AuthCredentials,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T> | null> {\n assertCsrfOriginAllowed(request);\n\n const result = await this.login(Model, credentials, deviceInfo);\n\n if (!result) return null;\n\n if (result.tokens.refreshToken) {\n this.setSessionCookies(\n response,\n {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n },\n request,\n );\n } else {\n this.setAuthCookie(response, result.tokens.accessToken, {\n domain: this.cookieDomainFor(\"loginWithSessionCookies\", request),\n });\n }\n\n return result;\n }\n\n /** The one token-issuing tail every login method shares. */\n private async finalizeLogin<T extends Auth>(\n user: T,\n deviceInfo?: DeviceInfo,\n ): Promise<LoginResult<T>> {\n if (!authConfig.refreshToken.enabled()) {\n const accessToken = await this.issueAccessToken(user, deviceInfo?.payload);\n\n return { user, tokens: { accessToken } };\n }\n\n const tokens = await this.issueTokenPair(user, deviceInfo);\n\n authEvents.emit(\"login.success\", user, tokens, deviceInfo);\n\n return { user, tokens };\n }\n\n /**\n * Log a user out.\n *\n * @param accessToken - access token string to revoke (optional)\n * @param refreshToken - refresh token string to revoke (optional)\n *\n * When no refresh token is supplied, `config.auth.refreshToken.logoutWithoutToken`\n * decides the behavior: `\"revoke-all\"` (default, fail-safe) revokes every\n * refresh token; `\"error\"` requires the caller to pass one.\n */\n public async logout(user: Auth, accessToken?: string, refreshToken?: string): Promise<void> {\n if (accessToken) {\n await this.removeAccessToken(user, accessToken);\n }\n\n if (refreshToken) {\n const token = await this.refreshTokenModel.findForUser(user, refreshToken);\n\n if (token) {\n await this.revokeTokenFamily(token.familyId);\n authEvents.emit(\"session.destroyed\", user, token);\n }\n } else {\n const behavior = authConfig.refreshToken.logoutWithoutToken();\n\n if (behavior === \"error\") {\n throw new Error(\"Refresh token required for logout\");\n }\n\n await this.revokeAllTokens(user);\n authEvents.emit(\"logout.failsafe\", user);\n }\n\n authEvents.emit(\"logout\", user);\n }\n\n /**\n * Remove a specific access token belonging to the user.\n */\n public async removeAccessToken(user: Auth, token: string): Promise<void> {\n await this.accessTokenModel.deleteForUser(user, token);\n }\n\n /**\n * Remove every access token belonging to the user.\n */\n public async removeAllAccessTokens(user: Auth): Promise<void> {\n await this.accessTokenModel.deleteAllForUser(user);\n }\n\n /**\n * Remove a specific refresh token belonging to the user.\n */\n public async removeRefreshToken(user: Auth, token: string): Promise<void> {\n await this.refreshTokenModel.deleteForUser(user, token);\n }\n\n /**\n * Revoke every active refresh token for the user and delete their access\n * tokens — \"log out of all devices\". Each durable family is first marked through its revision coordinator; an\n * event fires per revoked token.\n */\n public async revokeAllTokens(user: Auth): Promise<void> {\n // Upgrade existing installations lazily before the family scan. Include\n // revoked rows: a rotation may have revoked its predecessor while its\n // durable family still needs logout's marker.\n const existingRows = await this.refreshTokenModel.familiesForUser(user);\n\n for (const token of existingRows) {\n await AuthTokenFamily.ensure(user, token.familyId);\n }\n\n const families = await AuthTokenFamily.activeFor(user);\n\n for (const family of families) {\n await this.revokeTokenFamily(family.get<string>(\"family_id\"));\n }\n\n // A deployment can still have rows created before the additive migration\n // ran; retain the old bulk cleanup as a final conservative backstop.\n const legacyTokens = await this.refreshTokenModel.revokeAllFor(user);\n\n for (const token of legacyTokens) {\n authEvents.emit(\"token.revoked\", user, token);\n }\n await this.removeAllAccessTokens(user);\n\n authEvents.emit(\"logout.all\", user);\n }\n\n /**\n * Revoke an entire token family — rotation breach containment.\n */\n public async revokeTokenFamily(familyId: string): Promise<void> {\n let family = await AuthTokenFamily.findByFamilyId(familyId);\n\n if (!family) {\n const legacyToken = await this.refreshTokenModel.findInFamily(familyId);\n\n if (!legacyToken) return;\n\n family = await AuthTokenFamily.ensure(\n {\n id: legacyToken.get(\"user_id\"),\n userType: legacyToken.get<string>(\"user_type\"),\n } as Auth,\n familyId,\n );\n }\n\n const user = {\n id: family.get(\"user_id\"),\n userType: family.get<string>(\"user_type\"),\n } as Auth;\n\n if (family.isRevoked) {\n // Logout and replay containment are idempotent. Re-run cleanup because a\n // request that lost the original race may have observed stale rows.\n const revokedTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(user, familyId);\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.familyRevoked\", familyId, revokedTokens),\n );\n\n return;\n }\n\n let revokedTokens: RefreshToken[];\n try {\n revokedTokens = await runTokenFamilyOperation(familyId, async (currentFamily) => {\n const familyUser = {\n id: currentFamily.get(\"user_id\"),\n userType: currentFamily.get<string>(\"user_type\"),\n } as Auth;\n const revision = currentFamily.get<number>(\"revision\");\n const revoked = await AuthTokenFamily.revoke(familyId, revision);\n\n if (revoked !== 1) {\n throw new Error(\"Token family revoke lost its revision transition\");\n }\n\n const familyTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(familyUser, familyId);\n\n return familyTokens;\n });\n } catch (error) {\n if (!(error instanceof TokenFamilyUnavailableError)) throw error;\n\n // Another request committed the revoke between the read above and its\n // CAS. A second logout is successful after idempotent cleanup.\n revokedTokens = await this.refreshTokenModel.revokeFamily(familyId);\n await this.accessTokenModel.deleteFamilyAndLegacyForUser(user, familyId);\n }\n\n afterTokenFamilyOperation(() =>\n authEvents.emit(\"token.familyRevoked\", familyId, revokedTokens),\n );\n }\n\n /**\n * Delete expired tokens (refresh + access) and spent one-time tokens\n * (expired or consumed verification/reset/OTP/passkey rows). Emits `token.expired` per refresh\n * token and `cleanup.completed` with the refresh count. Drives the\n * `auth.cleanup` CLI command.\n */\n public async cleanupExpiredTokens(): Promise<number> {\n const expiredTokens = await this.refreshTokenModel.purgeExpired();\n\n for (const token of expiredTokens) {\n authEvents.emit(\"token.expired\", token);\n }\n\n await this.accessTokenModel.purgeExpired();\n await this.oneTimeTokenModel.purgeSpent();\n\n authEvents.emit(\"cleanup.completed\", expiredTokens.length);\n\n return expiredTokens.length;\n }\n\n /**\n * Find every persisted token — access and refresh — that can never retire\n * itself: an unusable `expires_at`, or a token carrying no `exp` claim.\n *\n * This is the remediation read for the pre-4.12.0 `expiresIn` defect (#25).\n * Nothing else surfaces these rows: `auth.cleanup` selects `expires_at < now`,\n * which an `Invalid Date` never satisfies, and a row whose date column is\n * perfectly fine can still hold a token with no deadline in it. Read-only —\n * pair with {@link purgeNeverExpiringTokens} to act on the answer.\n */\n public async findNeverExpiringTokens(): Promise<{\n accessTokens: AccessToken[];\n refreshTokens: RefreshToken[];\n }> {\n return {\n accessTokens: await this.accessTokenModel.findNeverExpiring(),\n refreshTokens: await this.refreshTokenModel.findNeverExpiring(),\n };\n }\n\n /**\n * Revoke every never-expiring token by deleting its row, emitting\n * `token.revoked` per refresh token. Drives `warlock auth.purge-never-expiring`.\n *\n * Access tokens first: deleting one is immediate revocation, while a refresh\n * token left in place for a moment can only mint an access token through a\n * verifier that now rejects it for the missing `exp`.\n */\n public async purgeNeverExpiringTokens(): Promise<{\n accessTokens: number;\n refreshTokens: number;\n }> {\n const accessTokens = await this.accessTokenModel.purgeNeverExpiring();\n const refreshTokens = await this.refreshTokenModel.purgeNeverExpiring();\n\n // `token.expired` (the event `auth.cleanup` already emits for a removed\n // refresh token) rather than `token.revoked`, which carries a loaded `Auth`\n // this batch path has no reason to fetch a user row for.\n for (const token of refreshTokens) {\n authEvents.emit(\"token.expired\", token);\n }\n\n return { accessTokens: accessTokens.length, refreshTokens: refreshTokens.length };\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public async getActiveSessions(user: Auth): Promise<RefreshToken[]> {\n return this.refreshTokenModel.activeFor(user);\n }\n\n /**\n * `Max-Age` (seconds) `setAuthCookie` should apply, derived from an\n * `AccessTokenOutput`'s `expiresAt` — or `undefined` for a bare token\n * string (a session cookie) or an unparseable `expiresAt`.\n */\n private cookieMaxAgeFromToken(token: string | AccessTokenOutput): number | undefined {\n if (typeof token === \"string\") return undefined;\n\n const expiresAt = new Date(token.expiresAt).getTime();\n\n if (Number.isNaN(expiresAt)) return undefined;\n\n return Math.max(0, Math.round((expiresAt - Date.now()) / 1000));\n }\n\n private cookieDomainFor(method: string, request?: Request): string | undefined {\n const resolver = authConfig.cookie.cookieDomain();\n\n if (!resolver) {\n return undefined;\n }\n\n if (!request) {\n throw new CookieDomainRequestRequiredError(method);\n }\n\n return resolver(request);\n }\n\n /**\n * Write the auth cookie on `response` — the write side of the `cookie:<name>`\n * token source `authMiddleware([], \"cookie:<name>\")` already reads. An explicit\n * app-controller call, never a side effect of {@link login}, so an existing\n * bearer-only app never starts emitting `Set-Cookie` just by upgrading.\n *\n * Attribute flags (`HttpOnly`, `SameSite=Lax`, `Secure` outside dev) come\n * from `response.cookie()`'s own `secureCookieDefaults()` floor — this\n * method never overrides them, only `name`/`path`/`maxAge`. `raw: true`\n * writes the token unquoted, so the same string a `cookie:<name>` source\n * reads back is exactly what was issued, not a JSON-wrapped copy.\n *\n * @param token - the token string, or an `AccessTokenOutput` (e.g. from\n * {@link login}) whose `expiresAt` sets `Max-Age` automatically when\n * `options.maxAge` is not given. A bare string with no `options.maxAge`\n * produces a session cookie.\n *\n * @example\n * const { user, tokens } = await authService.login(User, credentials);\n * authService.setAuthCookie(response, tokens.accessToken);\n */\n public setAuthCookie(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n token: string | AccessTokenOutput,\n options: SetAuthCookieOptions = {},\n ): void {\n const name = options.name ?? authConfig.cookie.name();\n const path = options.path ?? authConfig.cookie.path();\n const tokenValue = typeof token === \"string\" ? token : token.token;\n const maxAge = options.maxAge ?? this.cookieMaxAgeFromToken(token);\n\n response.cookie(name, tokenValue, {\n raw: true,\n path,\n ...(options.domain !== undefined ? { domain: options.domain } : {}),\n ...(maxAge !== undefined ? { maxAge } : {}),\n });\n }\n\n /**\n * Clear the auth cookie {@link setAuthCookie} wrote. An explicit\n * app-controller call — pair it with {@link logout} after the token row is\n * revoked. `path` must match what the cookie was set with, or the browser\n * silently ignores the clear (see `response.clearCookie`'s own doc comment).\n *\n * @example\n * await authService.logout(user, accessToken, refreshToken);\n * authService.clearAuthCookie(response);\n */\n public clearAuthCookie(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n options: ClearAuthCookieOptions = {},\n request?: Request,\n ): void {\n const name = options.name ?? authConfig.cookie.name();\n const path = options.path ?? authConfig.cookie.path();\n const domain = this.cookieDomainFor(\"clearAuthCookie\", request);\n\n if (domain !== undefined) {\n response.clearCookie(name, { path, domain });\n }\n\n response.clearCookie(name, { path });\n }\n\n /**\n * Write the access and refresh cookies of a browser session. Both are\n * `HttpOnly`, `SameSite=Lax`, `Path=/` (the refresh cookie must reach every\n * page) and `Secure` outside development, named by `auth.cookie.name` and\n * `auth.cookie.refreshName`. Each `Max-Age` is derived from its token's\n * `expiresAt`, so the cookie lives exactly as long as the token.\n *\n * @example\n * const { tokens } = await authService.login(User, credentials);\n * authService.setSessionCookies(response, tokens);\n */\n public setSessionCookies(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n tokens: { accessToken: AccessTokenOutput; refreshToken: AccessTokenOutput },\n request?: Request,\n ): void {\n const domain = this.cookieDomainFor(\"setSessionCookies\", request);\n const cookies = [\n [authConfig.cookie.name(), tokens.accessToken],\n [authConfig.cookie.refreshName(), tokens.refreshToken],\n ] as const;\n\n for (const [name, token] of cookies) {\n const maxAge = this.cookieMaxAgeFromToken(token);\n\n response.cookie(name, token.token, {\n raw: true,\n httpOnly: true,\n sameSite: \"lax\",\n path: \"/\",\n ...(domain !== undefined ? { domain } : {}),\n ...(maxAge !== undefined ? { maxAge } : {}),\n });\n }\n }\n\n /**\n * Clear both session cookies {@link setSessionCookies} wrote, on `Path=/`.\n * Pair it with {@link logout} after the token rows are revoked.\n */\n public clearSessionCookies(\n response: { [K in \"cookie\" | \"clearCookie\"]: (...args: Parameters<Response[K]>) => unknown },\n request?: Request,\n ): void {\n const domain = this.cookieDomainFor(\"clearSessionCookies\", request);\n\n for (const name of [authConfig.cookie.name(), authConfig.cookie.refreshName()]) {\n if (domain !== undefined) {\n response.clearCookie(name, { path: \"/\", domain });\n }\n\n response.clearCookie(name, { path: \"/\" });\n }\n }\n}\n\nexport const authService =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;IAAK;GAAO,CAAC;GAGlD,SAAS,YAAY,MAAM,EAAE,MAAM,IAAI,CAAC;EAC1C;CACF;AACF;AAEA,MAAa,cAAc,IAAI,YAAY"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
//#region ../../packages/auth/src/utils/normalize-credentials.ts
|
|
2
|
+
/**
|
|
3
|
+
* Normalize one email-like identifier: trim it and lower-case it.
|
|
4
|
+
*
|
|
5
|
+
* This is the single rule the login lookup and the login throttle both use,
|
|
6
|
+
* so `" Sara@x.io"` and `"sara@x.io"` are the same account to both.
|
|
7
|
+
*/
|
|
8
|
+
function normalizeEmailIdentifier(value) {
|
|
9
|
+
return value.trim().toLowerCase();
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Trim every string identifier value, leaving other values untouched. This is
|
|
13
|
+
* the "as sent" form the login lookup falls back to for legacy rows.
|
|
14
|
+
*/
|
|
15
|
+
function trimIdentifiers(identifiers) {
|
|
16
|
+
const trimmed = {};
|
|
17
|
+
for (const [key, value] of Object.entries(identifiers)) trimmed[key] = typeof value === "string" ? value.trim() : value;
|
|
18
|
+
return trimmed;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Default credential normalization: trim string values and lower-case the
|
|
22
|
+
* `email` field.
|
|
23
|
+
*/
|
|
24
|
+
function defaultNormalizeCredentials(identifiers) {
|
|
25
|
+
const normalized = trimIdentifiers(identifiers);
|
|
26
|
+
if (typeof normalized.email === "string") normalized.email = normalizeEmailIdentifier(normalized.email);
|
|
27
|
+
return normalized;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
//#endregion
|
|
31
|
+
export { defaultNormalizeCredentials, normalizeEmailIdentifier, trimIdentifiers };
|
|
32
|
+
//# sourceMappingURL=normalize-credentials.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalize-credentials.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/normalize-credentials.ts"],"sourcesContent":["import type { AuthCredentials } from \"../contracts/types\";\n\n/** Credentials without the password: the identity fields used to look a user up. */\nexport type AuthIdentifiers = Omit<AuthCredentials, \"password\">;\n\n/**\n * Normalize one email-like identifier: trim it and lower-case it.\n *\n * This is the single rule the login lookup and the login throttle both use,\n * so `\" Sara@x.io\"` and `\"sara@x.io\"` are the same account to both.\n */\nexport function normalizeEmailIdentifier(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/**\n * Trim every string identifier value, leaving other values untouched. This is\n * the \"as sent\" form the login lookup falls back to for legacy rows.\n */\nexport function trimIdentifiers(identifiers: AuthIdentifiers): AuthIdentifiers {\n const trimmed: AuthIdentifiers = {};\n\n for (const [key, value] of Object.entries(identifiers)) {\n trimmed[key] = typeof value === \"string\" ? value.trim() : value;\n }\n\n return trimmed;\n}\n\n/**\n * Default credential normalization: trim string values and lower-case the\n * `email` field.\n */\nexport function defaultNormalizeCredentials(identifiers: AuthIdentifiers): AuthIdentifiers {\n const normalized = trimIdentifiers(identifiers);\n\n if (typeof normalized.email === \"string\") {\n normalized.email = normalizeEmailIdentifier(normalized.email);\n }\n\n return normalized;\n}\n"],"mappings":";;;;;;;AAWA,SAAgB,yBAAyB,OAAuB;CAC9D,OAAO,MAAM,KAAK,CAAC,CAAC,YAAY;AAClC;;;;;AAMA,SAAgB,gBAAgB,aAA+C;CAC7E,MAAM,UAA2B,CAAC;CAElC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,WAAW,GACnD,QAAQ,OAAO,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;CAG5D,OAAO;AACT;;;;;AAMA,SAAgB,4BAA4B,aAA+C;CACzF,MAAM,aAAa,gBAAgB,WAAW;CAE9C,IAAI,OAAO,WAAW,UAAU,UAC9B,WAAW,QAAQ,yBAAyB,WAAW,KAAK;CAG9D,OAAO;AACT"}
|
package/llms-full.txt
CHANGED
|
@@ -606,6 +606,8 @@ authService.login(User, { username: "ada", password: "..." });
|
|
|
606
606
|
authService.login(User, { phone: "+1...", password: hashedOTP });
|
|
607
607
|
```
|
|
608
608
|
|
|
609
|
+
Identifiers are normalized before the lookup: string values are trimmed and `email` is lower-cased (`" Sara@x.io"` finds `sara@x.io`). If that finds no user and the normalized value differs from what was sent (trimmed), the lookup is retried once with the value as sent, so legacy rows stored with capitals still log in. The login throttle buckets by the same trimmed, lower-cased email. Configure with `auth.normalizeCredentials`: a function `(identifiers) => identifiers` (everything except `password`), or `false` for exact matching (the function type is `NormalizeCredentials`). Store new emails lower-cased.
|
|
610
|
+
|
|
609
611
|
For lower-level credential verification (just check, don't issue tokens), use `authService.attemptLogin(Model, credentials)` — returns the user or null without creating tokens.
|
|
610
612
|
|
|
611
613
|
## Device info
|
package/package.json
CHANGED
|
@@ -12,13 +12,13 @@
|
|
|
12
12
|
"ms": "^2.1.3"
|
|
13
13
|
},
|
|
14
14
|
"peerDependencies": {
|
|
15
|
-
"@warlock.js/fs": "5.
|
|
16
|
-
"@warlock.js/cache": "5.
|
|
17
|
-
"@warlock.js/cascade": "5.
|
|
18
|
-
"@warlock.js/core": "5.
|
|
19
|
-
"@warlock.js/logger": "5.
|
|
20
|
-
"@warlock.js/seal": "5.
|
|
21
|
-
"@warlock.js/notifications": "5.
|
|
15
|
+
"@warlock.js/fs": "5.52.0",
|
|
16
|
+
"@warlock.js/cache": "5.52.0",
|
|
17
|
+
"@warlock.js/cascade": "5.52.0",
|
|
18
|
+
"@warlock.js/core": "5.52.0",
|
|
19
|
+
"@warlock.js/logger": "5.52.0",
|
|
20
|
+
"@warlock.js/seal": "5.52.0",
|
|
21
|
+
"@warlock.js/notifications": "5.52.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.
|
|
51
|
+
"version": "5.52.0",
|
|
52
52
|
"type": "module",
|
|
53
53
|
"main": "./esm/index.mjs",
|
|
54
54
|
"module": "./esm/index.mjs",
|
|
@@ -81,6 +81,8 @@ authService.login(User, { username: "ada", password: "..." });
|
|
|
81
81
|
authService.login(User, { phone: "+1...", password: hashedOTP });
|
|
82
82
|
```
|
|
83
83
|
|
|
84
|
+
Identifiers are normalized before the lookup: string values are trimmed and `email` is lower-cased (`" Sara@x.io"` finds `sara@x.io`). If that finds no user and the normalized value differs from what was sent (trimmed), the lookup is retried once with the value as sent, so legacy rows stored with capitals still log in. The login throttle buckets by the same trimmed, lower-cased email. Configure with `auth.normalizeCredentials`: a function `(identifiers) => identifiers` (everything except `password`), or `false` for exact matching (the function type is `NormalizeCredentials`). Store new emails lower-cased.
|
|
85
|
+
|
|
84
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.
|
|
85
87
|
|
|
86
88
|
## Device info
|