@warlock.js/auth 5.64.0 → 5.65.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/esm/contracts/index.d.mts +2 -2
  3. package/esm/contracts/types.d.mts +36 -2
  4. package/esm/contracts/types.d.mts.map +1 -1
  5. package/esm/contracts/types.mjs.map +1 -1
  6. package/esm/index.d.mts +2 -2
  7. package/esm/models/access-token/access-token.model.d.mts +2 -1
  8. package/esm/models/access-token/access-token.model.d.mts.map +1 -1
  9. package/esm/models/access-token/access-token.model.mjs +10 -3
  10. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  11. package/esm/models/refresh-token/refresh-token.model.mjs +8 -2
  12. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  13. package/esm/otp/otp.d.mts +4 -1
  14. package/esm/otp/otp.d.mts.map +1 -1
  15. package/esm/otp/otp.mjs +7 -2
  16. package/esm/otp/otp.mjs.map +1 -1
  17. package/esm/passkeys/passkey-authentication.mjs +4 -1
  18. package/esm/passkeys/passkey-authentication.mjs.map +1 -1
  19. package/esm/providers/provider-login.mjs +4 -1
  20. package/esm/providers/provider-login.mjs.map +1 -1
  21. package/esm/services/auth-config.mjs +2 -2
  22. package/esm/services/auth-config.mjs.map +1 -1
  23. package/esm/services/auth.service.d.mts +32 -7
  24. package/esm/services/auth.service.d.mts.map +1 -1
  25. package/esm/services/auth.service.mjs +82 -27
  26. package/esm/services/auth.service.mjs.map +1 -1
  27. package/esm/services/resolve-request-user.d.mts.map +1 -1
  28. package/esm/services/resolve-request-user.mjs +6 -2
  29. package/esm/services/resolve-request-user.mjs.map +1 -1
  30. package/llms-full.txt +7 -3
  31. package/package.json +8 -8
  32. package/skills/customize-user-type/SKILL.md +1 -1
  33. package/skills/handle-login-and-logout/SKILL.md +4 -0
  34. package/skills/login-with-providers/SKILL.md +1 -1
  35. package/skills/manage-tokens/SKILL.md +1 -1
@@ -119,7 +119,10 @@ async function completeProviderLogin(Model, providerName, request, response, dev
119
119
  }
120
120
  });
121
121
  const user = await resolveProviderUser(Model, profile);
122
- return authService.completeLogin(user, deviceInfo);
122
+ return authService.completeLogin(user, deviceInfo, {
123
+ via: "oauth",
124
+ request
125
+ });
123
126
  }
124
127
 
