@warlock.js/auth 5.64.0 → 5.65.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/esm/contracts/index.d.mts +2 -2
- package/esm/contracts/types.d.mts +36 -2
- 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/models/access-token/access-token.model.d.mts +2 -1
- package/esm/models/access-token/access-token.model.d.mts.map +1 -1
- package/esm/models/access-token/access-token.model.mjs +10 -3
- package/esm/models/access-token/access-token.model.mjs.map +1 -1
- package/esm/models/refresh-token/refresh-token.model.mjs +8 -2
- package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
- package/esm/otp/otp.d.mts +4 -1
- package/esm/otp/otp.d.mts.map +1 -1
- package/esm/otp/otp.mjs +7 -2
- package/esm/otp/otp.mjs.map +1 -1
- package/esm/passkeys/passkey-authentication.mjs +4 -1
- package/esm/passkeys/passkey-authentication.mjs.map +1 -1
- package/esm/providers/provider-login.mjs +4 -1
- package/esm/providers/provider-login.mjs.map +1 -1
- package/esm/services/auth-config.mjs +2 -2
- package/esm/services/auth-config.mjs.map +1 -1
- package/esm/services/auth.service.d.mts +32 -7
- package/esm/services/auth.service.d.mts.map +1 -1
- package/esm/services/auth.service.mjs +82 -27
- package/esm/services/auth.service.mjs.map +1 -1
- package/esm/services/resolve-request-user.d.mts.map +1 -1
- package/esm/services/resolve-request-user.mjs +6 -2
- package/esm/services/resolve-request-user.mjs.map +1 -1
- package/llms-full.txt +7 -3
- package/package.json +8 -8
- package/skills/customize-user-type/SKILL.md +1 -1
- package/skills/handle-login-and-logout/SKILL.md +4 -0
- package/skills/login-with-providers/SKILL.md +1 -1
- package/skills/manage-tokens/SKILL.md +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,23 @@ 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.65.0 - 2026-11-26
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `authService.verifyCredentials(Model, credentials, request?)` returns `{ type: "ok", user }`, `{ type: "invalid" }` or `{ type: "refused", user }`, so an app can reveal a suspended account only after the right password. Unknown accounts still spend the same hashing time. New exported type `CredentialsVerification`.
|
|
12
|
+
- `auth.canAuthenticate(user, context?)` now receives `{ via, request? }` (types `AuthenticationContext` and `AuthenticationMethod`); `via` is `"password"`, `"otp"`, `"passkey"`, `"oauth"`, `"token"`, `"refresh"` or `"custom"`. `login`, `attemptLogin` and `verifyOtp` take the request, `completeLogin` takes the context, and the auth middleware and automatic renewal pass theirs. One-argument policies keep working.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- Access tokens are built from the user model's `accessTokenPayload()` on login, refresh and automatic renewal, so a claim added by the override stays on the session. A payload passed at login is merged over those claims (it no longer replaces them) and is not kept for later refreshes; `id`, `userType` and `jti` are always set from the user.
|
|
17
|
+
- `deleteForUser` and `findForUser` on the access and refresh token models also match `user_type`.
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- `removeAllAccessTokens()` (and so logout without a refresh token, `revokeAllTokens` and password reset) no longer deletes the access tokens of another user type that has the same id.
|
|
22
|
+
- The documented `accessTokenPayload()` override is now used when issuing tokens.
|
|
23
|
+
|
|
7
24
|
## 5.54.0 - 2026-11-16
|
|
8
25
|
|
|
9
26
|
### Upgrading
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AppleProviderConfig, AuthProvider, DiscordProviderConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LinkedInProviderConfig, OtpConfig, OtpMessage, OtpSender, PasskeysConfig, ProviderAuthorizationState, ProviderCallbackParams, ProviderLinkExisting, 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, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, PageAuthConfig, PasswordResetConfig, PasswordSetter, RefreshTokenConfig, SetAuthCookieOptions, TokenFrom, TokenPair } from "./types.mjs";
|
|
2
|
+
import { AccessTokenConfig, AccessTokenOutput, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthRefreshCredentialDescriptor, AuthenticationContext, AuthenticationMethod, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CredentialsVerification, 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, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAuthorizationState, ProviderCallbackParams, ProviderLinkExisting, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshTokenConfig, RequestUser, SetAuthCookieOptions, TokenFrom, TokenPair, XProviderConfig };
|
|
5
|
+
export { AccessTokenConfig, AccessTokenOutput, AppleProviderConfig, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthRefreshCredentialDescriptor, Authenticable, AuthenticationContext, AuthenticationMethod, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CredentialsVerification, 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, ProviderLinkExisting, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshTokenConfig, RequestUser, SetAuthCookieOptions, TokenFrom, TokenPair, XProviderConfig };
|
|
@@ -66,8 +66,42 @@ export interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor>
|
|
|
66
66
|
returnUrlParam?: string;
|
|
67
67
|
};
|
|
68
68
|
}
|
|
69
|
-
/**
|
|
70
|
-
export type
|
|
69
|
+
/** How a user is being authenticated when `auth.canAuthenticate` runs. */
|
|
70
|
+
export type AuthenticationMethod = "password" | "otp" | "passkey" | "oauth" |
|
|
71
|
+
/** A bearer/cookie access token on a request, or tokens issued for a user directly. */
|
|
72
|
+
"token" |
|
|
73
|
+
/** A refresh token exchanged for a new pair, or automatic session renewal. */
|
|
74
|
+
"refresh" |
|
|
75
|
+
/** An app calling `completeLogin()` after its own verification. */
|
|
76
|
+
"custom";
|
|
77
|
+
/** What `auth.canAuthenticate` receives next to the user. */
|
|
78
|
+
export type AuthenticationContext = {
|
|
79
|
+
/** The request being served; absent where the call site has none (for example a refresh by token string). */
|
|
80
|
+
request?: Request;
|
|
81
|
+
/** The method that is authenticating the user. */
|
|
82
|
+
via: AuthenticationMethod;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Application policy that decides whether a resolved user may authenticate.
|
|
86
|
+
* The optional second argument says how and, where one exists, on which request.
|
|
87
|
+
*/
|
|
88
|
+
export type CanAuthenticate = (user: Auth, context?: AuthenticationContext) => boolean | Promise<boolean>;
|
|
89
|
+
/** Result of `authService.verifyCredentials()`. */
|
|
90
|
+
export type CredentialsVerification<UserType extends Auth = Auth> =
|
|
91
|
+
/** Account found, password right and allowed to authenticate. */
|
|
92
|
+
{
|
|
93
|
+
type: "ok";
|
|
94
|
+
user: UserType;
|
|
95
|
+
} |
|
|
96
|
+
/** Unknown account or wrong password. */
|
|
97
|
+
{
|
|
98
|
+
type: "invalid";
|
|
99
|
+
} |
|
|
100
|
+
/** Password right, but `auth.canAuthenticate` refuses the account. */
|
|
101
|
+
{
|
|
102
|
+
type: "refused";
|
|
103
|
+
user: UserType;
|
|
104
|
+
};
|
|
71
105
|
/** Password credentials plus the application-defined identity fields. */
|
|
72
106
|
export type AuthCredentials = Record<string, unknown> & {
|
|
73
107
|
password: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;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;;EAEA,eAAe;;EAEf,MAAM;;;;;YAMI;;;;;EAKV;;;;;EAKA;;EAEA,eAAe;;EAEf,MAAM;;;;;;;EAON,cAAc;;;;;;;;;EASd;;;;;YAMU;;EAEV,eAAe;;YAGL;;;;;EAKV;KACG,mBAAmB,WAAW;;;EAGjC;;;;;EAKA,kBAAkB;;;;;;;;;;;;;EAalB,+BAA+B;;;;;;;;;;;;;EAa/B;;;;;;;;;EASA;;;;EAIA,cAAc;;;;EAId,eAAe;;;;;;EAMf,WAAW;;;;;;EAMX,SAAS;;;;EAIT,OAAO;;;;EAIP,eAAe;;;;EAIf,gBAAgB;;;;EAIhB,eAAe;;;;EAIf,YAAY;;;;EAIZ,WAAW;;;;EAIX,MAAM;;;;EAIN,MAAM;;YAGI;;;;EAIV;;;;EAIA;;;;;YAMU;;;;EAIV,aAAa;;;;EAIb,eAAe;;;;;YAML;;;;EAIV;;;;EAIA;;;;EAIA;;;;;EAKA;;;;EAIA,UAAU;;YAGA,YAAY,iBAAiB;EACvC,MAAM;EACN,QAAQ;;;YAIE,wBAAwB,SAAS;;;;;;;;;YAUjC;;;;;;EAMV;;;;;EAKA;;;;;EAKA;;EAEA,eAAe;;;;;;;;;;;;EAYf;;;;;;YAOU;;;;;;EAMV;;;;;;;;YASU;;EAEV;;EAEA;;EAEA;;;;;;;EAOA;;;YAIU;;EAEV;;EAEA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"sourcesContent":["import { type ChildModel } from \"@warlock.js/cascade\";\nimport type { Request } from \"@warlock.js/core\";\nimport { type Algorithm } from \"fast-jwt\";\nimport type { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport type { OneTimeToken } from \"../models/one-time-token\";\nimport type { OtpConfig, PasskeysConfig, ProvidersConfig } from \"./providers\";\nimport type { RefreshToken } from \"../models/refresh-token\";\n\n/**\n * Symbol to indicate no expiration for tokens\n * Use this when you explicitly want tokens to never expire\n *\n * @example\n * ```typescript\n * // src/config/auth.ts\n * import { NO_EXPIRATION, type AuthConfigurations } from \"@warlock.js/auth\";\n *\n * const authConfigurations: AuthConfigurations = {\n * accessToken: {\n * secret: env(\"JWT_SECRET\"),\n * expiresIn: NO_EXPIRATION, // Token expires within 100 years\n * },\n * };\n *\n * export default authConfigurations;\n * ```\n */\nexport const NO_EXPIRATION = \"100y\";\n\n/**\n * Behavior when logout is called without a refresh token\n * - \"revoke-all\": Revoke all refresh tokens for the user (secure default)\n * - \"error\": Return an error requiring the refresh token\n */\nexport type LogoutWithoutTokenBehavior = \"revoke-all\" | \"error\";\n\n/** The single request credential source an auth middleware instance accepts. */\nexport type TokenFrom = \"header\" | `cookie:${string}`;\n\n/** One explicitly named credential location accepted by auth middleware. */\nexport interface AuthCredentialDescriptor {\n source: \"header\" | \"cookie\";\n key?: string;\n}\n\n/** Cookie credential and bounded duplicate window for automatic renewal. */\nexport interface AuthRefreshCredentialDescriptor extends AuthCredentialDescriptor {\n /** Milliseconds; the service clamps this to the 0–10 second range (default 5 seconds). */\n overlapMs?: number;\n}\n\n/** Per-route authentication behavior for the object middleware overload. */\nexport interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor> {\n optional?: boolean;\n /**\n * Accept both a header and a cookie credential (at most one of each).\n * Precedence is fixed and independent of array order: a present\n * `Authorization` header wins, an invalid header rejects and never falls back\n * to the cookie, and renewal plus the CSRF Origin check apply only when the\n * cookie is the credential actually used. Cannot be combined with `source`.\n */\n sources?: AuthCredentialDescriptor[];\n /** Opt-in automatic renewal credential. Cookie sources only. */\n refresh?: AuthRefreshCredentialDescriptor;\n redirect?: { to: string; returnUrlParam?: string };\n}\n\n/** Application policy that decides whether a resolved user may authenticate. */\nexport type CanAuthenticate = (user: Auth) => boolean | Promise<boolean>;\n\n/** Password credentials plus the application-defined identity fields. */\nexport type AuthCredentials = Record<string, unknown> & {\n password: string;\n};\n\n/**\n * Rewrites the identity fields of a login (everything except `password`)\n * before the user lookup.\n */\nexport type NormalizeCredentials = (\n identifiers: Omit<AuthCredentials, \"password\">,\n) => Omit<AuthCredentials, \"password\">;\n\n/**\n * Access-token configuration.\n *\n * `secret` may also be supplied via the deprecated `jwt.secret` (resolved by a\n * backward-compatible shim); one of the two is required at runtime.\n */\nexport type AccessTokenConfig = {\n /**\n * Override the persisted access-token model — extend {@link AccessToken} to\n * add columns (e.g. a tenant key) or rename them, then register the subclass\n * here. Defaults to the package's `AccessToken`.\n */\n model?: typeof AccessToken;\n /**\n * Secret used to sign access tokens.\n */\n secret?: string;\n /**\n * Retired access-token secrets, newest first. Tokens signed with one of them\n * still verify; new tokens are always signed with `secret`. Remove an entry\n * once every token signed with it has expired.\n */\n previousSecrets?: string[];\n /**\n * JWT algorithm.\n * @default \"HS256\"\n */\n algorithm?: Algorithm;\n /**\n * Access-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\n * first token issue: each of them would otherwise sign a token with no `exp`\n * claim at all.\n * @example \"1h\" or NO_EXPIRATION\n * @default \"1h\"\n */\n expiresIn?: string;\n /**\n * Issuer (`iss` claim) stamped on every access and refresh token this app\n * signs, and required on every token it accepts. Set it when several apps\n * or services share a signing secret, so a token minted by one is refused\n * by the others. Unset (the default) ⇒ no `iss` is stamped or checked.\n *\n * Tokens signed before it was set carry no `iss` and are refused once it is\n * set, so every signed-in user signs in again once.\n * @example \"https://api.example.com\"\n */\n issuer?: string;\n /**\n * Audience (`aud` claim) stamped on every token this app signs, and\n * required on every token it accepts (a token matches when its `aud`\n * includes one of the values). Unset (the default) ⇒ no `aud` is stamped or\n * checked. Like `issuer`, setting it signs everyone out once.\n * @example \"web-app\"\n */\n audience?: string | string[];\n};\n\n/**\n * Refresh-token configuration.\n */\nexport type RefreshTokenConfig = {\n /**\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\n * Defaults to the package's `RefreshToken`.\n */\n model?: typeof RefreshToken;\n /**\n * Enable refresh tokens.\n * @default true\n */\n enabled?: boolean;\n /**\n * Separate secret for refresh tokens (recommended for security). Falls back\n * to the access-token secret when omitted.\n */\n secret?: string;\n /**\n * Retired refresh-token secrets. Tokens signed with one of them still\n * verify; new tokens are always signed with `secret`. When no refresh\n * `secret` is set, the retired access-token secrets apply to refresh tokens\n * too.\n */\n previousSecrets?: string[];\n /**\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds; an unusable value throws naming this key on issue\n * (see {@link AccessTokenConfig.expiresIn}).\n * @example \"7d\" or \"1w\"\n * @default \"7d\"\n */\n expiresIn?: string;\n /**\n * Rotate the refresh token on each use (old token revoked, replay detected).\n * @default true\n */\n rotation?: boolean;\n /**\n * Maximum active refresh tokens per user; the oldest are revoked past it.\n * @default 5\n */\n maxPerUser?: number;\n /**\n * Behavior when logout is called without a refresh token.\n * @default \"revoke-all\"\n */\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n};\n\n/**\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\n * deprecation warning.\n *\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\n */\nexport type LegacyJwtConfig = {\n secret?: string;\n algorithm?: Algorithm;\n expiresIn?: string;\n refresh?: {\n secret?: string;\n enabled?: boolean;\n expiresIn?: string;\n rotation?: boolean;\n maxPerUser?: number;\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n };\n};\n\n/**\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\n * to a login page instead of returning the API-style JSON 401.\n *\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\n * always keep the JSON 401 contract regardless of this setting.\n */\nexport type PageAuthConfig = {\n /**\n * Login path a guarded page route redirects a logged-out browser to (e.g.\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\n * behavior is opt-in and backward-compatible.\n */\n loginPath?: string;\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed.\n * @default \"returnUrl\"\n */\n returnUrlParam?: string;\n};\n\n/**\n * Data every email-verification / password-reset notification receives.\n */\nexport type OneTimeTokenNotificationData = {\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\n token: string;\n /** When the token stops working. */\n expiresAt: Date;\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\n url?: string;\n};\n\n/**\n * Anything auth can deliver a token through — a `defineNotification(...)`\n * result satisfies it, as does any object with a compatible `send`.\n */\nexport type AuthNotification = {\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\n};\n\n/** Builds the link a token notification points at. */\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\n\n/** Persists a new plaintext password for a user during a password reset. */\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\n\n/**\n * Email-verification configuration (`auth.verification`).\n */\nexport type EmailVerificationConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"24h\"\n */\n expiresIn?: string;\n /**\n * User attribute stamped with the verification `Date`. Declare it in the\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\n * @default \"emailVerifiedAt\"\n */\n field?: string;\n /** Replace the default verification email. */\n notification?: AuthNotification;\n /** Build the verification link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n};\n\n/**\n * Password-reset configuration (`auth.passwordReset`).\n */\nexport type PasswordResetConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"60m\"\n */\n expiresIn?: string;\n /**\n * User attribute `requestPasswordReset` looks the account up by.\n * @default \"email\"\n */\n identifierField?: string;\n /** Replace the default reset email. */\n notification?: AuthNotification;\n /** Build the reset link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n /**\n * Persist the new password yourself. By default auth saves a hash made by\n * the same `hashPassword` login verifies against, and falls back to the\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\n * the stored value with `verifyPassword` either way.\n */\n setPassword?: PasswordSetter;\n /**\n * Wait for the reset notification before `requestPasswordReset` resolves,\n * so a delivery error reaches the caller. Off by default: the notification\n * is sent in the background, so the response time does not reveal whether\n * the account exists. A background failure is logged and emitted as\n * `password.resetDeliveryFailed`.\n * @default false\n */\n awaitDelivery?: boolean;\n};\n\n/**\n * One-time token storage configuration (`auth.oneTimeToken`).\n */\nexport type OneTimeTokenConfig = {\n /** Override the persisted model — extend {@link OneTimeToken}. */\n model?: typeof OneTimeToken;\n};\n\nexport type AuthConfigurations = {\n /**\n * Define all user types — maps a user-type slug to its `Auth` model class so\n * tokens and the middleware can resolve the right model.\n */\n userType: {\n [userType: string]: ChildModel<Auth>;\n };\n /** Default user type used by `authMiddleware()` and options-only overloads. */\n defaultUserType?: string;\n /**\n * Decide whether a resolved user may authenticate or receive new tokens.\n * @default () => true\n */\n canAuthenticate?: CanAuthenticate;\n /**\n * How login identifiers are normalized before the user lookup. Default:\n * string values are trimmed and the `email` field is lower-cased, so\n * `\" Sara@x.io\"` finds the account stored as `sara@x.io`. If that finds no\n * user and the normalized value differs from what was sent (trimmed), the\n * lookup is retried once with the value as sent, so rows stored with capitals\n * keep working. Pass a function to normalize your own way (the retry still\n * applies), or `false` for exact matching.\n *\n * The login throttle buckets `email` by trimmed, lower-cased value either way.\n * @default trim string values, lower-case `email`\n */\n normalizeCredentials?: false | NormalizeCredentials;\n /**\n * Store only a SHA-256 digest of each access and refresh token in the\n * database, never the token itself, so a copy of the token tables (a\n * backup, a replica, a read-only injection) cannot be replayed as a login.\n *\n * No migration is needed: the digest goes in the existing `token` column,\n * and lookups accept both forms, so rows issued before the switch keep\n * working until they expire, and turning it off again signs no one out.\n * A row loaded from storage no longer carries its raw token; a freshly\n * issued one exposes it as `row.plainToken`.\n * @default false\n */\n hashTokensAtRest?: boolean;\n /**\n * After a successful password login, replace a stored hash made with another\n * algorithm or cost than `encryption.password` now asks for (a raised bcrypt\n * `salt`, or a switch to the `\"scrypt\"` driver) with a fresh one. A failure\n * to save is logged and never fails the login. Set `false` to keep hashes as\n * they are.\n * @default true\n */\n rehashPasswords?: boolean;\n /**\n * Access-token configuration (secret, expiry, algorithm, model override).\n */\n accessToken?: AccessTokenConfig;\n /**\n * Refresh-token configuration (rotation, lifetime, cap, model override).\n */\n refreshToken?: RefreshTokenConfig;\n /**\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\n */\n pageAuth?: PageAuthConfig;\n /**\n * Cookie auth session config — read by `authService.setAuthCookie` /\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\n */\n cookie?: CookieAuthConfig;\n /**\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\n */\n csrf?: CsrfConfig;\n /**\n * Email verification — token lifetime, verified field, notification override.\n */\n verification?: EmailVerificationConfig;\n /**\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\n */\n passwordReset?: PasswordResetConfig;\n /**\n * One-time token (verification / reset) storage — model override.\n */\n oneTimeToken?: OneTimeTokenConfig;\n /**\n * Redirect login providers (`google`, `custom`) and account-linking policy.\n */\n providers?: ProvidersConfig;\n /**\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\n */\n passkeys?: PasskeysConfig;\n /**\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\n */\n otp?: OtpConfig;\n /**\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\n */\n jwt?: LegacyJwtConfig;\n};\n\nexport type AccessTokenOutput = {\n /**\n * JWT Token\n */\n token: string;\n /**\n * Exprie time in ISO format UTC time\n */\n expiresAt: string;\n};\n\n/**\n * Token pair returned after login or token refresh\n */\nexport type TokenPair = {\n /**\n * JWT access token (short-lived)\n */\n accessToken: AccessTokenOutput;\n /**\n * JWT refresh token (long-lived)\n */\n refreshToken?: AccessTokenOutput;\n};\n\n/**\n * Device information for session tracking\n */\nexport type DeviceInfo = {\n /**\n * User agent string from request\n */\n userAgent?: string;\n /**\n * Client IP address\n */\n ip?: string;\n /**\n * Optional device identifier\n */\n deviceId?: string;\n /**\n * Token family ID (for rotation tracking)\n * @internal\n */\n familyId?: string;\n /**\n * Access token payload\n */\n payload?: Record<string, unknown>;\n};\n\nexport type LoginResult<UserType extends Auth> = {\n user: UserType;\n tokens: TokenPair;\n};\n\n/** Selects a cookie Domain for one request; return `undefined` for a host-only cookie. */\nexport type CookieDomainResolver = (request: Request) => string | undefined;\n\n/**\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\n * configurable here — they come from core's `secureCookieDefaults()`, the\n * same floor every `response.cookie()` call gets, so a cookie auth session can\n * never be weakened to a laxer policy than the framework default.\n */\nexport type CookieAuthConfig = {\n /**\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\n * `cookie:<name>` token source must match to read it back.\n * @default \"access_token\"\n */\n name?: string;\n /**\n * Cookie name the session helpers write and clear for the refresh token.\n * @default \"refresh_token\"\n */\n refreshName?: string;\n /**\n * Cookie `Path` attribute.\n * @default \"/\"\n */\n path?: string;\n /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */\n cookieDomain?: CookieDomainResolver;\n /**\n * Write the auth cookies under a `__Host-` name prefix (`__Host-access_token`,\n * `__Host-refresh_token`). Browsers accept such a cookie only when it is\n * Secure, has `Path=/` and no `Domain`, so a subdomain or a plain-HTTP page\n * cannot plant or overwrite the session cookie. Requires `path: \"/\"` and no\n * `cookieDomain`; a write that breaks either rule throws naming the setting.\n *\n * While switching, the unprefixed cookie is still read (so signed-in users\n * stay signed in) and both names are cleared on logout.\n * @default false\n */\n hostPrefix?: boolean;\n};\n\n/**\n * CSRF Origin-check configuration. Read via\n * `authConfig.csrf.allowedOrigins()`.\n */\nexport type CsrfConfig = {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * in addition to the request's own origin.\n * @default []\n */\n allowedOrigins?: string[];\n};\n\n/**\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\n * falls back to `auth.cookie.*` config, then the package default. Cookie\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\n * see {@link CookieAuthConfig}.\n */\nexport type SetAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\n path?: string;\n /** Cookie `Domain` attribute. Omit for a host-only cookie. */\n domain?: string;\n /**\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\n * bare token string with no `maxAge` produces a session cookie (cleared\n * when the browser closes).\n */\n maxAge?: number;\n};\n\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\nexport type ClearAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\n path?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
|
|
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/** How a user is being authenticated when `auth.canAuthenticate` runs. */\nexport type AuthenticationMethod =\n | \"password\"\n | \"otp\"\n | \"passkey\"\n | \"oauth\"\n /** A bearer/cookie access token on a request, or tokens issued for a user directly. */\n | \"token\"\n /** A refresh token exchanged for a new pair, or automatic session renewal. */\n | \"refresh\"\n /** An app calling `completeLogin()` after its own verification. */\n | \"custom\";\n\n/** What `auth.canAuthenticate` receives next to the user. */\nexport type AuthenticationContext = {\n /** The request being served; absent where the call site has none (for example a refresh by token string). */\n request?: Request;\n /** The method that is authenticating the user. */\n via: AuthenticationMethod;\n};\n\n/**\n * Application policy that decides whether a resolved user may authenticate.\n * The optional second argument says how and, where one exists, on which request.\n */\nexport type CanAuthenticate = (\n user: Auth,\n context?: AuthenticationContext,\n) => boolean | Promise<boolean>;\n\n/** Result of `authService.verifyCredentials()`. */\nexport type CredentialsVerification<UserType extends Auth = Auth> =\n /** Account found, password right and allowed to authenticate. */\n | { type: \"ok\"; user: UserType }\n /** Unknown account or wrong password. */\n | { type: \"invalid\" }\n /** Password right, but `auth.canAuthenticate` refuses the account. */\n | { type: \"refused\"; user: UserType };\n\n/** Password credentials plus the application-defined identity fields. */\nexport type AuthCredentials = Record<string, unknown> & {\n password: string;\n};\n\n/**\n * Rewrites the identity fields of a login (everything except `password`)\n * before the user lookup.\n */\nexport type NormalizeCredentials = (\n identifiers: Omit<AuthCredentials, \"password\">,\n) => Omit<AuthCredentials, \"password\">;\n\n/**\n * Access-token configuration.\n *\n * `secret` may also be supplied via the deprecated `jwt.secret` (resolved by a\n * backward-compatible shim); one of the two is required at runtime.\n */\nexport type AccessTokenConfig = {\n /**\n * Override the persisted access-token model — extend {@link AccessToken} to\n * add columns (e.g. a tenant key) or rename them, then register the subclass\n * here. Defaults to the package's `AccessToken`.\n */\n model?: typeof AccessToken;\n /**\n * Secret used to sign access tokens.\n */\n secret?: string;\n /**\n * Retired access-token secrets, newest first. Tokens signed with one of them\n * still verify; new tokens are always signed with `secret`. Remove an entry\n * once every token signed with it has expired.\n */\n previousSecrets?: string[];\n /**\n * JWT algorithm.\n * @default \"HS256\"\n */\n algorithm?: Algorithm;\n /**\n * Access-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\n * first token issue: each of them would otherwise sign a token with no `exp`\n * claim at all.\n * @example \"1h\" or NO_EXPIRATION\n * @default \"1h\"\n */\n expiresIn?: string;\n /**\n * Issuer (`iss` claim) stamped on every access and refresh token this app\n * signs, and required on every token it accepts. Set it when several apps\n * or services share a signing secret, so a token minted by one is refused\n * by the others. Unset (the default) ⇒ no `iss` is stamped or checked.\n *\n * Tokens signed before it was set carry no `iss` and are refused once it is\n * set, so every signed-in user signs in again once.\n * @example \"https://api.example.com\"\n */\n issuer?: string;\n /**\n * Audience (`aud` claim) stamped on every token this app signs, and\n * required on every token it accepts (a token matches when its `aud`\n * includes one of the values). Unset (the default) ⇒ no `aud` is stamped or\n * checked. Like `issuer`, setting it signs everyone out once.\n * @example \"web-app\"\n */\n audience?: string | string[];\n};\n\n/**\n * Refresh-token configuration.\n */\nexport type RefreshTokenConfig = {\n /**\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\n * Defaults to the package's `RefreshToken`.\n */\n model?: typeof RefreshToken;\n /**\n * Enable refresh tokens.\n * @default true\n */\n enabled?: boolean;\n /**\n * Separate secret for refresh tokens (recommended for security). Falls back\n * to the access-token secret when omitted.\n */\n secret?: string;\n /**\n * Retired refresh-token secrets. Tokens signed with one of them still\n * verify; new tokens are always signed with `secret`. When no refresh\n * `secret` is set, the retired access-token secrets apply to refresh tokens\n * too.\n */\n previousSecrets?: string[];\n /**\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds; an unusable value throws naming this key on issue\n * (see {@link AccessTokenConfig.expiresIn}).\n * @example \"7d\" or \"1w\"\n * @default \"7d\"\n */\n expiresIn?: string;\n /**\n * Rotate the refresh token on each use (old token revoked, replay detected).\n * @default true\n */\n rotation?: boolean;\n /**\n * Maximum active refresh tokens per user; the oldest are revoked past it.\n * @default 5\n */\n maxPerUser?: number;\n /**\n * Behavior when logout is called without a refresh token.\n * @default \"revoke-all\"\n */\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n};\n\n/**\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\n * deprecation warning.\n *\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\n */\nexport type LegacyJwtConfig = {\n secret?: string;\n algorithm?: Algorithm;\n expiresIn?: string;\n refresh?: {\n secret?: string;\n enabled?: boolean;\n expiresIn?: string;\n rotation?: boolean;\n maxPerUser?: number;\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n };\n};\n\n/**\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\n * to a login page instead of returning the API-style JSON 401.\n *\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\n * always keep the JSON 401 contract regardless of this setting.\n */\nexport type PageAuthConfig = {\n /**\n * Login path a guarded page route redirects a logged-out browser to (e.g.\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\n * behavior is opt-in and backward-compatible.\n */\n loginPath?: string;\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed.\n * @default \"returnUrl\"\n */\n returnUrlParam?: string;\n};\n\n/**\n * Data every email-verification / password-reset notification receives.\n */\nexport type OneTimeTokenNotificationData = {\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\n token: string;\n /** When the token stops working. */\n expiresAt: Date;\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\n url?: string;\n};\n\n/**\n * Anything auth can deliver a token through — a `defineNotification(...)`\n * result satisfies it, as does any object with a compatible `send`.\n */\nexport type AuthNotification = {\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\n};\n\n/** Builds the link a token notification points at. */\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\n\n/** Persists a new plaintext password for a user during a password reset. */\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\n\n/**\n * Email-verification configuration (`auth.verification`).\n */\nexport type EmailVerificationConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"24h\"\n */\n expiresIn?: string;\n /**\n * User attribute stamped with the verification `Date`. Declare it in the\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\n * @default \"emailVerifiedAt\"\n */\n field?: string;\n /** Replace the default verification email. */\n notification?: AuthNotification;\n /** Build the verification link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n};\n\n/**\n * Password-reset configuration (`auth.passwordReset`).\n */\nexport type PasswordResetConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"60m\"\n */\n expiresIn?: string;\n /**\n * User attribute `requestPasswordReset` looks the account up by.\n * @default \"email\"\n */\n identifierField?: string;\n /** Replace the default reset email. */\n notification?: AuthNotification;\n /** Build the reset link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n /**\n * Persist the new password yourself. By default auth saves a hash made by\n * the same `hashPassword` login verifies against, and falls back to the\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\n * the stored value with `verifyPassword` either way.\n */\n setPassword?: PasswordSetter;\n /**\n * Wait for the reset notification before `requestPasswordReset` resolves,\n * so a delivery error reaches the caller. Off by default: the notification\n * is sent in the background, so the response time does not reveal whether\n * the account exists. A background failure is logged and emitted as\n * `password.resetDeliveryFailed`.\n * @default false\n */\n awaitDelivery?: boolean;\n};\n\n/**\n * One-time token storage configuration (`auth.oneTimeToken`).\n */\nexport type OneTimeTokenConfig = {\n /** Override the persisted model — extend {@link OneTimeToken}. */\n model?: typeof OneTimeToken;\n};\n\nexport type AuthConfigurations = {\n /**\n * Define all user types — maps a user-type slug to its `Auth` model class so\n * tokens and the middleware can resolve the right model.\n */\n userType: {\n [userType: string]: ChildModel<Auth>;\n };\n /** Default user type used by `authMiddleware()` and options-only overloads. */\n defaultUserType?: string;\n /**\n * Decide whether a resolved user may authenticate or receive new tokens.\n * @default () => true\n */\n canAuthenticate?: CanAuthenticate;\n /**\n * How login identifiers are normalized before the user lookup. Default:\n * string values are trimmed and the `email` field is lower-cased, so\n * `\" Sara@x.io\"` finds the account stored as `sara@x.io`. If that finds no\n * user and the normalized value differs from what was sent (trimmed), the\n * lookup is retried once with the value as sent, so rows stored with capitals\n * keep working. Pass a function to normalize your own way (the retry still\n * applies), or `false` for exact matching.\n *\n * The login throttle buckets `email` by trimmed, lower-cased value either way.\n * @default trim string values, lower-case `email`\n */\n normalizeCredentials?: false | NormalizeCredentials;\n /**\n * Store only a SHA-256 digest of each access and refresh token in the\n * database, never the token itself, so a copy of the token tables (a\n * backup, a replica, a read-only injection) cannot be replayed as a login.\n *\n * No migration is needed: the digest goes in the existing `token` column,\n * and lookups accept both forms, so rows issued before the switch keep\n * working until they expire, and turning it off again signs no one out.\n * A row loaded from storage no longer carries its raw token; a freshly\n * issued one exposes it as `row.plainToken`.\n * @default false\n */\n hashTokensAtRest?: boolean;\n /**\n * After a successful password login, replace a stored hash made with another\n * algorithm or cost than `encryption.password` now asks for (a raised bcrypt\n * `salt`, or a switch to the `\"scrypt\"` driver) with a fresh one. A failure\n * to save is logged and never fails the login. Set `false` to keep hashes as\n * they are.\n * @default true\n */\n rehashPasswords?: boolean;\n /**\n * Access-token configuration (secret, expiry, algorithm, model override).\n */\n accessToken?: AccessTokenConfig;\n /**\n * Refresh-token configuration (rotation, lifetime, cap, model override).\n */\n refreshToken?: RefreshTokenConfig;\n /**\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\n */\n pageAuth?: PageAuthConfig;\n /**\n * Cookie auth session config — read by `authService.setAuthCookie` /\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\n */\n cookie?: CookieAuthConfig;\n /**\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\n */\n csrf?: CsrfConfig;\n /**\n * Email verification — token lifetime, verified field, notification override.\n */\n verification?: EmailVerificationConfig;\n /**\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\n */\n passwordReset?: PasswordResetConfig;\n /**\n * One-time token (verification / reset) storage — model override.\n */\n oneTimeToken?: OneTimeTokenConfig;\n /**\n * Redirect login providers (`google`, `custom`) and account-linking policy.\n */\n providers?: ProvidersConfig;\n /**\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\n */\n passkeys?: PasskeysConfig;\n /**\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\n */\n otp?: OtpConfig;\n /**\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\n */\n jwt?: LegacyJwtConfig;\n};\n\nexport type AccessTokenOutput = {\n /**\n * JWT Token\n */\n token: string;\n /**\n * Exprie time in ISO format UTC time\n */\n expiresAt: string;\n};\n\n/**\n * Token pair returned after login or token refresh\n */\nexport type TokenPair = {\n /**\n * JWT access token (short-lived)\n */\n accessToken: AccessTokenOutput;\n /**\n * JWT refresh token (long-lived)\n */\n refreshToken?: AccessTokenOutput;\n};\n\n/**\n * Device information for session tracking\n */\nexport type DeviceInfo = {\n /**\n * User agent string from request\n */\n userAgent?: string;\n /**\n * Client IP address\n */\n ip?: string;\n /**\n * Optional device identifier\n */\n deviceId?: string;\n /**\n * Token family ID (for rotation tracking)\n * @internal\n */\n familyId?: string;\n /**\n * Access token payload\n */\n payload?: Record<string, unknown>;\n};\n\nexport type LoginResult<UserType extends Auth> = {\n user: UserType;\n tokens: TokenPair;\n};\n\n/** Selects a cookie Domain for one request; return `undefined` for a host-only cookie. */\nexport type CookieDomainResolver = (request: Request) => string | undefined;\n\n/**\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\n * configurable here — they come from core's `secureCookieDefaults()`, the\n * same floor every `response.cookie()` call gets, so a cookie auth session can\n * never be weakened to a laxer policy than the framework default.\n */\nexport type CookieAuthConfig = {\n /**\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\n * `cookie:<name>` token source must match to read it back.\n * @default \"access_token\"\n */\n name?: string;\n /**\n * Cookie name the session helpers write and clear for the refresh token.\n * @default \"refresh_token\"\n */\n refreshName?: string;\n /**\n * Cookie `Path` attribute.\n * @default \"/\"\n */\n path?: string;\n /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */\n cookieDomain?: CookieDomainResolver;\n /**\n * Write the auth cookies under a `__Host-` name prefix (`__Host-access_token`,\n * `__Host-refresh_token`). Browsers accept such a cookie only when it is\n * Secure, has `Path=/` and no `Domain`, so a subdomain or a plain-HTTP page\n * cannot plant or overwrite the session cookie. Requires `path: \"/\"` and no\n * `cookieDomain`; a write that breaks either rule throws naming the setting.\n *\n * While switching, the unprefixed cookie is still read (so signed-in users\n * stay signed in) and both names are cleared on logout.\n * @default false\n */\n hostPrefix?: boolean;\n};\n\n/**\n * CSRF Origin-check configuration. Read via\n * `authConfig.csrf.allowedOrigins()`.\n */\nexport type CsrfConfig = {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * in addition to the request's own origin.\n * @default []\n */\n allowedOrigins?: string[];\n};\n\n/**\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\n * falls back to `auth.cookie.*` config, then the package default. Cookie\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\n * see {@link CookieAuthConfig}.\n */\nexport type SetAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\n path?: string;\n /** Cookie `Domain` attribute. Omit for a host-only cookie. */\n domain?: string;\n /**\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\n * bare token string with no `maxAge` produces a session cookie (cleared\n * when the browser closes).\n */\n maxAge?: number;\n};\n\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\nexport type ClearAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\n path?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
|
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, ProviderLinkExisting, 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, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, PageAuthConfig, PasswordResetConfig, PasswordSetter, RefreshTokenConfig, SetAuthCookieOptions, TokenFrom, TokenPair } from "./contracts/types.mjs";
|
|
8
|
+
import { AccessTokenConfig, AccessTokenOutput, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthRefreshCredentialDescriptor, AuthenticationContext, AuthenticationMethod, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CredentialsVerification, 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";
|
|
@@ -63,5 +63,5 @@ import { PageSessionOptions, PageSessionResolver, SessionMiddlewareOptions, Sess
|
|
|
63
63
|
import "./session/index.mjs";
|
|
64
64
|
import { safeEqual } from "./utils/safe-equal.mjs";
|
|
65
65
|
import { isNeverExpiring, isUsableExpiry, tokenHasExpClaim } from "./utils/token-expiry.mjs";
|
|
66
|
-
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, ProviderAccountLinkBlockedError, ProviderAuthorizationState, ProviderCallbackParams, ProviderEmailNotVerifiedError, ProviderLinkExisting, 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
|
+
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, AuthenticationContext, AuthenticationMethod, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainRequestRequiredError, CookieDomainResolver, CredentialsVerification, 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, ProviderAccountLinkBlockedError, ProviderAuthorizationState, ProviderCallbackParams, ProviderEmailNotVerifiedError, ProviderLinkExisting, 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 };
|
|
67
67
|
import "./contracts/request-locals.mjs";
|
|
@@ -107,7 +107,8 @@ export declare class AccessToken extends Model {
|
|
|
107
107
|
*/
|
|
108
108
|
static deleteForUser(user: Auth, token: string): Promise<number>;
|
|
109
109
|
/**
|
|
110
|
-
* Delete every access token belonging to the user.
|
|
110
|
+
* Delete every access token belonging to the user. Matches the user type as
|
|
111
|
+
* well as the id, so another identity with the same id keeps its tokens.
|
|
111
112
|
*/
|
|
112
113
|
static deleteAllForUser(user: Auth): Promise<number>;
|
|
113
114
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"access-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"mappings":";;;;;;;;;;;qBAca,8CAAiB;;;;;;;;;;;;;;;;;;;;qBAmBjB,oBAAoB;SACjB;SAEA,mCAAM;;;;;;;;;;;;;;;;;;;;SAYN;;;;;;;;SASA;;MAGH;;MAKA;;;;;MAQA;;;;;;;;;;;;;;;;MAmBA;;;;;;;MAcA;;;;;SAQG,MAAM,MAAM,MAAM,eAAe,WAAW,MAAM,oBAAiB,QAAA;;;;;SAcnE,YAAY,gBAAgB,QAAQ;;;;SAOpC,cAAc,MAAM,MAAM,gBAAa
|
|
1
|
+
{"version":3,"file":"access-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"mappings":";;;;;;;;;;;qBAca,8CAAiB;;;;;;;;;;;;;;;;;;;;qBAmBjB,oBAAoB;SACjB;SAEA,mCAAM;;;;;;;;;;;;;;;;;;;;SAYN;;;;;;;;SASA;;MAGH;;MAKA;;;;;MAQA;;;;;;;;;;;;;;;;MAmBA;;;;;;;MAcA;;;;;SAQG,MAAM,MAAM,MAAM,eAAe,WAAW,MAAM,oBAAiB,QAAA;;;;;SAcnE,YAAY,gBAAgB,QAAQ;;;;SAOpC,cAAc,MAAM,MAAM,gBAAa;;;;;SAWvC,iBAAiB,MAAM,OAAI;;;;;;SASrB,6BAA6B,MAAM,MAAM,mBAAmB;;;;;SAS5D,gBAAgB;;;;;;;;;;;;SAqBhB,qBAAqB,QAAQ;;;;;;SAW7B,sBAAsB,QAAQ"}
|
|
@@ -111,13 +111,20 @@ var AccessToken = class extends Model {
|
|
|
111
111
|
* Delete a specific token that belongs to the given user, stored hashed or raw.
|
|
112
112
|
*/
|
|
113
113
|
static deleteForUser(user, token) {
|
|
114
|
-
return this.query().where({
|
|
114
|
+
return this.query().where({
|
|
115
|
+
user_id: user.id,
|
|
116
|
+
user_type: user.userType
|
|
117
|
+
}).whereIn("token", storedTokenForms(token)).delete();
|
|
115
118
|
}
|
|
116
119
|
/**
|
|
117
|
-
* Delete every access token belonging to the user.
|
|
120
|
+
* Delete every access token belonging to the user. Matches the user type as
|
|
121
|
+
* well as the id, so another identity with the same id keeps its tokens.
|
|
118
122
|
*/
|
|
119
123
|
static deleteAllForUser(user) {
|
|
120
|
-
return this.delete({
|
|
124
|
+
return this.delete({
|
|
125
|
+
user_id: user.id,
|
|
126
|
+
user_type: user.userType
|
|
127
|
+
});
|
|
121
128
|
}
|
|
122
129
|
/**
|
|
123
130
|
* Delete every access token attached to one family, plus pre-family rows for
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"access-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport { plainTokenOf, storedTokenForms } from \"../../utils/token-digest\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted access-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape.\n *\n * `last_access` and the `is_active` soft-revoke flag were removed — neither was\n * ever read; access tokens are revoked by deleting the row.\n */\nexport const accessTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n /** Null for tokens issued before family tracking was introduced. */\n family_id: v.string().optional(),\n expires_at: v.date().required(),\n});\n\n/**\n * Persisted access-token record + the data layer for access tokens.\n *\n * **Role.** Owns access-token persistence and lookup. The middleware checks a\n * presented JWT against this table so deleting a row (logout) invalidates the\n * token immediately, before its JWT expiry. The auth service goes through the\n * named statics exclusively, so it never hard-codes a column name and an\n * override can rename/add columns by registering under\n * `config.auth.accessToken.model`.\n */\nexport class AccessToken extends Model {\n public static table = \"access_tokens\";\n\n public static schema = accessTokenSchema;\n\n /**\n * The raw signed JWT is a bearer credential — never serialize it. `hidden`\n * only strips it from `toJSON()` / `JSON.stringify(model)` (so\n * `response.json(token)` or a resource cannot leak it); `get(\"token\")`,\n * `findByToken` and every query still read the column.\n *\n * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256\n * digest instead, so a copy of the table cannot be replayed; read the raw\n * token of a freshly issued row through {@link plainToken}.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `access_tokensTrash` on every `destroy()` (logout, expiry purge,\n * never-expiring purge). A revoked/expired access token must not survive\n * anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** The user this token was issued for. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The user-type slug this token was issued for. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /**\n * The raw token, when it is known: always for a row stored unhashed, and\n * for a hashed row only in the process that just issued it.\n */\n public get plainToken(): string | undefined {\n return plainTokenOf(this, this.get(\"token\"));\n }\n\n /**\n * Whether the persisted expiry has passed.\n *\n * The middleware asks this on every request, which is what makes the row the\n * authority it always looked like it was: before 4.12.0 the gate only checked\n * that the row *existed*, so a row the database knew was dead still let its\n * token through — the database was never asked.\n *\n * **Fails closed.** A missing or unparseable `expires_at` counts as expired.\n * `expires_at` is `required` in the schema, so a row that cannot answer \"when\n * does this die\" is malformed, and the safe reading of a malformed credential\n * is that it is not one. This is deliberately stricter than a naive\n * `now > expires_at`, which answers `false` for an `Invalid Date` and thereby\n * grants exactly the poisoned rows an unlimited life.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date(expiresAt).getTime() <= Date.now();\n }\n\n /**\n * Whether nothing about this row can ever retire it — an unusable\n * `expires_at`, or a token carrying no `exp` claim. See\n * {@link isNeverExpiring}; this is the predicate `purgeNeverExpiring` selects\n * on.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /**\n * Persist a freshly-signed access token for the user. `token` is the value\n * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.\n */\n public static issue(user: Auth, token: string, expiresAt: Date, familyId?: string) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: familyId,\n expires_at: expiresAt,\n });\n }\n\n /**\n * Find an access-token row by its raw token string, whether the row stores\n * the token hashed or raw (one query).\n */\n public static findByToken(token: string): Promise<AccessToken | null> {\n return this.query().whereIn(\"token\", storedTokenForms(token)).first();\n }\n\n /**\n * Delete a specific token that belongs to the given user, stored hashed or raw.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .delete();\n }\n\n /**\n * Delete every access token belonging to the user.\n */\n public static deleteAllForUser(user: Auth) {\n return this.delete({ user_id: user.id });\n }\n\n /**\n * Delete every access token attached to one family, plus pre-family rows for\n * the same user type. The latter is deliberately conservative during the\n * additive upgrade: old access rows cannot be assigned safely to a family.\n */\n public static async deleteFamilyAndLegacyForUser(user: Auth, familyId: string): Promise<void> {\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: familyId });\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: null });\n }\n\n /**\n * Hard-delete every expired access-token row. Returns the number removed.\n * Runs from the `auth.cleanup` CLI command (a cold batch path).\n */\n public static async purgeExpired(): Promise<number> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens.length;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}.\n *\n * **A full scan, filtered in memory, on purpose.** The defining case is a row\n * whose `expires_at` is an `Invalid Date`, which no date predicate can select\n * (`< now` and `> now` are both `false` for it), and the definitive case is a\n * token with no `exp` claim, which lives inside the token string rather than\n * in a column. Neither is expressible as a `where`, so the rows have to be\n * read to be judged. This runs from a one-off remediation command, not a\n * request path.\n */\n public static async findNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: AccessToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed so the\n * caller can report what it revoked. Deletion *is* revocation for access\n * tokens — the middleware rejects a token with no row.\n */\n public static async purgeNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,oBAAoB,EAAE,OAAO;CACxC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;;CAE/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;AAChC,CAAC;;;;;;;;;;;AAYD,IAAa,cAAb,cAAiC,MAAM;;eACf;;;gBAEC;;;gBAYA,CAAC,OAAO;;;wBASA;;;CAG/B,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;;;;CAMA,IAAW,aAAiC;EAC1C,OAAO,aAAa,MAAM,KAAK,IAAI,OAAO,CAAC;CAC7C;;;;;;;;;;;;;;;;CAiBA,IAAW,YAAqB;EAC9B,MAAM,YAAY,KAAK,IAAI,YAAY;EAEvC,IAAI,CAAC,eAAe,SAAS,GAAG,OAAO;EAEvC,OAAO,IAAI,KAAK,SAAS,CAAC,CAAC,QAAQ,KAAK,KAAK,IAAI;CACnD;;;;;;;CAQA,IAAW,eAAwB;EACjC,OAAO,gBAAgB,KAAK,IAAI,OAAO,GAAG,KAAK,IAAI,YAAY,CAAC;CAClE;;;;;CAMA,OAAc,MAAM,MAAY,OAAe,WAAiB,UAAmB;EACjF,OAAO,KAAK,OAAO;GACjB;GACA,SAAS,KAAK;GACd,WAAW,KAAK;GAChB,WAAW;GACX,YAAY;EACd,CAAC;CACH;;;;;CAMA,OAAc,YAAY,OAA4C;EACpE,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,SAAS,iBAAiB,KAAK,CAAC,CAAC,CAAC,MAAM;CACtE;;;;CAKA,OAAc,cAAc,MAAY,OAAe;EACrD,OAAO,KAAK,MAAM,CAAC,CAChB,MAAM,
|
|
1
|
+
{"version":3,"file":"access-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport { plainTokenOf, storedTokenForms } from \"../../utils/token-digest\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted access-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape.\n *\n * `last_access` and the `is_active` soft-revoke flag were removed — neither was\n * ever read; access tokens are revoked by deleting the row.\n */\nexport const accessTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n /** Null for tokens issued before family tracking was introduced. */\n family_id: v.string().optional(),\n expires_at: v.date().required(),\n});\n\n/**\n * Persisted access-token record + the data layer for access tokens.\n *\n * **Role.** Owns access-token persistence and lookup. The middleware checks a\n * presented JWT against this table so deleting a row (logout) invalidates the\n * token immediately, before its JWT expiry. The auth service goes through the\n * named statics exclusively, so it never hard-codes a column name and an\n * override can rename/add columns by registering under\n * `config.auth.accessToken.model`.\n */\nexport class AccessToken extends Model {\n public static table = \"access_tokens\";\n\n public static schema = accessTokenSchema;\n\n /**\n * The raw signed JWT is a bearer credential — never serialize it. `hidden`\n * only strips it from `toJSON()` / `JSON.stringify(model)` (so\n * `response.json(token)` or a resource cannot leak it); `get(\"token\")`,\n * `findByToken` and every query still read the column.\n *\n * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256\n * digest instead, so a copy of the table cannot be replayed; read the raw\n * token of a freshly issued row through {@link plainToken}.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `access_tokensTrash` on every `destroy()` (logout, expiry purge,\n * never-expiring purge). A revoked/expired access token must not survive\n * anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** The user this token was issued for. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The user-type slug this token was issued for. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /**\n * The raw token, when it is known: always for a row stored unhashed, and\n * for a hashed row only in the process that just issued it.\n */\n public get plainToken(): string | undefined {\n return plainTokenOf(this, this.get(\"token\"));\n }\n\n /**\n * Whether the persisted expiry has passed.\n *\n * The middleware asks this on every request, which is what makes the row the\n * authority it always looked like it was: before 4.12.0 the gate only checked\n * that the row *existed*, so a row the database knew was dead still let its\n * token through — the database was never asked.\n *\n * **Fails closed.** A missing or unparseable `expires_at` counts as expired.\n * `expires_at` is `required` in the schema, so a row that cannot answer \"when\n * does this die\" is malformed, and the safe reading of a malformed credential\n * is that it is not one. This is deliberately stricter than a naive\n * `now > expires_at`, which answers `false` for an `Invalid Date` and thereby\n * grants exactly the poisoned rows an unlimited life.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date(expiresAt).getTime() <= Date.now();\n }\n\n /**\n * Whether nothing about this row can ever retire it — an unusable\n * `expires_at`, or a token carrying no `exp` claim. See\n * {@link isNeverExpiring}; this is the predicate `purgeNeverExpiring` selects\n * on.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /**\n * Persist a freshly-signed access token for the user. `token` is the value\n * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.\n */\n public static issue(user: Auth, token: string, expiresAt: Date, familyId?: string) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: familyId,\n expires_at: expiresAt,\n });\n }\n\n /**\n * Find an access-token row by its raw token string, whether the row stores\n * the token hashed or raw (one query).\n */\n public static findByToken(token: string): Promise<AccessToken | null> {\n return this.query().whereIn(\"token\", storedTokenForms(token)).first();\n }\n\n /**\n * Delete a specific token that belongs to the given user, stored hashed or raw.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType })\n .whereIn(\"token\", storedTokenForms(token))\n .delete();\n }\n\n /**\n * Delete every access token belonging to the user. Matches the user type as\n * well as the id, so another identity with the same id keeps its tokens.\n */\n public static deleteAllForUser(user: Auth) {\n return this.delete({ user_id: user.id, user_type: user.userType });\n }\n\n /**\n * Delete every access token attached to one family, plus pre-family rows for\n * the same user type. The latter is deliberately conservative during the\n * additive upgrade: old access rows cannot be assigned safely to a family.\n */\n public static async deleteFamilyAndLegacyForUser(user: Auth, familyId: string): Promise<void> {\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: familyId });\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: null });\n }\n\n /**\n * Hard-delete every expired access-token row. Returns the number removed.\n * Runs from the `auth.cleanup` CLI command (a cold batch path).\n */\n public static async purgeExpired(): Promise<number> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens.length;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}.\n *\n * **A full scan, filtered in memory, on purpose.** The defining case is a row\n * whose `expires_at` is an `Invalid Date`, which no date predicate can select\n * (`< now` and `> now` are both `false` for it), and the definitive case is a\n * token with no `exp` claim, which lives inside the token string rather than\n * in a column. Neither is expressible as a `where`, so the rows have to be\n * read to be judged. This runs from a one-off remediation command, not a\n * request path.\n */\n public static async findNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: AccessToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed so the\n * caller can report what it revoked. Deletion *is* revocation for access\n * tokens — the middleware rejects a token with no row.\n */\n public static async purgeNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,oBAAoB,EAAE,OAAO;CACxC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;;CAE/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;AAChC,CAAC;;;;;;;;;;;AAYD,IAAa,cAAb,cAAiC,MAAM;;eACf;;;gBAEC;;;gBAYA,CAAC,OAAO;;;wBASA;;;CAG/B,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;;;;CAMA,IAAW,aAAiC;EAC1C,OAAO,aAAa,MAAM,KAAK,IAAI,OAAO,CAAC;CAC7C;;;;;;;;;;;;;;;;CAiBA,IAAW,YAAqB;EAC9B,MAAM,YAAY,KAAK,IAAI,YAAY;EAEvC,IAAI,CAAC,eAAe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AG9D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAuB,MAAM,YAAY;CACjE;;;;;;CAOA,aAAoB,qBAA6C;EAC/D,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
|
|
@@ -149,7 +149,10 @@ var RefreshToken = class extends Model {
|
|
|
149
149
|
* revoke a token that actually belongs to them.
|
|
150
150
|
*/
|
|
151
151
|
static findForUser(user, token) {
|
|
152
|
-
return this.query().where({
|
|
152
|
+
return this.query().where({
|
|
153
|
+
user_id: user.id,
|
|
154
|
+
user_type: user.userType
|
|
155
|
+
}).whereIn("token", storedTokenForms(token)).first();
|
|
153
156
|
}
|
|
154
157
|
/** Find any member of a family, including an already-revoked legacy member. */
|
|
155
158
|
static findInFamily(familyId) {
|
|
@@ -169,7 +172,10 @@ var RefreshToken = class extends Model {
|
|
|
169
172
|
* Delete a specific refresh token belonging to the user, stored hashed or raw.
|
|
170
173
|
*/
|
|
171
174
|
static deleteForUser(user, token) {
|
|
172
|
-
return this.query().where({
|
|
175
|
+
return this.query().where({
|
|
176
|
+
user_id: user.id,
|
|
177
|
+
user_type: user.userType
|
|
178
|
+
}).whereIn("token", storedTokenForms(token)).delete();
|
|
173
179
|
}
|
|
174
180
|
/**
|
|
175
181
|
* Active, unexpired sessions for the user, newest first.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refresh-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { DeviceInfo } from \"../../contracts/types\";\nimport { plainTokenOf, storedTokenForms } from \"../../utils/token-digest\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted refresh-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape:\n *\n * @example\n * export class AppRefreshToken extends RefreshToken {\n * public static schema = refreshTokenSchema.extend({\n * organization_id: v.string().required(),\n * });\n * }\n */\nexport const refreshTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n family_id: v.string().required(),\n expires_at: v.date().required(),\n last_used_at: v.date().default(() => new Date()),\n revoked_at: v.date().optional(),\n /** The successor pair a bounded concurrent renewal may reuse. */\n successor_access_token_id: v.string().optional(),\n successor_refresh_token_id: v.string().optional(),\n device_info: v.record(v.any()).optional(),\n});\n\n/**\n * Extra attributes captured when a refresh token is issued.\n */\nexport type RefreshTokenIssueOptions = {\n familyId: string;\n expiresAt: string;\n deviceInfo?: DeviceInfo;\n};\n\n/**\n * Persisted refresh-token record + the data layer for refresh tokens.\n *\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\n * The auth service drives refresh-token state exclusively through this model's\n * named statics and instance methods, so it never hard-codes a column name —\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\n * structurally impossible and lets an override rename or add columns by\n * extending this class and registering it under `config.auth.refreshToken.model`.\n */\nexport class RefreshToken extends Model {\n public static table = \"refresh_tokens\";\n\n public static schema = refreshTokenSchema;\n\n /**\n * The raw signed refresh JWT is a bearer credential — never serialize it.\n * `hidden` only strips it from `toJSON()` / `JSON.stringify(model)` (e.g. a\n * session list returned via `response.json`); `get(\"token\")`,\n * `findByToken` / `findForUser` and every query still read the column.\n *\n * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256\n * digest instead; read the raw token of a freshly issued row through\n * {@link plainToken}.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `refresh_tokensTrash` on every `destroy()` (expiry purge,\n * never-expiring purge). A purged refresh token must not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** Token family this row belongs to (rotation / replay grouping). */\n public get familyId(): string {\n return this.get(\"family_id\");\n }\n\n /**\n * The raw refresh token, when it is known: always for a row stored\n * unhashed, and for a hashed row only in the process that just issued it\n * (e.g. the row `authService.createRefreshToken` returns).\n */\n public get plainToken(): string | undefined {\n return plainTokenOf(this, this.get(\"token\"));\n }\n\n /**\n * Whether the token's `expires_at` is in the past.\n *\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\n * counts as expired. It previously answered `false` for both — \"no expiry\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\n * that cannot say when it dies is malformed, not immortal.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date().getTime() > new Date(expiresAt).getTime();\n }\n\n /**\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /** Whether the token has been revoked. */\n public get isRevoked(): boolean {\n return !!this.get(\"revoked_at\");\n }\n\n /** Whether the token is still usable (not expired and not revoked). */\n public get isValid(): boolean {\n return !this.isExpired && !this.isRevoked;\n }\n\n /**\n * Unconditionally stamp `revoked_at` on this token.\n */\n public async revoke(): Promise<this> {\n return this.merge({ revoked_at: new Date() }).save();\n }\n\n /**\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\n * when this call performed the revoke, `false` when a concurrent request had\n * already revoked it — the win/lose signal that powers rotation replay\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\n * same token can never both succeed.\n */\n public async revokeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof RefreshToken;\n\n const revokedCount = await modelClass.atomic(\n { id: this.id, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return revokedCount > 0;\n }\n\n /**\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\n */\n public async markAsUsed(): Promise<void> {\n await this.merge({ last_used_at: new Date() }).save();\n }\n\n /**\n * Persist a freshly-signed refresh token for the user. `token` is the value\n * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.\n */\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: options.familyId,\n expires_at: options.expiresAt,\n device_info: options.deviceInfo\n ? {\n userAgent: options.deviceInfo.userAgent,\n ip: options.deviceInfo.ip,\n deviceId: options.deviceInfo.deviceId,\n }\n : undefined,\n });\n }\n\n /**\n * Find a refresh-token row by its raw token string, whether the row stores\n * the token hashed or raw (one query).\n */\n public static findByToken(token: string): Promise<RefreshToken | null> {\n return this.query().whereIn(\"token\", storedTokenForms(token)).first();\n }\n\n /**\n * Find a refresh token scoped to a user — used by logout so a caller can only\n * revoke a token that actually belongs to them.\n */\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .first();\n }\n\n /** Find any member of a family, including an already-revoked legacy member. */\n public static findInFamily(familyId: string): Promise<RefreshToken | null> {\n return this.first({ family_id: familyId });\n }\n\n /**\n * Every refresh lineage for a user, including rotated rows. Logout uses this\n * to bootstrap durable family records before it starts family revocations.\n */\n public static familiesForUser(user: Auth): Promise<RefreshToken[]> {\n return this.query().where({ user_id: user.id, user_type: user.userType }).get();\n }\n\n /**\n * Delete a specific refresh token belonging to the user, stored hashed or raw.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .delete();\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\n return this.activeQuery(user).orderBy(\"created_at\", \"desc\").get();\n }\n\n private static activeQuery(user: Auth) {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .where(\"expires_at\", \">\", new Date());\n }\n\n /**\n * Revoke every still-active refresh token for the user, returning the rows\n * that were revoked so the caller can emit a per-token event for each.\n *\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\n * `revoked_at: null` would re-query the same predicate after the update and\n * match nothing, returning an empty set.\n */\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\n const tokens = await this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n\n if (tokens.length === 0) return tokens;\n\n // One conditional update for the whole user; rows a concurrent request\n // revoked in between keep their earlier stamp.\n await this.atomic(\n { user_id: user.id, user_type: user.userType, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return tokens;\n }\n\n /**\n * Revoke every still-active token in a family (rotation breach containment),\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\n */\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\n * small.\n */\n public static async enforceMax(user: Auth, max: number): Promise<void> {\n const activeTokens = await this.activeQuery(user).orderBy(\"created_at\", \"asc\").get();\n\n if (activeTokens.length < max) return;\n\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\n\n for (const token of tokensToRevoke) {\n await token.revoke();\n }\n }\n\n /**\n * Hard-delete every expired refresh token, returning the deleted rows so the\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\n * (a cold batch path).\n */\n public static async purgeExpired(): Promise<RefreshToken[]> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}. A full\n * scan filtered in memory, for the reason given on\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\n * missing `exp` claim is expressible as a `where`.\n */\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: RefreshToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed.\n *\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\n * table has to carry, and one of the two shapes being removed is a row whose\n * date column cannot be compared at all — leaving it in place keeps a\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\n * these rows can no longer be presented successfully either way.\n */\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;CAC9B,cAAc,EAAE,KAAK,CAAC,CAAC,8BAAc,IAAI,KAAK,CAAC;CAC/C,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;;CAE9B,2BAA2B,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/C,4BAA4B,EAAE,OAAO,CAAC,CAAC,SAAS;CAChD,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,SAAS;AAC1C,CAAC;;;;;;;;;;;AAqBD,IAAa,eAAb,cAAkC,MAAM;;eAChB;;;gBAEC;;;gBAYA,CAAC,OAAO;;;wBAQA;;;CAG/B,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;;;;;CAOA,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;EAAK,GAC/D,EAAE,MAAM,EAAE,4BAAY,IAAI,KAAK,EAAE,EAAE,CACrC;EAEA,OAAO;CACT;;;;;CAMA,aAAoB,aAAa,UAA2C;EAC1E,MAAM,SAAS,MAAM,KAAK,MAAM,CAAC,CAAC,MAAM;GAAE,WAAW;GAAU,YAAY;EAAK,CAAC,CAAC,CAAC,IAAI;EAEvF,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,OAAO;EAGrB,OAAO;CACT;;;;;;CAOA,aAAoB,WAAW,MAAY,KAA4B;EACrE,MAAM,eAAe,MAAM,KAAK,YAAY,IAAI,CAAC,CAAC,QAAQ,cAAc,KAAK,CAAC,CAAC,IAAI;EAEnF,IAAI,aAAa,SAAS,KAAK;EAE/B,MAAM,iBAAiB,aAAa,MAAM,GAAG,aAAa,SAAS,MAAM,CAAC;EAE1E,KAAK,MAAM,SAAS,gBAClB,MAAM,MAAM,OAAO;CAEvB;;;;;;CAOA,aAAoB,eAAwC;EAC1D,MAAM,gBAAgB,MAAM,KAAK,MAAM,CAAC,CAAC,MAAM,cAAc,qBAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI;EAElF,KAAK,MAAM,SAAS,eAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;;;;;;;CAQA,aAAoB,oBAA6C;EAG/D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAwB,MAAM,YAAY;CAClE;;;;;;;;;;CAWA,aAAoB,qBAA8C;EAChE,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"refresh-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { DeviceInfo } from \"../../contracts/types\";\nimport { plainTokenOf, storedTokenForms } from \"../../utils/token-digest\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted refresh-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape:\n *\n * @example\n * export class AppRefreshToken extends RefreshToken {\n * public static schema = refreshTokenSchema.extend({\n * organization_id: v.string().required(),\n * });\n * }\n */\nexport const refreshTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n family_id: v.string().required(),\n expires_at: v.date().required(),\n last_used_at: v.date().default(() => new Date()),\n revoked_at: v.date().optional(),\n /** The successor pair a bounded concurrent renewal may reuse. */\n successor_access_token_id: v.string().optional(),\n successor_refresh_token_id: v.string().optional(),\n device_info: v.record(v.any()).optional(),\n});\n\n/**\n * Extra attributes captured when a refresh token is issued.\n */\nexport type RefreshTokenIssueOptions = {\n familyId: string;\n expiresAt: string;\n deviceInfo?: DeviceInfo;\n};\n\n/**\n * Persisted refresh-token record + the data layer for refresh tokens.\n *\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\n * The auth service drives refresh-token state exclusively through this model's\n * named statics and instance methods, so it never hard-codes a column name —\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\n * structurally impossible and lets an override rename or add columns by\n * extending this class and registering it under `config.auth.refreshToken.model`.\n */\nexport class RefreshToken extends Model {\n public static table = \"refresh_tokens\";\n\n public static schema = refreshTokenSchema;\n\n /**\n * The raw signed refresh JWT is a bearer credential — never serialize it.\n * `hidden` only strips it from `toJSON()` / `JSON.stringify(model)` (e.g. a\n * session list returned via `response.json`); `get(\"token\")`,\n * `findByToken` / `findForUser` and every query still read the column.\n *\n * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256\n * digest instead; read the raw token of a freshly issued row through\n * {@link plainToken}.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `refresh_tokensTrash` on every `destroy()` (expiry purge,\n * never-expiring purge). A purged refresh token must not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** Token family this row belongs to (rotation / replay grouping). */\n public get familyId(): string {\n return this.get(\"family_id\");\n }\n\n /**\n * The raw refresh token, when it is known: always for a row stored\n * unhashed, and for a hashed row only in the process that just issued it\n * (e.g. the row `authService.createRefreshToken` returns).\n */\n public get plainToken(): string | undefined {\n return plainTokenOf(this, this.get(\"token\"));\n }\n\n /**\n * Whether the token's `expires_at` is in the past.\n *\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\n * counts as expired. It previously answered `false` for both — \"no expiry\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\n * that cannot say when it dies is malformed, not immortal.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date().getTime() > new Date(expiresAt).getTime();\n }\n\n /**\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /** Whether the token has been revoked. */\n public get isRevoked(): boolean {\n return !!this.get(\"revoked_at\");\n }\n\n /** Whether the token is still usable (not expired and not revoked). */\n public get isValid(): boolean {\n return !this.isExpired && !this.isRevoked;\n }\n\n /**\n * Unconditionally stamp `revoked_at` on this token.\n */\n public async revoke(): Promise<this> {\n return this.merge({ revoked_at: new Date() }).save();\n }\n\n /**\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\n * when this call performed the revoke, `false` when a concurrent request had\n * already revoked it — the win/lose signal that powers rotation replay\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\n * same token can never both succeed.\n */\n public async revokeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof RefreshToken;\n\n const revokedCount = await modelClass.atomic(\n { id: this.id, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return revokedCount > 0;\n }\n\n /**\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\n */\n public async markAsUsed(): Promise<void> {\n await this.merge({ last_used_at: new Date() }).save();\n }\n\n /**\n * Persist a freshly-signed refresh token for the user. `token` is the value\n * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.\n */\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: options.familyId,\n expires_at: options.expiresAt,\n device_info: options.deviceInfo\n ? {\n userAgent: options.deviceInfo.userAgent,\n ip: options.deviceInfo.ip,\n deviceId: options.deviceInfo.deviceId,\n }\n : undefined,\n });\n }\n\n /**\n * Find a refresh-token row by its raw token string, whether the row stores\n * the token hashed or raw (one query).\n */\n public static findByToken(token: string): Promise<RefreshToken | null> {\n return this.query().whereIn(\"token\", storedTokenForms(token)).first();\n }\n\n /**\n * Find a refresh token scoped to a user — used by logout so a caller can only\n * revoke a token that actually belongs to them.\n */\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType })\n .whereIn(\"token\", storedTokenForms(token))\n .first();\n }\n\n /** Find any member of a family, including an already-revoked legacy member. */\n public static findInFamily(familyId: string): Promise<RefreshToken | null> {\n return this.first({ family_id: familyId });\n }\n\n /**\n * Every refresh lineage for a user, including rotated rows. Logout uses this\n * to bootstrap durable family records before it starts family revocations.\n */\n public static familiesForUser(user: Auth): Promise<RefreshToken[]> {\n return this.query().where({ user_id: user.id, user_type: user.userType }).get();\n }\n\n /**\n * Delete a specific refresh token belonging to the user, stored hashed or raw.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType })\n .whereIn(\"token\", storedTokenForms(token))\n .delete();\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\n return this.activeQuery(user).orderBy(\"created_at\", \"desc\").get();\n }\n\n private static activeQuery(user: Auth) {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .where(\"expires_at\", \">\", new Date());\n }\n\n /**\n * Revoke every still-active refresh token for the user, returning the rows\n * that were revoked so the caller can emit a per-token event for each.\n *\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\n * `revoked_at: null` would re-query the same predicate after the update and\n * match nothing, returning an empty set.\n */\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\n const tokens = await this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n\n if (tokens.length === 0) return tokens;\n\n // One conditional update for the whole user; rows a concurrent request\n // revoked in between keep their earlier stamp.\n await this.atomic(\n { user_id: user.id, user_type: user.userType, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return tokens;\n }\n\n /**\n * Revoke every still-active token in a family (rotation breach containment),\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\n */\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\n * small.\n */\n public static async enforceMax(user: Auth, max: number): Promise<void> {\n const activeTokens = await this.activeQuery(user).orderBy(\"created_at\", \"asc\").get();\n\n if (activeTokens.length < max) return;\n\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\n\n for (const token of tokensToRevoke) {\n await token.revoke();\n }\n }\n\n /**\n * Hard-delete every expired refresh token, returning the deleted rows so the\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\n * (a cold batch path).\n */\n public static async purgeExpired(): Promise<RefreshToken[]> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}. A full\n * scan filtered in memory, for the reason given on\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\n * missing `exp` claim is expressible as a `where`.\n */\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: RefreshToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed.\n *\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\n * table has to carry, and one of the two shapes being removed is a row whose\n * date column cannot be compared at all — leaving it in place keeps a\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\n * these rows can no longer be presented successfully either way.\n */\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;CAC9B,cAAc,EAAE,KAAK,CAAC,CAAC,8BAAc,IAAI,KAAK,CAAC;CAC/C,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;;CAE9B,2BAA2B,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/C,4BAA4B,EAAE,OAAO,CAAC,CAAC,SAAS;CAChD,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,SAAS;AAC1C,CAAC;;;;;;;;;;;AA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}
|
package/esm/otp/otp.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Auth } from "../models/auth.model.mjs";
|
|
2
2
|
import { DeviceInfo, LoginResult } from "../contracts/types.mjs";
|
|
3
|
+
import { Request } from "@warlock.js/core";
|
|
3
4
|
import { ChildModel } from "@warlock.js/cascade";
|
|
4
5
|
//#region ../../packages/auth/src/otp/otp.d.ts
|
|
5
6
|
/**
|
|
@@ -33,9 +34,11 @@ export declare function requestOtp<T extends Auth>(Model: ChildModel<T>, phone:
|
|
|
33
34
|
* most that many times even under concurrent guesses. A correct code is
|
|
34
35
|
* consumed single-use. Throttle the route with `otpVerifyThrottleMiddleware()`.
|
|
35
36
|
*
|
|
37
|
+
* Pass the `request` so `auth.canAuthenticate` receives it.
|
|
38
|
+
*
|
|
36
39
|
* @throws InvalidOneTimeTokenError (400, EC008) — the same for an unknown
|
|
37
40
|
* phone, a wrong, expired, used or exhausted code.
|
|
38
41
|
*/
|
|
39
|
-
export declare function verifyOtp<T extends Auth>(Model: ChildModel<T>, phone: string, code: string, deviceInfo?: DeviceInfo): Promise<LoginResult<T>>;
|
|
42
|
+
export declare function verifyOtp<T extends Auth>(Model: ChildModel<T>, phone: string, code: string, deviceInfo?: DeviceInfo, request?: Request): Promise<LoginResult<T>>;
|
|
40
43
|
//#endregion
|
|
41
44
|
//# sourceMappingURL=otp.d.mts.map
|
package/esm/otp/otp.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"otp.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/otp/otp.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"otp.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/otp/otp.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;wBAgGsB,WAAW,UAAU,MACzC,OAAO,WAAW,IAClB,eACA;EAAW;IACV;;;;;;;;;;;;;;;wBAwDmB,UAAU,UAAU,MACxC,OAAO,WAAW,IAClB,eACA,cACA,aAAa,YACb,UAAU,UACT,QAAQ,YAAY"}
|
package/esm/otp/otp.mjs
CHANGED
|
@@ -102,10 +102,12 @@ async function requestOtp(Model, phone, options = {}) {
|
|
|
102
102
|
* most that many times even under concurrent guesses. A correct code is
|
|
103
103
|
* consumed single-use. Throttle the route with `otpVerifyThrottleMiddleware()`.
|
|
104
104
|
*
|
|
105
|
+
* Pass the `request` so `auth.canAuthenticate` receives it.
|
|
106
|
+
*
|
|
105
107
|
* @throws InvalidOneTimeTokenError (400, EC008) — the same for an unknown
|
|
106
108
|
* phone, a wrong, expired, used or exhausted code.
|
|
107
109
|
*/
|
|
108
|
-
async function verifyOtp(Model, phone, code, deviceInfo) {
|
|
110
|
+
async function verifyOtp(Model, phone, code, deviceInfo, request) {
|
|
109
111
|
if (typeof phone !== "string" || phone.length === 0) throw invalidCode();
|
|
110
112
|
if (typeof code !== "string" || !CODE_PATTERN.test(code)) throw invalidCode();
|
|
111
113
|
const user = await Model.first({ [authConfig.otp.phoneField()]: phone });
|
|
@@ -118,7 +120,10 @@ async function verifyOtp(Model, phone, code, deviceInfo) {
|
|
|
118
120
|
}
|
|
119
121
|
if (!codeMatches(user, String(row.get("token_hash") ?? ""), code)) throw invalidCode();
|
|
120
122
|
if (!await row.consumeIfActive()) throw invalidCode();
|
|
121
|
-
return authService.completeLogin(user, deviceInfo
|
|
123
|
+
return authService.completeLogin(user, deviceInfo, {
|
|
124
|
+
via: "otp",
|
|
125
|
+
request
|
|
126
|
+
});
|
|
122
127
|
}
|
|
123
128
|
|
|
124
129
|
//#endregion
|
package/esm/otp/otp.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"otp.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/otp/otp.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { log } from \"@warlock.js/logger\";\nimport { createHmac, randomBytes, randomInt } from \"node:crypto\";\nimport type { OtpMessage, OtpSender } from \"../contracts/providers\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidOneTimeTokenError } from \"../errors/invalid-one-time-token.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authEvents } from \"../services/auth-events\";\nimport { authService } from \"../services/auth.service\";\nimport { runInBackground } from \"../services/background-work\";\nimport { oneTimeTokenModel } from \"../services/one-time-tokens\";\nimport { loadOptionalPeer } from \"../services/optional-peer\";\nimport { safeEqual } from \"../utils/safe-equal\";\n\n/** The slice of `@warlock.js/notifications` OTP delivery uses (an optional peer). */\ntype NotifyModule = {\n notify: {\n channel: (name: string) => { send: (to: string, payload: unknown) => Promise<unknown> };\n };\n};\n\nconst CODE_PATTERN = /^\\d{6}$/;\n\n/** One error for every rejection: unknown phone, no code, wrong, expired, used, over the cap. */\nfunction invalidCode(): InvalidOneTimeTokenError {\n return new InvalidOneTimeTokenError(\"Invalid or expired code.\");\n}\n\n/**\n * Keyed hash of a code. A plain SHA-256 of a 6-digit code is reversed by\n * trying all million values, so the MAC key (derived from the access-token\n * secret) is what keeps a leaked table useless. `salt` makes each stored\n * value unique.\n */\nfunction macCode(user: Auth, salt: string, code: string): string {\n const key = createHmac(\"sha256\", authConfig.accessToken.secret())\n .update(\"@warlock.js/auth:otp\")\n .digest();\n\n return createHmac(\"sha256\", key)\n .update(`${salt}:${user.userType}:${user.id}:${code}`)\n .digest(\"base64url\");\n}\n\n/** Stored form: `<salt>.<mac>` — 16 + 1 + 43 chars, inside the 64-char `token_hash` column. */\nfunction storedCodeHash(user: Auth, code: string): string {\n const salt = randomBytes(12).toString(\"base64url\");\n\n return `${salt}.${macCode(user, salt, code)}`;\n}\n\nfunction codeMatches(user: Auth, stored: string, code: string): boolean {\n const [salt, mac] = stored.split(\".\");\n\n return !!salt && !!mac && safeEqual(mac, macCode(user, salt, code));\n}\n\n/**\n * Resolve how a code is sent: `auth.otp.send`, else the app's notifications\n * channel. Resolved BEFORE the user lookup, so a missing notifications package\n * fails identically for known and unknown phones.\n */\nasync function resolveDelivery(channel: string): Promise<OtpSender> {\n const custom = authConfig.otp.send();\n\n if (custom) return custom;\n\n const { notify } = await loadOptionalPeer<NotifyModule>(\n \"@warlock.js/notifications\",\n \"notifications\",\n );\n\n return (phone, message, channelName) => notify.channel(channelName).send(phone, message);\n}\n\n/**\n * Send a 6-digit login code to the account whose `auth.otp.phoneField`\n * (default `phone`) equals `phone`, through the notifications channel named by\n * `options.channel` / `auth.otp.channel` (default `\"sms\"`). Auth ships no\n * SMS/WhatsApp driver — the app registers that channel.\n *\n * The code is stored only as a keyed hash in `one_time_tokens` (purpose\n * `otp`), expires after `auth.otp.expiresIn` (default 5m), and replaces any\n * earlier unused code. **Anti-enumeration:** an unknown phone resolves the same\n * way and sends nothing, and the lookup, the code writes and the delivery run\n * in the background so the response time does not reveal a known phone. A\n * failure is logged and emitted as `otp.deliveryFailed`; set\n * `auth.otp.awaitDelivery: true` to wait for all of it (and receive its error)\n * instead. Throttle the route with\n * `otpRequestThrottleMiddleware()`.\n *\n * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not\n * installed and no `auth.otp.send` is configured.\n */\nexport async function requestOtp<T extends Auth>(\n Model: ChildModel<T>,\n phone: string,\n options: { channel?: string } = {},\n): Promise<void> {\n const channel = options.channel ?? authConfig.otp.channel();\n const deliver = await resolveDelivery(channel);\n\n if (typeof phone !== \"string\" || phone.length === 0) return;\n\n let user: T | null = null;\n\n const issueAndDeliver = async (): Promise<void> => {\n user = (await Model.first({ [authConfig.otp.phoneField()]: phone })) as T | null;\n\n if (!user) return;\n\n const code = String(randomInt(0, 1_000_000)).padStart(6, \"0\");\n const expiresAt = new Date(Date.now() + authConfig.otp.expiresInMs());\n const TokenModel = oneTimeTokenModel();\n\n await TokenModel.invalidateActiveFor(user, \"otp\");\n await TokenModel.issue(user, \"otp\", storedCodeHash(user, code), expiresAt);\n\n const message: OtpMessage = { body: authConfig.otp.message(code), code, expiresAt };\n\n await deliver(phone, message, channel);\n };\n\n if (authConfig.otp.awaitDelivery()) {\n await issueAndDeliver();\n\n return;\n }\n\n // The lookup, the code writes and the delivery all run after the response,\n // so a known and an unknown phone answer in the same time.\n runInBackground(() =>\n issueAndDeliver().catch((error: unknown) => {\n log.error(\"auth\", \"otp\", error);\n\n if (user) authEvents.emit(\"otp.deliveryFailed\", user, error);\n }),\n );\n}\n\n/**\n * Verify a phone login code and log the user in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * Each check first counts an attempt atomically; once `auth.otp.maxAttempts`\n * (default 5) have been counted the code is invalidated, so it is compared at\n * most that many times even under concurrent guesses. A correct code is\n * consumed single-use. Throttle the route with `otpVerifyThrottleMiddleware()`.\n *\n * @throws InvalidOneTimeTokenError (400, EC008) — the same for an unknown\n * phone, a wrong, expired, used or exhausted code.\n */\nexport async function verifyOtp<T extends Auth>(\n Model: ChildModel<T>,\n phone: string,\n code: string,\n deviceInfo?: DeviceInfo,\n): Promise<LoginResult<T>> {\n if (typeof phone !== \"string\" || phone.length === 0) throw invalidCode();\n if (typeof code !== \"string\" || !CODE_PATTERN.test(code)) throw invalidCode();\n\n const user = (await Model.first({ [authConfig.otp.phoneField()]: phone })) as T | null;\n\n if (!user) throw invalidCode();\n\n const row = await oneTimeTokenModel().findActiveFor(user, \"otp\");\n\n if (!row || row.isConsumed || row.isExpired) throw invalidCode();\n\n if (!(await row.recordAttempt(authConfig.otp.maxAttempts()))) {\n await row.consumeIfActive();\n\n throw invalidCode();\n }\n\n if (!codeMatches(user, String(row.get(\"token_hash\") ?? \"\"), code)) throw invalidCode();\n\n if (!(await row.consumeIfActive())) throw invalidCode();\n\n return authService.completeLogin(user, deviceInfo);\n}\n"],"mappings":";;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"otp.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/otp/otp.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Request } from \"@warlock.js/core\";\nimport { createHmac, randomBytes, randomInt } from \"node:crypto\";\nimport type { OtpMessage, OtpSender } from \"../contracts/providers\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidOneTimeTokenError } from \"../errors/invalid-one-time-token.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authEvents } from \"../services/auth-events\";\nimport { authService } from \"../services/auth.service\";\nimport { runInBackground } from \"../services/background-work\";\nimport { oneTimeTokenModel } from \"../services/one-time-tokens\";\nimport { loadOptionalPeer } from \"../services/optional-peer\";\nimport { safeEqual } from \"../utils/safe-equal\";\n\n/** The slice of `@warlock.js/notifications` OTP delivery uses (an optional peer). */\ntype NotifyModule = {\n notify: {\n channel: (name: string) => { send: (to: string, payload: unknown) => Promise<unknown> };\n };\n};\n\nconst CODE_PATTERN = /^\\d{6}$/;\n\n/** One error for every rejection: unknown phone, no code, wrong, expired, used, over the cap. */\nfunction invalidCode(): InvalidOneTimeTokenError {\n return new InvalidOneTimeTokenError(\"Invalid or expired code.\");\n}\n\n/**\n * Keyed hash of a code. A plain SHA-256 of a 6-digit code is reversed by\n * trying all million values, so the MAC key (derived from the access-token\n * secret) is what keeps a leaked table useless. `salt` makes each stored\n * value unique.\n */\nfunction macCode(user: Auth, salt: string, code: string): string {\n const key = createHmac(\"sha256\", authConfig.accessToken.secret())\n .update(\"@warlock.js/auth:otp\")\n .digest();\n\n return createHmac(\"sha256\", key)\n .update(`${salt}:${user.userType}:${user.id}:${code}`)\n .digest(\"base64url\");\n}\n\n/** Stored form: `<salt>.<mac>` — 16 + 1 + 43 chars, inside the 64-char `token_hash` column. */\nfunction storedCodeHash(user: Auth, code: string): string {\n const salt = randomBytes(12).toString(\"base64url\");\n\n return `${salt}.${macCode(user, salt, code)}`;\n}\n\nfunction codeMatches(user: Auth, stored: string, code: string): boolean {\n const [salt, mac] = stored.split(\".\");\n\n return !!salt && !!mac && safeEqual(mac, macCode(user, salt, code));\n}\n\n/**\n * Resolve how a code is sent: `auth.otp.send`, else the app's notifications\n * channel. Resolved BEFORE the user lookup, so a missing notifications package\n * fails identically for known and unknown phones.\n */\nasync function resolveDelivery(channel: string): Promise<OtpSender> {\n const custom = authConfig.otp.send();\n\n if (custom) return custom;\n\n const { notify } = await loadOptionalPeer<NotifyModule>(\n \"@warlock.js/notifications\",\n \"notifications\",\n );\n\n return (phone, message, channelName) => notify.channel(channelName).send(phone, message);\n}\n\n/**\n * Send a 6-digit login code to the account whose `auth.otp.phoneField`\n * (default `phone`) equals `phone`, through the notifications channel named by\n * `options.channel` / `auth.otp.channel` (default `\"sms\"`). Auth ships no\n * SMS/WhatsApp driver — the app registers that channel.\n *\n * The code is stored only as a keyed hash in `one_time_tokens` (purpose\n * `otp`), expires after `auth.otp.expiresIn` (default 5m), and replaces any\n * earlier unused code. **Anti-enumeration:** an unknown phone resolves the same\n * way and sends nothing, and the lookup, the code writes and the delivery run\n * in the background so the response time does not reveal a known phone. A\n * failure is logged and emitted as `otp.deliveryFailed`; set\n * `auth.otp.awaitDelivery: true` to wait for all of it (and receive its error)\n * instead. Throttle the route with\n * `otpRequestThrottleMiddleware()`.\n *\n * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not\n * installed and no `auth.otp.send` is configured.\n */\nexport async function requestOtp<T extends Auth>(\n Model: ChildModel<T>,\n phone: string,\n options: { channel?: string } = {},\n): Promise<void> {\n const channel = options.channel ?? authConfig.otp.channel();\n const deliver = await resolveDelivery(channel);\n\n if (typeof phone !== \"string\" || phone.length === 0) return;\n\n let user: T | null = null;\n\n const issueAndDeliver = async (): Promise<void> => {\n user = (await Model.first({ [authConfig.otp.phoneField()]: phone })) as T | null;\n\n if (!user) return;\n\n const code = String(randomInt(0, 1_000_000)).padStart(6, \"0\");\n const expiresAt = new Date(Date.now() + authConfig.otp.expiresInMs());\n const TokenModel = oneTimeTokenModel();\n\n await TokenModel.invalidateActiveFor(user, \"otp\");\n await TokenModel.issue(user, \"otp\", storedCodeHash(user, code), expiresAt);\n\n const message: OtpMessage = { body: authConfig.otp.message(code), code, expiresAt };\n\n await deliver(phone, message, channel);\n };\n\n if (authConfig.otp.awaitDelivery()) {\n await issueAndDeliver();\n\n return;\n }\n\n // The lookup, the code writes and the delivery all run after the response,\n // so a known and an unknown phone answer in the same time.\n runInBackground(() =>\n issueAndDeliver().catch((error: unknown) => {\n log.error(\"auth\", \"otp\", error);\n\n if (user) authEvents.emit(\"otp.deliveryFailed\", user, error);\n }),\n );\n}\n\n/**\n * Verify a phone login code and log the user in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * Each check first counts an attempt atomically; once `auth.otp.maxAttempts`\n * (default 5) have been counted the code is invalidated, so it is compared at\n * most that many times even under concurrent guesses. A correct code is\n * consumed single-use. Throttle the route with `otpVerifyThrottleMiddleware()`.\n *\n * Pass the `request` so `auth.canAuthenticate` receives it.\n *\n * @throws InvalidOneTimeTokenError (400, EC008) — the same for an unknown\n * phone, a wrong, expired, used or exhausted code.\n */\nexport async function verifyOtp<T extends Auth>(\n Model: ChildModel<T>,\n phone: string,\n code: string,\n deviceInfo?: DeviceInfo,\n request?: Request,\n): Promise<LoginResult<T>> {\n if (typeof phone !== \"string\" || phone.length === 0) throw invalidCode();\n if (typeof code !== \"string\" || !CODE_PATTERN.test(code)) throw invalidCode();\n\n const user = (await Model.first({ [authConfig.otp.phoneField()]: phone })) as T | null;\n\n if (!user) throw invalidCode();\n\n const row = await oneTimeTokenModel().findActiveFor(user, \"otp\");\n\n if (!row || row.isConsumed || row.isExpired) throw invalidCode();\n\n if (!(await row.recordAttempt(authConfig.otp.maxAttempts()))) {\n await row.consumeIfActive();\n\n throw invalidCode();\n }\n\n if (!codeMatches(user, String(row.get(\"token_hash\") ?? \"\"), code)) throw invalidCode();\n\n if (!(await row.consumeIfActive())) throw invalidCode();\n\n return authService.completeLogin(user, deviceInfo, { via: \"otp\", request });\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAM,eAAe;;AAGrB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AAI,CAAC,YAAY,MAAM,OAAO,IAAI,IAAI,YAAY,KAAK,EAAE,GAAG,IAAI,GAAG,MAAM,YAAY;CAErF,IAAI,CAAE,MAAM,IAAI,gBAAgB,GAAI,MAAM,YAAY;CAEtD,OAAO,YAAY,cAAc,MAAM,YAAY;EAAE,KAAK;EAAO;CAAQ,CAAC;AAC5E"}
|
|
@@ -86,7 +86,10 @@ async function verifyPasskeyAuthentication(request, credential, deviceInfo) {
|
|
|
86
86
|
const UserModel = config.key(`auth.userType.${stored.userType}`);
|
|
87
87
|
const user = UserModel ? await UserModel.find(stored.userId) : null;
|
|
88
88
|
if (!user) throw new InvalidPasskeyError("credential-owner-missing");
|
|
89
|
-
return authService.completeLogin(user, deviceInfo
|
|
89
|
+
return authService.completeLogin(user, deviceInfo, {
|
|
90
|
+
via: "passkey",
|
|
91
|
+
request
|
|
92
|
+
});
|
|
90
93
|
}
|
|
91
94
|
|
|
92
95
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"passkey-authentication.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/passkeys/passkey-authentication.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { config, type Request } from \"@warlock.js/core\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidPasskeyError } from \"../errors/invalid-passkey.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { PasskeyCredential } from \"../models/passkey-credential\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authService } from \"../services/auth.service\";\nimport {\n assertPasskeyOrigin,\n storePasskeyChallenge,\n takePasskeyChallenge,\n} from \"./passkey-challenges\";\nimport {\n loadSimpleWebAuthn,\n type PasskeyOptionsJSON,\n type PasskeyResponseJSON,\n} from \"./simplewebauthn\";\n\n/** A counter that did not advance past the stored one (when either is non-zero): a cloned authenticator. */\nfunction counterRegressed(stored: number, presented: number | undefined): boolean {\n if (presented === undefined) return false;\n\n return (stored > 0 || presented > 0) && !(presented > stored);\n}\n\n/**\n * The signature counter an assertion CLAIMS (bytes 33–36 of authenticatorData).\n * Unverified — only used to label a rejection the SDK already made.\n */\nfunction presentedCounter(credential: PasskeyResponseJSON): number | undefined {\n const encoded = credential.response.authenticatorData;\n\n if (typeof encoded !== \"string\") return undefined;\n\n const authData = Buffer.from(encoded, \"base64url\");\n\n return authData.length >= 37 ? authData.readUInt32BE(33) : undefined;\n}\n\n/**\n * Authentication options for a passkey login. No user is identified yet\n * (discoverable credentials), so the stored single-use challenge has no owner;\n * the credential the browser returns decides the user.\n *\n * @example\n * // POST /auth/passkeys/login/options\n * response.success(await generatePasskeyAuthenticationOptions());\n */\nexport async function generatePasskeyAuthenticationOptions(): Promise<PasskeyOptionsJSON> {\n const webauthn = await loadSimpleWebAuthn();\n\n const options = await webauthn.generateAuthenticationOptions({\n rpID: authConfig.passkeys.settings().rpID,\n userVerification: authConfig.passkeys.userVerification(),\n });\n\n await storePasskeyChallenge(\"passkey-authentication\", options.challenge);\n\n return options;\n}\n\n/**\n * Verify a passkey assertion and log its owner in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * Checks, in order: the request `Origin` (CSRF), the single-use challenge\n * (consumed even if what follows fails), the credential is registered, the\n * assertion via `@simplewebauthn/server`, then that the signature counter\n * ADVANCED — a counter that did not move past the stored one (when either is\n * non-zero) means a cloned authenticator and is rejected. The new counter is\n * written with a compare-and-set.\n *\n * @throws InvalidPasskeyError (400, EC011) on any rejection.\n */\nexport async function verifyPasskeyAuthentication(\n request: Request,\n credential: PasskeyResponseJSON,\n deviceInfo?: DeviceInfo,\n): Promise<LoginResult<Auth>> {\n const webauthn = await loadSimpleWebAuthn();\n const origins = assertPasskeyOrigin(request);\n const { challenge } = await takePasskeyChallenge(\"passkey-authentication\", credential);\n\n const stored =\n typeof credential.id === \"string\"\n ? await PasskeyCredential.findByCredentialId(credential.id)\n : null;\n\n if (!stored) {\n throw new InvalidPasskeyError(\"unknown-credential\");\n }\n\n let verification: Awaited<ReturnType<typeof webauthn.verifyAuthenticationResponse>>;\n\n try {\n verification = await webauthn.verifyAuthenticationResponse({\n response: credential,\n expectedChallenge: challenge,\n expectedOrigin: origins,\n expectedRPID: authConfig.passkeys.settings().rpID,\n credential: {\n id: stored.credentialId,\n publicKey: new Uint8Array(Buffer.from(String(stored.get(\"public_key\")), \"base64url\")),\n counter: stored.counter,\n transports: stored.get(\"transports\") ?? undefined,\n },\n requireUserVerification: authConfig.passkeys.userVerification() === \"required\",\n });\n } catch (error) {\n // The SDK enforces the counter rule itself and throws a generic Error for\n // it; keep clone detection visible as its own reason in the logs.\n const reason = counterRegressed(stored.counter, presentedCounter(credential))\n ? \"counter-regression\"\n : \"authentication-verification-failed\";\n\n throw new InvalidPasskeyError(reason, error);\n }\n\n if (!verification.verified) {\n throw new InvalidPasskeyError(\"authentication-not-verified\");\n }\n\n const previous = stored.counter;\n const next = Number(verification.authenticationInfo.newCounter);\n\n if (counterRegressed(previous, next)) {\n throw new InvalidPasskeyError(\"counter-regression\");\n }\n\n if (!(await stored.advanceCounter(previous, next))) {\n throw new InvalidPasskeyError(\"counter-changed-concurrently\");\n }\n\n const UserModel = config.key<ChildModel<Auth> | undefined>(`auth.userType.${stored.userType}`);\n const user = UserModel ? ((await UserModel.find(stored.userId)) as Auth | null) : null;\n\n if (!user) {\n throw new InvalidPasskeyError(\"credential-owner-missing\");\n }\n\n return authService.completeLogin(user, deviceInfo);\n}\n"],"mappings":";;;;;;;;;;;AAoBA,SAAS,iBAAiB,QAAgB,WAAwC;CAChF,IAAI,cAAc,QAAW,OAAO;CAEpC,QAAQ,SAAS,KAAK,YAAY,MAAM,EAAE,YAAY;AACxD;;;;;AAMA,SAAS,iBAAiB,YAAqD;CAC7E,MAAM,UAAU,WAAW,SAAS;CAEpC,IAAI,OAAO,YAAY,UAAU,OAAO;CAExC,MAAM,WAAW,OAAO,KAAK,SAAS,WAAW;CAEjD,OAAO,SAAS,UAAU,KAAK,SAAS,aAAa,EAAE,IAAI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AAM,IAAI,oBAAoB,oBAAoB;CAGpD,IAAI,CAAE,MAAM,OAAO,eAAe,UAAU,IAAI,GAC9C,MAAM,IAAI,oBAAoB,8BAA8B;CAG9D,MAAM,YAAY,OAAO,IAAkC,iBAAiB,OAAO,UAAU;CAC7F,MAAM,OAAO,YAAc,MAAM,UAAU,KAAK,OAAO,MAAM,IAAqB;CAElF,IAAI,CAAC,MACH,MAAM,IAAI,oBAAoB,0BAA0B;CAG1D,OAAO,YAAY,cAAc,MAAM,
|
|
1
|
+
{"version":3,"file":"passkey-authentication.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/passkeys/passkey-authentication.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { config, type Request } from \"@warlock.js/core\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidPasskeyError } from \"../errors/invalid-passkey.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { PasskeyCredential } from \"../models/passkey-credential\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authService } from \"../services/auth.service\";\nimport {\n assertPasskeyOrigin,\n storePasskeyChallenge,\n takePasskeyChallenge,\n} from \"./passkey-challenges\";\nimport {\n loadSimpleWebAuthn,\n type PasskeyOptionsJSON,\n type PasskeyResponseJSON,\n} from \"./simplewebauthn\";\n\n/** A counter that did not advance past the stored one (when either is non-zero): a cloned authenticator. */\nfunction counterRegressed(stored: number, presented: number | undefined): boolean {\n if (presented === undefined) return false;\n\n return (stored > 0 || presented > 0) && !(presented > stored);\n}\n\n/**\n * The signature counter an assertion CLAIMS (bytes 33–36 of authenticatorData).\n * Unverified — only used to label a rejection the SDK already made.\n */\nfunction presentedCounter(credential: PasskeyResponseJSON): number | undefined {\n const encoded = credential.response.authenticatorData;\n\n if (typeof encoded !== \"string\") return undefined;\n\n const authData = Buffer.from(encoded, \"base64url\");\n\n return authData.length >= 37 ? authData.readUInt32BE(33) : undefined;\n}\n\n/**\n * Authentication options for a passkey login. No user is identified yet\n * (discoverable credentials), so the stored single-use challenge has no owner;\n * the credential the browser returns decides the user.\n *\n * @example\n * // POST /auth/passkeys/login/options\n * response.success(await generatePasskeyAuthenticationOptions());\n */\nexport async function generatePasskeyAuthenticationOptions(): Promise<PasskeyOptionsJSON> {\n const webauthn = await loadSimpleWebAuthn();\n\n const options = await webauthn.generateAuthenticationOptions({\n rpID: authConfig.passkeys.settings().rpID,\n userVerification: authConfig.passkeys.userVerification(),\n });\n\n await storePasskeyChallenge(\"passkey-authentication\", options.challenge);\n\n return options;\n}\n\n/**\n * Verify a passkey assertion and log its owner in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * Checks, in order: the request `Origin` (CSRF), the single-use challenge\n * (consumed even if what follows fails), the credential is registered, the\n * assertion via `@simplewebauthn/server`, then that the signature counter\n * ADVANCED — a counter that did not move past the stored one (when either is\n * non-zero) means a cloned authenticator and is rejected. The new counter is\n * written with a compare-and-set.\n *\n * @throws InvalidPasskeyError (400, EC011) on any rejection.\n */\nexport async function verifyPasskeyAuthentication(\n request: Request,\n credential: PasskeyResponseJSON,\n deviceInfo?: DeviceInfo,\n): Promise<LoginResult<Auth>> {\n const webauthn = await loadSimpleWebAuthn();\n const origins = assertPasskeyOrigin(request);\n const { challenge } = await takePasskeyChallenge(\"passkey-authentication\", credential);\n\n const stored =\n typeof credential.id === \"string\"\n ? await PasskeyCredential.findByCredentialId(credential.id)\n : null;\n\n if (!stored) {\n throw new InvalidPasskeyError(\"unknown-credential\");\n }\n\n let verification: Awaited<ReturnType<typeof webauthn.verifyAuthenticationResponse>>;\n\n try {\n verification = await webauthn.verifyAuthenticationResponse({\n response: credential,\n expectedChallenge: challenge,\n expectedOrigin: origins,\n expectedRPID: authConfig.passkeys.settings().rpID,\n credential: {\n id: stored.credentialId,\n publicKey: new Uint8Array(Buffer.from(String(stored.get(\"public_key\")), \"base64url\")),\n counter: stored.counter,\n transports: stored.get(\"transports\") ?? undefined,\n },\n requireUserVerification: authConfig.passkeys.userVerification() === \"required\",\n });\n } catch (error) {\n // The SDK enforces the counter rule itself and throws a generic Error for\n // it; keep clone detection visible as its own reason in the logs.\n const reason = counterRegressed(stored.counter, presentedCounter(credential))\n ? \"counter-regression\"\n : \"authentication-verification-failed\";\n\n throw new InvalidPasskeyError(reason, error);\n }\n\n if (!verification.verified) {\n throw new InvalidPasskeyError(\"authentication-not-verified\");\n }\n\n const previous = stored.counter;\n const next = Number(verification.authenticationInfo.newCounter);\n\n if (counterRegressed(previous, next)) {\n throw new InvalidPasskeyError(\"counter-regression\");\n }\n\n if (!(await stored.advanceCounter(previous, next))) {\n throw new InvalidPasskeyError(\"counter-changed-concurrently\");\n }\n\n const UserModel = config.key<ChildModel<Auth> | undefined>(`auth.userType.${stored.userType}`);\n const user = UserModel ? ((await UserModel.find(stored.userId)) as Auth | null) : null;\n\n if (!user) {\n throw new InvalidPasskeyError(\"credential-owner-missing\");\n }\n\n return authService.completeLogin(user, deviceInfo, { via: \"passkey\", request });\n}\n"],"mappings":";;;;;;;;;;;AAoBA,SAAS,iBAAiB,QAAgB,WAAwC;CAChF,IAAI,cAAc,QAAW,OAAO;CAEpC,QAAQ,SAAS,KAAK,YAAY,MAAM,EAAE,YAAY;AACxD;;;;;AAMA,SAAS,iBAAiB,YAAqD;CAC7E,MAAM,UAAU,WAAW,SAAS;CAEpC,IAAI,OAAO,YAAY,UAAU,OAAO;CAExC,MAAM,WAAW,OAAO,KAAK,SAAS,WAAW;CAEjD,OAAO,SAAS,UAAU,KAAK,SAAS,aAAa,EAAE,IAAI;AAC7D;;;;;;;;;;AAWA,eAAsB,uCAAoE;CAGxF,MAAM,UAAU,OAAM,MAFC,mBAAmB,EAEZ,CAAC,8BAA8B;EAC3D,MAAM,WAAW,SAAS,SAAS,CAAC,CAAC;EACrC,kBAAkB,WAAW,SAAS,iBAAiB;CACzD,CAAC;CAED,MAAM,sBAAsB,0BAA0B,QAAQ,SAAS;CAEvE,OAAO;AACT;;;;;;;;;;;;;;AAeA,eAAsB,4BACp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