125
128
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"provider-login.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/providers/provider-login.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport type { Request, Response } from \"@warlock.js/core\";\nimport type { AuthProvider } from \"../contracts/providers\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidProviderCallbackError } from \"../errors/invalid-provider-callback.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authService } from \"../services/auth.service\";\nimport { AppleProvider } from \"./apple-provider\";\nimport { DiscordProvider } from \"./discord-provider\";\nimport { FacebookProvider } from \"./facebook-provider\";\nimport { GitHubProvider } from \"./github-provider\";\nimport { GoogleProvider } from \"./google-provider\";\nimport { LinkedInProvider } from \"./linkedin-provider\";\nimport { XProvider } from \"./x-provider\";\nimport { safeEqual } from \"../utils/safe-equal\";\nimport { randomUrlSafe, takeProviderState, writeProviderState } from \"./provider-state-cookie\";\nimport { resolveProviderUser } from \"./resolve-provider-user\";\n\n/** Providers auth ships, by name — each built from `auth.providers.<name>`. */\nconst BUILT_IN_PROVIDERS: Record<string, (name: string) => AuthProvider | undefined> = {\n google: () => {\n const google = authConfig.providers.google();\n\n return google ? new GoogleProvider(google) : undefined;\n },\n github: () => {\n const github = authConfig.providers.github();\n\n return github ? new GitHubProvider(github) : undefined;\n },\n discord: () => {\n const discord = authConfig.providers.discord();\n\n return discord ? new DiscordProvider(discord) : undefined;\n },\n linkedin: () => {\n const linkedin = authConfig.providers.linkedin();\n\n return linkedin ? new LinkedInProvider(linkedin) : undefined;\n },\n apple: () => {\n const apple = authConfig.providers.apple();\n\n return apple ? new AppleProvider(apple) : undefined;\n },\n facebook: () => {\n const facebook = authConfig.providers.facebook();\n\n return facebook ? new FacebookProvider(facebook) : undefined;\n },\n x: () => {\n const x = authConfig.providers.x();\n\n return x ? new XProvider(x) : undefined;\n },\n};\n\n/**\n * Resolve a provider by name: a built-in name (`google`, `github`, `discord`,\n * `linkedin`, `apple`, `facebook`, `x`) from `auth.providers.<name>`, anything\n * else from `auth.providers.custom`. Throws naming the config key when absent.\n */\nexport function resolveAuthProvider(name: string): AuthProvider {\n const isBuiltIn = Object.hasOwn(BUILT_IN_PROVIDERS, name);\n\n if (isBuiltIn) {\n const provider = BUILT_IN_PROVIDERS[name]!(name);\n\n if (provider) return provider;\n } else {\n const custom = authConfig.providers.custom(name);\n\n if (custom) return custom;\n }\n\n throw new Error(\n `@warlock.js/auth: no login provider \"${name}\" — configure \\`auth.providers.${\n isBuiltIn ? name : `custom.${name}`\n }\\`.`,\n );\n}\n\n/**\n * Start a redirect login: generate `state`, `nonce` and a PKCE verifier, store\n * them in a signed 10-minute cookie, and resolve the provider URL to redirect\n * the browser to.\n *\n * @example\n * // GET /auth/google\n * export const googleRedirect: RequestHandler = async (_request, response) =>\n * response.redirect(await startProviderLogin(response, \"google\"));\n */\nexport async function startProviderLogin(\n response: Response,\n providerName: string,\n): Promise<string> {\n const provider = resolveAuthProvider(providerName);\n\n const state = {\n state: randomUrlSafe(),\n nonce: randomUrlSafe(),\n codeVerifier: randomUrlSafe(),\n };\n\n const url = await provider.authorizationUrl(state);\n\n writeProviderState(response, provider.name, state, provider.callbackMode ?? \"query\");\n\n return url;\n}\n\n/**\n * Finish a redirect login on the provider's callback: consume the state\n * cookie, reject a missing/forged/expired cookie, a cookie from another\n * provider, a provider-reported error or a `state` mismatch; let the provider\n * verify the callback; find-or-link the user; then log them in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * @throws InvalidProviderCallbackError (400, EC009) for any callback rejection.\n * @throws ProviderEmailNotVerifiedError (403, EC010) for an unlinked, unverified email.\n * @throws AuthProviderSdkMissingError when the provider's SDK is not installed.\n *\n * @example\n * // GET /auth/google/callback\n * const { user, tokens } = await completeProviderLogin(User, \"google\", request, response);\n * authService.setAuthCookie(response, tokens.accessToken);\n */\nexport async function completeProviderLogin<T extends Auth>(\n Model: ChildModel<T>,\n providerName: string,\n request: Request,\n response: Response,\n deviceInfo?: DeviceInfo,\n): Promise<LoginResult<T>> {\n const provider = resolveAuthProvider(providerName);\n const expected = takeProviderState(request, response);\n\n if (!expected) {\n throw new InvalidProviderCallbackError(\"missing-or-invalid-state-cookie\");\n }\n\n if (expected.provider !== provider.name) {\n throw new InvalidProviderCallbackError(\"state-cookie-for-another-provider\");\n }\n\n const query: Record<string, unknown> = {\n code: request.input(\"code\"),\n state: request.input(\"state\"),\n error: request.input(\"error\"),\n // Apple's form_post callback carries the account name here, on the first authorization only.\n user: request.input(\"user\"),\n };\n\n if (query.error) {\n throw new InvalidProviderCallbackError(`provider-error:${String(query.error)}`);\n }\n\n if (typeof query.state !== \"string\" || !safeEqual(query.state, expected.state)) {\n throw new InvalidProviderCallbackError(\"state-mismatch\");\n }\n\n const profile = await provider.handleCallback({\n query,\n expected: { state: expected.state, nonce: expected.nonce, codeVerifier: expected.codeVerifier },\n });\n\n const user = await resolveProviderUser(Model, profile);\n\n return authService.completeLogin(user, deviceInfo);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAM,qBAAiF;CACrF,cAAc;EACZ,MAAM,SAAS,WAAW,UAAU,OAAO;EAE3C,OAAO,SAAS,IAAI,eAAe,MAAM,IAAI;CAC/C;CACA,cAAc;EACZ,MAAM,SAAS,WAAW,UAAU,OAAO;EAE3C,OAAO,SAAS,IAAI,eAAe,MAAM,IAAI;CAC/C;CACA,eAAe;EACb,MAAM,UAAU,WAAW,UAAU,QAAQ;EAE7C,OAAO,UAAU,IAAI,gBAAgB,OAAO,IAAI;CAClD;CACA,gBAAgB;EACd,MAAM,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BAA6B,mCAAmC;CAG5E,MAAM,QAAiC;EACrC,MAAM,QAAQ,MAAM,MAAM;EAC1B,OAAO,QAAQ,MAAM,OAAO;EAC5B,OAAO,QAAQ,MAAM,OAAO;EAE5B,MAAM,QAAQ,MAAM,MAAM;CAC5B;CAEA,IAAI,MAAM,OACR,MAAM,IAAI,6BAA6B,kBAAkB,OAAO,MAAM,KAAK,GAAG;CAGhF,IAAI,OAAO,MAAM,UAAU,YAAY,CAAC,UAAU,MAAM,OAAO,SAAS,KAAK,GAC3E,MAAM,IAAI,6BAA6B,gBAAgB;CAGzD,MAAM,UAAU,MAAM,SAAS,eAAe;EAC5C;EACA,UAAU;GAAE,OAAO,SAAS;GAAO,OAAO,SAAS;GAAO,cAAc,SAAS;EAAa;CAChG,CAAC;CAED,MAAM,OAAO,MAAM,oBAAoB,OAAO,OAAO;CAErD,OAAO,YAAY,cAAc,MAAM,UAAU;AACnD"}
1
+ {"version":3,"file":"provider-login.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/providers/provider-login.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport type { Request, Response } from \"@warlock.js/core\";\nimport type { AuthProvider } from \"../contracts/providers\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidProviderCallbackError } from \"../errors/invalid-provider-callback.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authService } from \"../services/auth.service\";\nimport { AppleProvider } from \"./apple-provider\";\nimport { DiscordProvider } from \"./discord-provider\";\nimport { FacebookProvider } from \"./facebook-provider\";\nimport { GitHubProvider } from \"./github-provider\";\nimport { GoogleProvider } from \"./google-provider\";\nimport { LinkedInProvider } from \"./linkedin-provider\";\nimport { XProvider } from \"./x-provider\";\nimport { safeEqual } from \"../utils/safe-equal\";\nimport { randomUrlSafe, takeProviderState, writeProviderState } from \"./provider-state-cookie\";\nimport { resolveProviderUser } from \"./resolve-provider-user\";\n\n/** Providers auth ships, by name — each built from `auth.providers.<name>`. */\nconst BUILT_IN_PROVIDERS: Record<string, (name: string) => AuthProvider | undefined> = {\n google: () => {\n const google = authConfig.providers.google();\n\n return google ? new GoogleProvider(google) : undefined;\n },\n github: () => {\n const github = authConfig.providers.github();\n\n return github ? new GitHubProvider(github) : undefined;\n },\n discord: () => {\n const discord = authConfig.providers.discord();\n\n return discord ? new DiscordProvider(discord) : undefined;\n },\n linkedin: () => {\n const linkedin = authConfig.providers.linkedin();\n\n return linkedin ? new LinkedInProvider(linkedin) : undefined;\n },\n apple: () => {\n const apple = authConfig.providers.apple();\n\n return apple ? new AppleProvider(apple) : undefined;\n },\n facebook: () => {\n const facebook = authConfig.providers.facebook();\n\n return facebook ? new FacebookProvider(facebook) : undefined;\n },\n x: () => {\n const x = authConfig.providers.x();\n\n return x ? new XProvider(x) : undefined;\n },\n};\n\n/**\n * Resolve a provider by name: a built-in name (`google`, `github`, `discord`,\n * `linkedin`, `apple`, `facebook`, `x`) from `auth.providers.<name>`, anything\n * else from `auth.providers.custom`. Throws naming the config key when absent.\n */\nexport function resolveAuthProvider(name: string): AuthProvider {\n const isBuiltIn = Object.hasOwn(BUILT_IN_PROVIDERS, name);\n\n if (isBuiltIn) {\n const provider = BUILT_IN_PROVIDERS[name]!(name);\n\n if (provider) return provider;\n } else {\n const custom = authConfig.providers.custom(name);\n\n if (custom) return custom;\n }\n\n throw new Error(\n `@warlock.js/auth: no login provider \"${name}\" — configure \\`auth.providers.${\n isBuiltIn ? name : `custom.${name}`\n }\\`.`,\n );\n}\n\n/**\n * Start a redirect login: generate `state`, `nonce` and a PKCE verifier, store\n * them in a signed 10-minute cookie, and resolve the provider URL to redirect\n * the browser to.\n *\n * @example\n * // GET /auth/google\n * export const googleRedirect: RequestHandler = async (_request, response) =>\n * response.redirect(await startProviderLogin(response, \"google\"));\n */\nexport async function startProviderLogin(\n response: Response,\n providerName: string,\n): Promise<string> {\n const provider = resolveAuthProvider(providerName);\n\n const state = {\n state: randomUrlSafe(),\n nonce: randomUrlSafe(),\n codeVerifier: randomUrlSafe(),\n };\n\n const url = await provider.authorizationUrl(state);\n\n writeProviderState(response, provider.name, state, provider.callbackMode ?? \"query\");\n\n return url;\n}\n\n/**\n * Finish a redirect login on the provider's callback: consume the state\n * cookie, reject a missing/forged/expired cookie, a cookie from another\n * provider, a provider-reported error or a `state` mismatch; let the provider\n * verify the callback; find-or-link the user; then log them in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * @throws InvalidProviderCallbackError (400, EC009) for any callback rejection.\n * @throws ProviderEmailNotVerifiedError (403, EC010) for an unlinked, unverified email.\n * @throws AuthProviderSdkMissingError when the provider's SDK is not installed.\n *\n * @example\n * // GET /auth/google/callback\n * const { user, tokens } = await completeProviderLogin(User, \"google\", request, response);\n * authService.setAuthCookie(response, tokens.accessToken);\n */\nexport async function completeProviderLogin<T extends Auth>(\n Model: ChildModel<T>,\n providerName: string,\n request: Request,\n response: Response,\n deviceInfo?: DeviceInfo,\n): Promise<LoginResult<T>> {\n const provider = resolveAuthProvider(providerName);\n const expected = takeProviderState(request, response);\n\n if (!expected) {\n throw new InvalidProviderCallbackError(\"missing-or-invalid-state-cookie\");\n }\n\n if (expected.provider !== provider.name) {\n throw new InvalidProviderCallbackError(\"state-cookie-for-another-provider\");\n }\n\n const query: Record<string, unknown> = {\n code: request.input(\"code\"),\n state: request.input(\"state\"),\n error: request.input(\"error\"),\n // Apple's form_post callback carries the account name here, on the first authorization only.\n user: request.input(\"user\"),\n };\n\n if (query.error) {\n throw new InvalidProviderCallbackError(`provider-error:${String(query.error)}`);\n }\n\n if (typeof query.state !== \"string\" || !safeEqual(query.state, expected.state)) {\n throw new InvalidProviderCallbackError(\"state-mismatch\");\n }\n\n const profile = await provider.handleCallback({\n query,\n expected: { state: expected.state, nonce: expected.nonce, codeVerifier: expected.codeVerifier },\n });\n\n const user = await resolveProviderUser(Model, profile);\n\n return authService.completeLogin(user, deviceInfo, { via: \"oauth\", request });\n}\n"],"mappings":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,MAAM,MAAM,MAAM,SAAS,iBAAiB,KAAK;CAEjD,mBAAmB,UAAU,SAAS,MAAM,OAAO,SAAS,gBAAgB,OAAO;CAEnF,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,eAAsB,sBACpB,OACA,cACA,SACA,UACA,YACyB;CACzB,MAAM,WAAW,oBAAoB,YAAY;CACjD,MAAM,WAAW,kBAAkB,SAAS,QAAQ;CAEpD,IAAI,CAAC,UACH,MAAM,IAAI,6BAA6B,iCAAiC;CAG1E,IAAI,SAAS,aAAa,SAAS,MACjC,MAAM,IAAI,6BAA6B,mCAAmC;CAG5E,MAAM,QAAiC;EACrC,MAAM,QAAQ,MAAM,MAAM;EAC1B,OAAO,QAAQ,MAAM,OAAO;EAC5B,OAAO,QAAQ,MAAM,OAAO;EAE5B,MAAM,QAAQ,MAAM,MAAM;CAC5B;CAEA,IAAI,MAAM,OACR,MAAM,IAAI,6BAA6B,kBAAkB,OAAO,MAAM,KAAK,GAAG;CAGhF,IAAI,OAAO,MAAM,UAAU,YAAY,CAAC,UAAU,MAAM,OAAO,SAAS,KAAK,GAC3E,MAAM,IAAI,6BAA6B,gBAAgB;CAGzD,MAAM,UAAU,MAAM,SAAS,eAAe;EAC5C;EACA,UAAU;GAAE,OAAO,SAAS;GAAO,OAAO,SAAS;GAAO,cAAc,SAAS;EAAa;CAChG,CAAC;CAED,MAAM,OAAO,MAAM,oBAAoB,OAAO,OAAO;CAErD,OAAO,YAAY,cAAc,MAAM,YAAY;EAAE,KAAK;EAAS;CAAQ,CAAC;AAC9E"}
@@ -118,8 +118,8 @@ function resolve(newKey, legacyKey, fallback) {
118
118
  * config and the legacy `auth.jwt.*` shape both resolve the same way.
119
119
  */
120
120
  const authConfig = {
121
- canAuthenticate: async (user) => {
122
- return config.key("auth.canAuthenticate", permitAuthentication)(user);
121
+ canAuthenticate: async (user, context) => {
122
+ return config.key("auth.canAuthenticate", permitAuthentication)(user, context);
123
123
  },
124
124
  /**
125
125
  * Store only a SHA-256 digest of each access and refresh token
@@ -1 +1 @@
1
- {"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport { type Algorithm } from \"fast-jwt\";\nimport ms from \"ms\";\nimport type {\n AuthNotification,\n CanAuthenticate,\n NormalizeCredentials,\n LogoutWithoutTokenBehavior,\n OneTimeTokenUrlBuilder,\n PasswordSetter,\n} from \"../contracts/types\";\nimport type {\n AppleProviderConfig,\n AuthProvider,\n DiscordProviderConfig,\n FacebookProviderConfig,\n GitHubProviderConfig,\n GoogleProviderConfig,\n LinkedInProviderConfig,\n OtpSender,\n PasskeysConfig,\n ProviderLinkExisting,\n ProviderUserCreator,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport type { Auth } from \"../models/auth.model\";\nimport { defaultNormalizeCredentials } from \"../utils/normalize-credentials\";\n\nconst warnedLegacyKeys = new Set<string>();\n\n/** One-time production warnings already logged, by key. */\nconst warnedProduction = new Set<string>();\n\n/** Signing secrets shorter than this are brute-forceable from one captured token. */\nconst MIN_SECRET_BYTES = 32;\n\n/** Access-token lifetimes past this get a production warning. */\nconst LONG_ACCESS_TOKEN_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Same answer as core's `environment()`, read directly so config stays dependency-light. */\nfunction isProduction(): boolean {\n return process.env.NODE_ENV === \"production\";\n}\n\n/** Log `message` once per process, in production only. */\nfunction warnOnceInProduction(key: string, message: string): void {\n if (!isProduction() || warnedProduction.has(key)) return;\n\n warnedProduction.add(key);\n log.warn(\"auth\", \"config\", message);\n}\n\n/** Log `message` once per process, in any environment. */\nfunction warnOnce(key: string, message: string): void {\n if (warnedProduction.has(key)) return;\n\n warnedProduction.add(key);\n log.warn(\"auth\", \"config\", message);\n}\n\n/** Warn (production, once) when a signing secret is too short to resist offline guessing. */\nfunction checkSecretStrength(key: string, secret: string): void {\n if (Buffer.byteLength(secret) >= MIN_SECRET_BYTES) return;\n\n warnOnceInProduction(\n `secret:${key}`,\n `auth.${key} is shorter than ${MIN_SECRET_BYTES} bytes, so a captured token lets an attacker ` +\n `guess it offline and forge tokens. Generate a strong secret with \"warlock jwt.generate\". ` +\n `From 6.0 a secret this short stops the app from booting.`,\n );\n}\n\n/**\n * Read a list of retired secrets: non-empty strings only. Each one gets the\n * same strength warning as an active secret.\n */\nfunction readPreviousSecrets(key: string): string[] {\n const raw = config.key<unknown>(`auth.${key}`);\n\n if (!Array.isArray(raw)) return [];\n\n const secrets = raw.filter((value): value is string => typeof value === \"string\" && value !== \"\");\n\n for (const secret of secrets) checkSecretStrength(key, secret);\n\n return secrets;\n}\n\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\n\n/**\n * `ms` accepts anything at runtime and answers `undefined` for a string it\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\n * `(value: ms.StringValue) => number`, which is exactly what let an\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\n * here, so every caller is forced to deal with the `undefined`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * Turn a configured lifetime into a positive number of milliseconds, or throw\n * naming the key.\n *\n * A token lifetime is a security boundary, so an unusable value is a hard error\n * rather than a silent fallback: substituting a default would trade one\n * unintended lifetime for another, just as quietly — and quiet is the whole\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\n *\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\n * claim** and an `Invalid Date` written to the token row.\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\n * emits with **no `exp` claim** — it survives any guard that only rejects\n * `undefined`. `\"-1h\"` signs an already-expired token.\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\n */\nfunction parseDuration(key: string, raw: unknown): number {\n let parsed: number | string | undefined;\n\n try {\n parsed = parseMs(raw);\n } catch {\n // ms throws (rather than returning undefined) for \"\" and non-strings\n parsed = undefined;\n }\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\n );\n }\n\n return parsed;\n}\n\n/** Email-verification token lifetime used when nothing is configured. */\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\n\n/** Password-reset token lifetime used when nothing is configured. */\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\n\n/** Passkey challenge lifetime used when nothing is configured. */\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\n\n/** OTP lifetime used when nothing is configured. */\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\n\n/** Access-token lifetime used when nothing is configured. */\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\n\n/**\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\n *\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\n * keep working after the config split.\n */\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\n const fromNew = config.key(`auth.${newKey}`);\n\n if (fromNew !== undefined && fromNew !== null) {\n return fromNew as T;\n }\n\n const fromLegacy = config.key(`auth.${legacyKey}`);\n\n if (fromLegacy !== undefined && fromLegacy !== null) {\n if (!warnedLegacyKeys.has(legacyKey)) {\n warnedLegacyKeys.add(legacyKey);\n log.warn(\n \"auth\",\n \"config-deprecation\",\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\n );\n }\n\n return fromLegacy as T;\n }\n\n return fallback as T;\n}\n\n/**\n * Typed, backward-compatible access to auth configuration. The service and the\n * jwt signer read configuration exclusively through here, so the new split\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\n */\nexport const authConfig = {\n canAuthenticate: async (user: Auth): Promise<boolean> => {\n const canAuthenticate = config.key<CanAuthenticate>(\n \"auth.canAuthenticate\",\n permitAuthentication,\n );\n\n return canAuthenticate(user);\n },\n /**\n * Store only a SHA-256 digest of each access and refresh token\n * (`auth.hashTokensAtRest`). @default false\n */\n hashTokensAtRest: (): boolean => config.key<boolean>(\"auth.hashTokensAtRest\", false) === true,\n /**\n * Replace a password hash made with another algorithm or cost than\n * `encryption.password` asks for, after a successful login\n * (`auth.rehashPasswords`). @default true\n */\n rehashPasswords: (): boolean => config.key<boolean>(\"auth.rehashPasswords\", true) !== false,\n /** Login identifier normalizer, or `false` for exact matching. */\n normalizeCredentials: (): false | NormalizeCredentials =>\n config.key<false | NormalizeCredentials>(\n \"auth.normalizeCredentials\",\n defaultNormalizeCredentials,\n ),\n accessToken: {\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\n secret: (): string => {\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\n\n if (!secret) {\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\n }\n\n checkSecretStrength(\"accessToken.secret\", secret);\n\n return secret;\n },\n /**\n * Retired signing secrets, tried only when verifying an access token whose\n * signature the current secret rejects. Never used to sign.\n */\n previousSecrets: (): string[] => readPreviousSecrets(\"accessToken.previousSecrets\"),\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\n /** `iss` claim stamped on and required of every token; unset ⇒ not used. */\n issuer: (): string | undefined => {\n const issuer = config.key<unknown>(\"auth.accessToken.issuer\");\n\n return typeof issuer === \"string\" && issuer.length > 0 ? issuer : undefined;\n },\n /** `aud` claim stamped on and required of every token; unset ⇒ not used. */\n audience: (): string | string[] | undefined => {\n const audience = config.key<unknown>(\"auth.accessToken.audience\");\n\n if (typeof audience === \"string\" && audience.length > 0) return audience;\n\n if (\n Array.isArray(audience) &&\n audience.length > 0 &&\n audience.every((entry) => typeof entry === \"string\" && entry.length > 0)\n ) {\n return audience as string[];\n }\n\n return undefined;\n },\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\n * to 1 hour when unset; throws naming the key when the configured value is\n * not a positive `ms` duration. See {@link parseDuration}.\n */\n expiresInMs: (): number => {\n const lifetime = parseDuration(\n \"accessToken.expiresIn\",\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\n );\n\n if (lifetime > LONG_ACCESS_TOKEN_MS) {\n warnOnceInProduction(\n \"accessToken.expiresIn\",\n \"auth.accessToken.expiresIn is longer than 30 days: a stolen access token stays usable \" +\n 'that long. Use a short lifetime (e.g. \"1h\") with refresh tokens ' +\n \"(auth.refreshToken.enabled) instead.\",\n );\n }\n\n return lifetime;\n },\n },\n pageAuth: {\n /**\n * Login path a guarded PAGE route redirects a logged-out browser to.\n *\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\n * to opt a browser-facing app into login-redirect UX: a logged-out human\n * navigating to a guarded page lands on the login screen instead of reading\n * a raw JSON error blob. Finding b9ab9804.\n */\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed. Defaults to\n * `\"returnUrl\"`.\n */\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\n },\n cookie: {\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\n /** Select the request-scoped cookie Domain; undefined keeps it host-only. */\n cookieDomain: (): CookieDomainResolver | undefined => config.key(\"auth.cookie.cookieDomain\"),\n /** Write the auth cookies as `__Host-<name>` (Secure, `Path=/`, no Domain). @default false */\n hostPrefix: (): boolean => config.key<boolean>(\"auth.cookie.hostPrefix\", false) === true,\n },\n csrf: {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * beyond the request's own origin. @default []\n */\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\n },\n verification: {\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\n expiresInMs: (): number =>\n parseDuration(\n \"verification.expiresIn\",\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\n ),\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\n /** App notification replacing the default verification email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\n },\n passwordReset: {\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\n expiresInMs: (): number =>\n parseDuration(\n \"passwordReset.expiresIn\",\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\n ),\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\n /** App notification replacing the default reset email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\n /** App-owned password writer replacing the default. */\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\n /** Wait for the reset notification before `requestPasswordReset` resolves. @default false */\n awaitDelivery: (): boolean =>\n config.key<boolean>(\"auth.passwordReset.awaitDelivery\", false) === true,\n },\n providers: {\n /** `auth.providers.google`, when configured. */\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\n /** `auth.providers.github`, when configured. */\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\n /** `auth.providers.discord`, when configured. */\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\n /** `auth.providers.linkedin`, when configured. */\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\n /** `auth.providers.apple`, when configured. */\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\n /** `auth.providers.facebook`, when configured. */\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\n /** `auth.providers.x`, when configured. */\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\n /** An app-registered provider under `auth.providers.custom.<name>`. */\n custom: (name: string): AuthProvider | undefined => {\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\n\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\n },\n /** User attribute a verified provider email is matched against. @default \"email\" */\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\n /** App-owned user creation for a first provider login. */\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\n /** Linking a first provider login to an existing account by email. @default \"verified\" */\n linkExisting: (): ProviderLinkExisting => {\n const value = config.key<unknown>(\"auth.providers.linkExisting\", \"verified\");\n\n return value === \"always\" || value === \"never\" ? value : \"verified\";\n },\n },\n passkeys: {\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\n settings: (): PasskeysConfig => {\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\n\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\n throw new Error(\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\n );\n }\n\n return settings;\n },\n /** Allowed ceremony origins, as a list. */\n origins: (): string[] => {\n const { origin } = authConfig.passkeys.settings();\n\n return Array.isArray(origin) ? origin : [origin];\n },\n /** User-verification requirement for both ceremonies. @default \"preferred\" (becomes \"required\" in 6.0) */\n userVerification: (): \"required\" | \"preferred\" => {\n const configured = config.key<PasskeysConfig | undefined>(\"auth.passkeys\")?.userVerification;\n\n if (configured === undefined) {\n warnOnce(\n \"passkeys.userVerification\",\n 'auth.passkeys.userVerification is not set, so \"preferred\" applies: a passkey proving only possession of the device is accepted. The default changes to \"required\" in 6.0: set it explicitly to choose now.',\n );\n }\n\n return configured === \"required\" ? \"required\" : \"preferred\";\n },\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n challengeExpiresInMs: (): number =>\n parseDuration(\n \"passkeys.challengeExpiresIn\",\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\n ),\n },\n otp: {\n /** Notifications channel the code is sent through. @default \"sms\" */\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\n /** User attribute holding the phone number. @default \"phone\" */\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n expiresInMs: (): number =>\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\n /** Verify attempts before the code is invalidated. @default 5 */\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\n /** The message text for a code. */\n message: (code: string): string => {\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\n\n return build ? build(code) : `Your verification code is ${code}`;\n },\n /** App-owned delivery replacing the notifications channel send. */\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\n /** Wait for the code delivery before `requestOtp` resolves. @default false */\n awaitDelivery: (): boolean => config.key<boolean>(\"auth.otp.awaitDelivery\", false) === true,\n },\n refreshToken: {\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\n secret: (): string | undefined => {\n const secret = resolve<string | undefined>(\"refreshToken.secret\", \"jwt.refresh.secret\");\n\n if (secret) checkSecretStrength(\"refreshToken.secret\", secret);\n\n return secret;\n },\n /**\n * Retired refresh secrets, tried only when verifying a refresh token whose\n * signature the current secret rejects. Never used to sign.\n */\n previousSecrets: (): string[] => readPreviousSecrets(\"refreshToken.previousSecrets\"),\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\n * naming the key when the configured value is not a positive `ms` duration.\n */\n expiresInMs: (): number =>\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\n logoutWithoutToken: (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E3D,kBAA0B,OAAO,IAAI,uBAAuB,OAAO;;EAEnE,mBACE,cAAc,iBAAiB,OAAO,IAAI,sBAAsB,sBAAsB,CAAC;;EAEzF,mBAA2B,OAAO,IAAI,wBAAwB,CAAC;;EAE/D,UAAU,SAAyB;GACjC,MAAM,QAAQ,OAAO,IAA4C,kBAAkB;GAEnF,OAAO,QAAQ,MAAM,IAAI,IAAI,6BAA6B;EAC5D;;EAEA,YAAmC,OAAO,IAAI,eAAe;;EAE7D,qBAA8B,OAAO,IAAa,0BAA0B,KAAK,MAAM;CACzF;CACA,cAAc;;EAEZ,cAAkC;GAChC,MAAM,SAAS,QAA4B,uBAAuB,oBAAoB;GAEtF,IAAI,QAAQ,oBAAoB,uBAAuB,MAAM;GAE7D,OAAO;EACT;;;;;EAKA,uBAAiC,oBAAoB,8BAA8B;;EAEnF,eAAwB,QAAQ,wBAAwB,uBAAuB,IAAI;;EAEnF,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
1
+ {"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport { type Algorithm } from \"fast-jwt\";\nimport ms from \"ms\";\nimport type {\n AuthenticationContext,\n AuthNotification,\n CanAuthenticate,\n NormalizeCredentials,\n LogoutWithoutTokenBehavior,\n OneTimeTokenUrlBuilder,\n PasswordSetter,\n} from \"../contracts/types\";\nimport type {\n AppleProviderConfig,\n AuthProvider,\n DiscordProviderConfig,\n FacebookProviderConfig,\n GitHubProviderConfig,\n GoogleProviderConfig,\n LinkedInProviderConfig,\n OtpSender,\n PasskeysConfig,\n ProviderLinkExisting,\n ProviderUserCreator,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport type { Auth } from \"../models/auth.model\";\nimport { defaultNormalizeCredentials } from \"../utils/normalize-credentials\";\n\nconst warnedLegacyKeys = new Set<string>();\n\n/** One-time production warnings already logged, by key. */\nconst warnedProduction = new Set<string>();\n\n/** Signing secrets shorter than this are brute-forceable from one captured token. */\nconst MIN_SECRET_BYTES = 32;\n\n/** Access-token lifetimes past this get a production warning. */\nconst LONG_ACCESS_TOKEN_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Same answer as core's `environment()`, read directly so config stays dependency-light. */\nfunction isProduction(): boolean {\n return process.env.NODE_ENV === \"production\";\n}\n\n/** Log `message` once per process, in production only. */\nfunction warnOnceInProduction(key: string, message: string): void {\n if (!isProduction() || warnedProduction.has(key)) return;\n\n warnedProduction.add(key);\n log.warn(\"auth\", \"config\", message);\n}\n\n/** Log `message` once per process, in any environment. */\nfunction warnOnce(key: string, message: string): void {\n if (warnedProduction.has(key)) return;\n\n warnedProduction.add(key);\n log.warn(\"auth\", \"config\", message);\n}\n\n/** Warn (production, once) when a signing secret is too short to resist offline guessing. */\nfunction checkSecretStrength(key: string, secret: string): void {\n if (Buffer.byteLength(secret) >= MIN_SECRET_BYTES) return;\n\n warnOnceInProduction(\n `secret:${key}`,\n `auth.${key} is shorter than ${MIN_SECRET_BYTES} bytes, so a captured token lets an attacker ` +\n `guess it offline and forge tokens. Generate a strong secret with \"warlock jwt.generate\". ` +\n `From 6.0 a secret this short stops the app from booting.`,\n );\n}\n\n/**\n * Read a list of retired secrets: non-empty strings only. Each one gets the\n * same strength warning as an active secret.\n */\nfunction readPreviousSecrets(key: string): string[] {\n const raw = config.key<unknown>(`auth.${key}`);\n\n if (!Array.isArray(raw)) return [];\n\n const secrets = raw.filter((value): value is string => typeof value === \"string\" && value !== \"\");\n\n for (const secret of secrets) checkSecretStrength(key, secret);\n\n return secrets;\n}\n\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\n\n/**\n * `ms` accepts anything at runtime and answers `undefined` for a string it\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\n * `(value: ms.StringValue) => number`, which is exactly what let an\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\n * here, so every caller is forced to deal with the `undefined`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * Turn a configured lifetime into a positive number of milliseconds, or throw\n * naming the key.\n *\n * A token lifetime is a security boundary, so an unusable value is a hard error\n * rather than a silent fallback: substituting a default would trade one\n * unintended lifetime for another, just as quietly — and quiet is the whole\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\n *\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\n * claim** and an `Invalid Date` written to the token row.\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\n * emits with **no `exp` claim** — it survives any guard that only rejects\n * `undefined`. `\"-1h\"` signs an already-expired token.\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\n */\nfunction parseDuration(key: string, raw: unknown): number {\n let parsed: number | string | undefined;\n\n try {\n parsed = parseMs(raw);\n } catch {\n // ms throws (rather than returning undefined) for \"\" and non-strings\n parsed = undefined;\n }\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\n );\n }\n\n return parsed;\n}\n\n/** Email-verification token lifetime used when nothing is configured. */\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\n\n/** Password-reset token lifetime used when nothing is configured. */\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\n\n/** Passkey challenge lifetime used when nothing is configured. */\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\n\n/** OTP lifetime used when nothing is configured. */\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\n\n/** Access-token lifetime used when nothing is configured. */\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\n\n/**\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\n *\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\n * keep working after the config split.\n */\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\n const fromNew = config.key(`auth.${newKey}`);\n\n if (fromNew !== undefined && fromNew !== null) {\n return fromNew as T;\n }\n\n const fromLegacy = config.key(`auth.${legacyKey}`);\n\n if (fromLegacy !== undefined && fromLegacy !== null) {\n if (!warnedLegacyKeys.has(legacyKey)) {\n warnedLegacyKeys.add(legacyKey);\n log.warn(\n \"auth\",\n \"config-deprecation\",\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\n );\n }\n\n return fromLegacy as T;\n }\n\n return fallback as T;\n}\n\n/**\n * Typed, backward-compatible access to auth configuration. The service and the\n * jwt signer read configuration exclusively through here, so the new split\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\n */\nexport const authConfig = {\n canAuthenticate: async (user: Auth, context?: AuthenticationContext): Promise<boolean> => {\n const canAuthenticate = config.key<CanAuthenticate>(\n \"auth.canAuthenticate\",\n permitAuthentication,\n );\n\n return canAuthenticate(user, context);\n },\n /**\n * Store only a SHA-256 digest of each access and refresh token\n * (`auth.hashTokensAtRest`). @default false\n */\n hashTokensAtRest: (): boolean => config.key<boolean>(\"auth.hashTokensAtRest\", false) === true,\n /**\n * Replace a password hash made with another algorithm or cost than\n * `encryption.password` asks for, after a successful login\n * (`auth.rehashPasswords`). @default true\n */\n rehashPasswords: (): boolean => config.key<boolean>(\"auth.rehashPasswords\", true) !== false,\n /** Login identifier normalizer, or `false` for exact matching. */\n normalizeCredentials: (): false | NormalizeCredentials =>\n config.key<false | NormalizeCredentials>(\n \"auth.normalizeCredentials\",\n defaultNormalizeCredentials,\n ),\n accessToken: {\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\n secret: (): string => {\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\n\n if (!secret) {\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\n }\n\n checkSecretStrength(\"accessToken.secret\", secret);\n\n return secret;\n },\n /**\n * Retired signing secrets, tried only when verifying an access token whose\n * signature the current secret rejects. Never used to sign.\n */\n previousSecrets: (): string[] => readPreviousSecrets(\"accessToken.previousSecrets\"),\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\n /** `iss` claim stamped on and required of every token; unset ⇒ not used. */\n issuer: (): string | undefined => {\n const issuer = config.key<unknown>(\"auth.accessToken.issuer\");\n\n return typeof issuer === \"string\" && issuer.length > 0 ? issuer : undefined;\n },\n /** `aud` claim stamped on and required of every token; unset ⇒ not used. */\n audience: (): string | string[] | undefined => {\n const audience = config.key<unknown>(\"auth.accessToken.audience\");\n\n if (typeof audience === \"string\" && audience.length > 0) return audience;\n\n if (\n Array.isArray(audience) &&\n audience.length > 0 &&\n audience.every((entry) => typeof entry === \"string\" && entry.length > 0)\n ) {\n return audience as string[];\n }\n\n return undefined;\n },\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\n * to 1 hour when unset; throws naming the key when the configured value is\n * not a positive `ms` duration. See {@link parseDuration}.\n */\n expiresInMs: (): number => {\n const lifetime = parseDuration(\n \"accessToken.expiresIn\",\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\n );\n\n if (lifetime > LONG_ACCESS_TOKEN_MS) {\n warnOnceInProduction(\n \"accessToken.expiresIn\",\n \"auth.accessToken.expiresIn is longer than 30 days: a stolen access token stays usable \" +\n 'that long. Use a short lifetime (e.g. \"1h\") with refresh tokens ' +\n \"(auth.refreshToken.enabled) instead.\",\n );\n }\n\n return lifetime;\n },\n },\n pageAuth: {\n /**\n * Login path a guarded PAGE route redirects a logged-out browser to.\n *\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\n * to opt a browser-facing app into login-redirect UX: a logged-out human\n * navigating to a guarded page lands on the login screen instead of reading\n * a raw JSON error blob. Finding b9ab9804.\n */\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed. Defaults to\n * `\"returnUrl\"`.\n */\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\n },\n cookie: {\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\n /** Select the request-scoped cookie Domain; undefined keeps it host-only. */\n cookieDomain: (): CookieDomainResolver | undefined => config.key(\"auth.cookie.cookieDomain\"),\n /** Write the auth cookies as `__Host-<name>` (Secure, `Path=/`, no Domain). @default false */\n hostPrefix: (): boolean => config.key<boolean>(\"auth.cookie.hostPrefix\", false) === true,\n },\n csrf: {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * beyond the request's own origin. @default []\n */\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\n },\n verification: {\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\n expiresInMs: (): number =>\n parseDuration(\n \"verification.expiresIn\",\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\n ),\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\n /** App notification replacing the default verification email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\n },\n passwordReset: {\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\n expiresInMs: (): number =>\n parseDuration(\n \"passwordReset.expiresIn\",\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\n ),\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\n /** App notification replacing the default reset email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\n /** App-owned password writer replacing the default. */\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\n /** Wait for the reset notification before `requestPasswordReset` resolves. @default false */\n awaitDelivery: (): boolean =>\n config.key<boolean>(\"auth.passwordReset.awaitDelivery\", false) === true,\n },\n providers: {\n /** `auth.providers.google`, when configured. */\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\n /** `auth.providers.github`, when configured. */\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\n /** `auth.providers.discord`, when configured. */\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\n /** `auth.providers.linkedin`, when configured. */\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\n /** `auth.providers.apple`, when configured. */\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\n /** `auth.providers.facebook`, when configured. */\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\n /** `auth.providers.x`, when configured. */\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\n /** An app-registered provider under `auth.providers.custom.<name>`. */\n custom: (name: string): AuthProvider | undefined => {\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\n\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\n },\n /** User attribute a verified provider email is matched against. @default \"email\" */\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\n /** App-owned user creation for a first provider login. */\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\n /** Linking a first provider login to an existing account by email. @default \"verified\" */\n linkExisting: (): ProviderLinkExisting => {\n const value = config.key<unknown>(\"auth.providers.linkExisting\", \"verified\");\n\n return value === \"always\" || value === \"never\" ? value : \"verified\";\n },\n },\n passkeys: {\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\n settings: (): PasskeysConfig => {\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\n\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\n throw new Error(\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\n );\n }\n\n return settings;\n },\n /** Allowed ceremony origins, as a list. */\n origins: (): string[] => {\n const { origin } = authConfig.passkeys.settings();\n\n return Array.isArray(origin) ? origin : [origin];\n },\n /** User-verification requirement for both ceremonies. @default \"preferred\" (becomes \"required\" in 6.0) */\n userVerification: (): \"required\" | \"preferred\" => {\n const configured = config.key<PasskeysConfig | undefined>(\"auth.passkeys\")?.userVerification;\n\n if (configured === undefined) {\n warnOnce(\n \"passkeys.userVerification\",\n 'auth.passkeys.userVerification is not set, so \"preferred\" applies: a passkey proving only possession of the device is accepted. The default changes to \"required\" in 6.0: set it explicitly to choose now.',\n );\n }\n\n return configured === \"required\" ? \"required\" : \"preferred\";\n },\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n challengeExpiresInMs: (): number =>\n parseDuration(\n \"passkeys.challengeExpiresIn\",\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\n ),\n },\n otp: {\n /** Notifications channel the code is sent through. @default \"sms\" */\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\n /** User attribute holding the phone number. @default \"phone\" */\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n expiresInMs: (): number =>\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\n /** Verify attempts before the code is invalidated. @default 5 */\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\n /** The message text for a code. */\n message: (code: string): string => {\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\n\n return build ? build(code) : `Your verification code is ${code}`;\n },\n /** App-owned delivery replacing the notifications channel send. */\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\n /** Wait for the code delivery before `requestOtp` resolves. @default false */\n awaitDelivery: (): boolean => config.key<boolean>(\"auth.otp.awaitDelivery\", false) === true,\n },\n refreshToken: {\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\n secret: (): string | undefined => {\n const secret = resolve<string | undefined>(\"refreshToken.secret\", \"jwt.refresh.secret\");\n\n if (secret) checkSecretStrength(\"refreshToken.secret\", secret);\n\n return secret;\n },\n /**\n * Retired refresh secrets, tried only when verifying a refresh token whose\n * signature the current secret rejects. Never used to sign.\n */\n previousSecrets: (): string[] => readPreviousSecrets(\"refreshToken.previousSecrets\"),\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\n * naming the key when the configured value is not a positive `ms` duration.\n */\n expiresInMs: (): number =>\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\n },\n};\n"],"mappings":";;;;;;AA+BA,MAAM,mCAAmB,IAAI,IAAY;;AAGzC,MAAM,mCAAmB,IAAI,IAAY;;AAGzC,MAAM,mBAAmB;;AAGzB,MAAM,uBAAuB;;AAG7B,SAAS,eAAwB;CAC/B,OAAO,QAAQ,IAAI,aAAa;AAClC;;AAGA,SAAS,qBAAqB,KAAa,SAAuB;CAChE,IAAI,CAAC,aAAa,KAAK,iBAAiB,IAAI,GAAG,GAAG;CAElD,iBAAiB,IAAI,GAAG;CACxB,I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uBAAuB,oBAAoB;GAEtF,IAAI,QAAQ,oBAAoB,uBAAuB,MAAM;GAE7D,OAAO;EACT;;;;;EAKA,uBAAiC,oBAAoB,8BAA8B;;EAEnF,eAAwB,QAAQ,wBAAwB,uBAAuB,IAAI;;EAEnF,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
@@ -2,7 +2,7 @@ import { Auth } from "../models/auth.model.mjs";
2
2
  import { AccessToken } from "../models/access-token/access-token.model.mjs";
3
3
  import "../models/access-token/index.mjs";
4
4
  import "../models/refresh-token/index.mjs";
5
- import { AccessTokenOutput, AuthCredentials, ClearAuthCookieOptions, DeviceInfo, LoginResult, SetAuthCookieOptions, TokenPair } from "../contracts/types.mjs";
5
+ import { AccessTokenOutput, AuthCredentials, AuthenticationContext, ClearAuthCookieOptions, CredentialsVerification, DeviceInfo, LoginResult, SetAuthCookieOptions, TokenPair } from "../contracts/types.mjs";
6
6
  import { RefreshToken } from "../models/refresh-token/refresh-token.model.mjs";
7
7
  import { Request, Response } from "@warlock.js/core";
8
8
  import { ChildModel } from "@warlock.js/cascade";
@@ -31,8 +31,12 @@ declare class AuthService {
31
31
  * Build the default access-token JWT payload from a user.
32
32
  */
33
33
  buildAccessTokenPayload(user: Auth): Record<string, unknown>;
34
- /** One policy seam keeps account-state checks identical across all auth paths. */
35
- canAuthenticate(user: Auth): Promise<boolean>;
34
+ /**
35
+ * One policy seam keeps account-state checks identical across all auth paths.
36
+ * `context` tells the `auth.canAuthenticate` policy how the user is
37
+ * authenticating (`via`) and, when the call site has one, the request.
38
+ */
39
+ canAuthenticate(user: Auth, context?: AuthenticationContext): Promise<boolean>;
36
40
  private assertCanAuthenticate;
37
41
  private issueAccessToken;
38
42
  /**
@@ -74,6 +78,8 @@ declare class AuthService {
74
78
  overlapMs?: number;
75
79
  deviceInfo?: DeviceInfo;
76
80
  maxAgeMs?: number;
81
+ /** The request being renewed, passed to the `auth.canAuthenticate` policy. */
82
+ request?: Request;
77
83
  }): Promise<TokenPair | null>;
78
84
  /**
79
85
  * Whether the family's first issue is older than `maxAgeMs`. The start is the
@@ -108,11 +114,27 @@ declare class AuthService {
108
114
  * (trimmed) when that differs, so legacy rows stored with capitals still match.
109
115
  */
110
116
  private findLoginUser;
117
+ /**
118
+ * Check credentials and report WHY they failed, without emitting events or
119
+ * touching the stored hash:
120
+ *
121
+ * - `{ type: "ok", user }`: the account exists, the password is right and
122
+ * `auth.canAuthenticate` allows it.
123
+ * - `{ type: "invalid" }`: unknown account or wrong password (both take the
124
+ * same time, so the answer does not reveal which).
125
+ * - `{ type: "refused", user }`: the password is right but
126
+ * `auth.canAuthenticate` refuses the account (suspended, not yet approved).
127
+ * Reveal this only after the correct password, as here.
128
+ */
129
+ verifyCredentials<T extends Auth>(Model: ChildModel<T>, credentials: AuthCredentials, request?: Request): Promise<CredentialsVerification<T>>;
130
+ /** The shared check: `verifyCredentials` plus the reason `attemptLogin` reports in its event. */
131
+ private checkCredentials;
111
132
  /**
112
133
  * Resolve a user by credentials, verifying the password. Returns `null` on a
113
- * missing user or a wrong password, emitting `login.failed` either way.
134
+ * missing user, a wrong password or a refused account, emitting
135
+ * `login.failed` either way. Use {@link verifyCredentials} to tell them apart.
114
136
  */
115
- attemptLogin<T extends Auth>(Model: ChildModel<T>, data: AuthCredentials): Promise<T | null>;
137
+ attemptLogin<T extends Auth>(Model: ChildModel<T>, data: AuthCredentials, request?: Request): Promise<T | null>;
116
138
  /**
117
139
  * After a successful password check, replace a hash that no longer matches
118
140
  * the configured algorithm or cost (`auth.rehashPasswords`, default on) with
@@ -124,7 +146,7 @@ declare class AuthService {
124
146
  * Full login flow: validate credentials, issue tokens, emit events. Returns
125
147
  * the user + token pair on success, `null` on failure.
126
148
  */
127
- login<T extends Auth>(Model: ChildModel<T>, credentials: AuthCredentials, deviceInfo?: DeviceInfo): Promise<LoginResult<T> | null>;
149
+ login<T extends Auth>(Model: ChildModel<T>, credentials: AuthCredentials, deviceInfo?: DeviceInfo, request?: Request): Promise<LoginResult<T> | null>;
128
150
  /**
129
151
  * Log in a user some OTHER method already authenticated — a provider
130
152
  * callback, a passkey assertion, a one-time code. Applies the
@@ -132,9 +154,12 @@ declare class AuthService {
132
154
  * what {@link login} produces: the same tokens, rows and events. Pair with
133
155
  * {@link setAuthCookie} for a cookie session, as with password login.
134
156
  *
157
+ * `context` is passed to the policy: `via` names the login method (default
158
+ * `"custom"`) and `request` is the request being served, when there is one.
159
+ *
135
160
  * Never call this for a user you have not authenticated.
136
161
  */
137
- completeLogin<T extends Auth>(user: T, deviceInfo?: DeviceInfo): Promise<LoginResult<T>>;
162
+ completeLogin<T extends Auth>(user: T, deviceInfo?: DeviceInfo, context?: Partial<AuthenticationContext>): Promise<LoginResult<T>>;
138
163
  /**
139
164
  * Cookie login for a browser: same-origin check, credential login, then both
140
165
  * session cookies. Unlike the default CSRF guard, the Origin/Referer check
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth.service.ts"],"mappings":";;;;;;;;;;qBAoDa,yCAAyC;EACpD,YAAmB;;cAyEf;;;;;;;cAOQ;;;;cAOA;;;;cAOA;;;;EAOL,wBAAwB,MAAM,OAAO;;EAS/B,gBAAgB,MAAM,OAAO;UAI5B;UAMA;;;;;;EAiCD,oBACX,MAAM,MACN,UAAU,0BACT,QAAQ;UAMG;;;;;;;UAkDA;;;;;EAgCD,mBACX,MAAM,MACN,aAAa,aACZ,QAAQ;UAcG;;;;EAqDD,gBAAgB,MAAM,MAAM,aAAa,aAAa,QAAQ;;;;;;EAiB9D,cACX,4BACA,aAAa,aACZ,QAAQ;;;;;;EA0FE,sBACX,4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E;IAAU,aAAa;IAAmB,cAAc;KACxD,UAAU;;;;;EA8BL,oBACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,UAAU;;qBAuBD,aAAW"}
1
+ {"version":3,"file":"auth.service.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth.service.ts"],"mappings":";;;;;;;;;;qBAsDa,yCAAyC;EACpD,YAAmB;;cAyEf;;;;;;;cAOQ;;;;cAOA;;;;cAOA;;;;EAOL,wBAAwB,MAAM,OAAO;;;;;;EAa/B,gBAAgB,MAAM,MAAM,UAAU,wBAAwB;UAI7D;UAMA;;;;;;EA2CD,oBACX,MAAM,MACN,UAAU,0BACT,QAAQ;UAMG;;;;;;;UAkDA;;;;;EAgCD,mBACX,MAAM,MACN,aAAa,aACZ,QAAQ;UAcG;;;;EAqDD,gBAAgB,MAAM,MAAM,aAAa,aAAa,QAAQ;;;;;;EAiB9D,cACX,4BACA,aAAa,aACZ,QAAQ;;;;;;EA0FE,sBACX,4BACA,0BACA;IACE;IACA,aAAa;IACb;;IAEA,UAAU;MAEX,QAAQ;;;;;;UAoHG;UAsBN;UAMA;UAWA;UAMA;UAOM;;;;;;;UA4DA;UAmBA;;;;EAaD,eAAe,uBAAuB,yBAAyB;;;;EAO/D,aAAa,mBAAmB;;;;;;UAS/B;;;;;;;;;;;;;EAkCD,kBAAkB,UAAU,MACvC,OAAO,WAAW,IAClB,aAAa,iBACb,UAAU,UACT,QAAQ,wBAAwB;;UAOrB;;;;;;EAoCD,aAAa,UAAU,MAClC,OAAO,WAAW,IAClB,MAAM,iBACN,UAAU,UACT,QAAQ;;;;;;;UAiCG;;;;;EAqBD,MAAM,UAAU,MAC3B,OAAO,WAAW,IAClB,aAAa,iBACb,aAAa,YACb,UAAU,UACT,QAAQ,YAAY;;;;;;;;;;;;;EAsBV,cAAc,UAAU,MACnC,MAAM,GACN,aAAa,YACb,UAAU,QAAQ,yBACjB,QAAQ,YAAY;;;;;;;;EAaV,wBAAwB,UAAU,MAC7C,SAAS,SACT,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,OAAO,WAAW,IAClB,aAAa,iBACb,aAAa,aACZ,QAAQ,YAAY;;UA0BT;;;;;;;;;;;EA2BD,OAAO,MAAM,MAAM,sBAAsB,wBAAwB;;;;EA6BjE,kBAAkB,MAAM,MAAM,gBAAgB;;;;EAO9C,sBAAsB,MAAM,OAAO;;;;EAOnC,mBAAmB,MAAM,MAAM,gBAAgB;;;;;;;;EAW/C,gBAAgB,MAAM,OAAO;;;;EAqD7B,kBAAkB,mBAAmB;;;;;;;EAyErC,wBAAwB;;;;;;;;;;;EAyBxB,2BAA2B;IACtC,cAAc;IACd,eAAe;;;;;;;;;;EAgBJ,4BAA4B;IACvC;IACA;;;;;EAkBW,kBAAkB,MAAM,OAAO,QAAQ;;;;;;UAS5C;UAUA;;;;;;;;;;;;;;;;;;;;;;EAmCD,cACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,gBAAgB,mBAChB,UAAS;;;;;;;;;;;EA6BJ,gBACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,UAAS,wBACT,UAAU;;;;;;;;;;;;EA8BL,kBACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E;IAAU,aAAa;IAAmB,cAAc;KACxD,UAAU;;;;;EA8BL,oBACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,UAAU;;qBAuBD,aAAW"}
@@ -109,16 +109,21 @@ var AuthService = class {
109
109
  created_at: Date.now()
110
110
  };
111
111
  }
112
- /** One policy seam keeps account-state checks identical across all auth paths. */
113
- async canAuthenticate(user) {
114
- return authConfig.canAuthenticate(user);
112
+ /**
113
+ * One policy seam keeps account-state checks identical across all auth paths.
114
+ * `context` tells the `auth.canAuthenticate` policy how the user is
115
+ * authenticating (`via`) and, when the call site has one, the request.
116
+ */
117
+ async canAuthenticate(user, context) {
118
+ return authConfig.canAuthenticate(user, context);
115
119
  }
116
- async assertCanAuthenticate(user) {
117
- if (!await this.canAuthenticate(user)) throw new ForbiddenError("This user cannot authenticate.");
120
+ async assertCanAuthenticate(user, context) {
121
+ if (!await this.canAuthenticate(user, context)) throw new ForbiddenError("This user cannot authenticate.");
118
122
  }
119
123
  async issueAccessToken(user, payload, familyId) {
120
124
  const data = {
121
- ...payload || this.buildAccessTokenPayload(user),
125
+ ...typeof user.accessTokenPayload === "function" ? user.accessTokenPayload() : this.buildAccessTokenPayload(user),
126
+ ...payload,
122
127
  id: user.id,
123
128
  userType: user.userType,
124
129
  jti: randomUUID()
@@ -139,7 +144,7 @@ var AuthService = class {
139
144
  * re-verifying the token we just signed.
140
145
  */
141
146
  async generateAccessToken(user, payload) {
142
- await this.assertCanAuthenticate(user);
147
+ await this.assertCanAuthenticate(user, { via: "token" });
143
148
  return this.issueAccessToken(user, payload);
144
149
  }
145
150
  async issueRefreshToken(user, deviceInfo, ensuredFamily) {
@@ -185,7 +190,7 @@ var AuthService = class {
185
190
  */
186
191
  async createRefreshToken(user, deviceInfo) {
187
192
  if (!authConfig.refreshToken.enabled()) return;
188
- await this.assertCanAuthenticate(user);
193
+ await this.assertCanAuthenticate(user, { via: "token" });
189
194
  if (deviceInfo?.familyId) return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) => this.issueRefreshToken(user, deviceInfo, family));
190
195
  return this.issueRefreshToken(user, deviceInfo);
191
196
  }
@@ -216,7 +221,7 @@ var AuthService = class {
216
221
  * Issue both an access and a refresh token, emitting the creation events.
217
222
  */
218
223
  async createTokenPair(user, deviceInfo) {
219
- await this.assertCanAuthenticate(user);
224
+ await this.assertCanAuthenticate(user, { via: "token" });
220
225
  if (authConfig.refreshToken.enabled() && deviceInfo?.familyId) return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) => this.issueTokenPair(user, deviceInfo, family));
221
226
  return this.issueTokenPair(user, deviceInfo);
222
227
  }
@@ -251,7 +256,7 @@ var AuthService = class {
251
256
  if (!UserModel) throw new Error(`User type ${decoded.userType} is unknown type.`);
252
257
  const user = await UserModel.find(decoded.userId);
253
258
  if (!user) return null;
254
- if (!await this.canAuthenticate(user)) return null;
259
+ if (!await this.canAuthenticate(user, { via: "refresh" })) return null;
255
260
  if (authConfig.refreshToken.rotation()) {
256
261
  if (!await refreshToken.revokeIfActive()) {
257
262
  await this.revokeTokenFamily(refreshToken.familyId);
@@ -306,7 +311,10 @@ var AuthService = class {
306
311
  const UserModel = config.key(`auth.userType.${decoded.userType}`);
307
312
  if (!UserModel) throw new Error(`User type ${decoded.userType} is unknown type.`);
308
313
  const user = await UserModel.find(decoded.userId);
309
- if (!user || !await this.canAuthenticate(user)) return null;
314
+ if (!user || !await this.canAuthenticate(user, {
315
+ via: "refresh",
316
+ request: options.request
317
+ })) return null;
310
318
  if (!await oldToken.revokeIfActive()) {
311
319
  const currentToken = await this.refreshTokenModel.findByToken(refreshTokenString);
312
320
  if (!currentToken) return null;
@@ -448,27 +456,68 @@ var AuthService = class {
448
456
  return await Model.first(asSent);
449
457
  }
450
458
  /**
451
- * Resolve a user by credentials, verifying the password. Returns `null` on a
452
- * missing user or a wrong password, emitting `login.failed` either way.
453
- */
454
- async attemptLogin(Model, data) {
455
- const { password, ...otherData } = data;
456
- authEvents.emit("login.attempt", otherData);
459
+ * Check credentials and report WHY they failed, without emitting events or
460
+ * touching the stored hash:
461
+ *
462
+ * - `{ type: "ok", user }`: the account exists, the password is right and
463
+ * `auth.canAuthenticate` allows it.
464
+ * - `{ type: "invalid" }`: unknown account or wrong password (both take the
465
+ * same time, so the answer does not reveal which).
466
+ * - `{ type: "refused", user }`: the password is right but
467
+ * `auth.canAuthenticate` refuses the account (suspended, not yet approved).
468
+ * Reveal this only after the correct password, as here.
469
+ */
470
+ async verifyCredentials(Model, credentials, request) {
471
+ const { reason: _reason, ...result } = await this.checkCredentials(Model, credentials, request);
472
+ return result;
473
+ }
474
+ /** The shared check: `verifyCredentials` plus the reason `attemptLogin` reports in its event. */
475
+ async checkCredentials(Model, credentials, request) {
476
+ const { password, ...otherData } = credentials;
457
477
  const user = await this.findLoginUser(Model, otherData);
458
478
  const storedHash = user?.string("password");
459
479
  if (!user || !storedHash) {
460
480
  await dummyHash().then((hash) => this.verifyPassword(String(password ?? ""), hash)).catch(() => false);
461
- authEvents.emit("login.failed", otherData, user ? "Invalid password" : "User not found");
462
- return null;
481
+ return {
482
+ type: "invalid",
483
+ reason: user ? "Invalid password" : "User not found"
484
+ };
463
485
  }
464
- if (!await this.verifyPassword(password, storedHash)) {
465
- authEvents.emit("login.failed", otherData, "Invalid password");
486
+ if (!await this.verifyPassword(password, storedHash)) return {
487
+ type: "invalid",
488
+ reason: "Invalid password"
489
+ };
490
+ if (!await this.canAuthenticate(user, {
491
+ via: "password",
492
+ request
493
+ })) return {
494
+ type: "refused",
495
+ user
496
+ };
497
+ return {
498
+ type: "ok",
499
+ user
500
+ };
501
+ }
502
+ /**
503
+ * Resolve a user by credentials, verifying the password. Returns `null` on a
504
+ * missing user, a wrong password or a refused account, emitting
505
+ * `login.failed` either way. Use {@link verifyCredentials} to tell them apart.
506
+ */
507
+ async attemptLogin(Model, data, request) {
508
+ const { password, ...otherData } = data;
509
+ authEvents.emit("login.attempt", otherData);
510
+ const result = await this.checkCredentials(Model, data, request);
511
+ if (result.type === "invalid") {
512
+ authEvents.emit("login.failed", otherData, result.reason ?? "Invalid password");
466
513
  return null;
467
514
  }
468
- if (!await this.canAuthenticate(user)) {
515
+ if (result.type === "refused") {
469
516
  authEvents.emit("login.failed", otherData, "Authentication not allowed");
470
517
  return null;
471
518
  }
519
+ const user = result.user;
520
+ const storedHash = user.string("password");
472
521
  await this.rehashPassword(user, String(password), storedHash);
473
522
  return user;
474
523
  }
@@ -492,8 +541,8 @@ var AuthService = class {
492
541
  * Full login flow: validate credentials, issue tokens, emit events. Returns
493
542
  * the user + token pair on success, `null` on failure.
494
543
  */
495
- async login(Model, credentials, deviceInfo) {
496
- const user = await this.attemptLogin(Model, credentials);
544
+ async login(Model, credentials, deviceInfo, request) {
545
+ const user = await this.attemptLogin(Model, credentials, request);
497
546
  if (!user) return null;
498
547
  return this.finalizeLogin(user, deviceInfo);
499
548
  }
@@ -504,10 +553,16 @@ var AuthService = class {
504
553
  * what {@link login} produces: the same tokens, rows and events. Pair with
505
554
  * {@link setAuthCookie} for a cookie session, as with password login.
506
555
  *
556
+ * `context` is passed to the policy: `via` names the login method (default
557
+ * `"custom"`) and `request` is the request being served, when there is one.
558
+ *
507
559
  * Never call this for a user you have not authenticated.
508
560
  */
509
- async completeLogin(user, deviceInfo) {
510
- await this.assertCanAuthenticate(user);
561
+ async completeLogin(user, deviceInfo, context) {
562
+ await this.assertCanAuthenticate(user, {
563
+ ...context,
564
+ via: context?.via ?? "custom"
565
+ });
511
566
  return this.finalizeLogin(user, deviceInfo);
512
567
  }
513
568
  /**
@@ -519,7 +574,7 @@ var AuthService = class {
519
574
  */
520
575
  async loginWithSessionCookies(request, response, Model, credentials, deviceInfo) {
521
576
  assertCsrfOriginAllowed(request);
522
- const result = await this.login(Model, credentials, deviceInfo);
577
+ const result = await this.login(Model, credentials, deviceInfo, request);
523
578
  if (!result) return null;
524
579
  if (result.tokens.refreshToken) this.setSessionCookies(response, {
525
580
  accessToken: result.tokens.accessToken,