@warlock.js/auth 5.52.0 → 5.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/esm/commands/auth-cleanup-command.mjs.map +1 -1
  3. package/esm/commands/auth-purge-never-expiring-command.mjs.map +1 -1
  4. package/esm/commands/jwt-secret-generator-command.mjs.map +1 -1
  5. package/esm/contracts/index.d.mts +2 -2
  6. package/esm/contracts/providers.d.mts +53 -0
  7. package/esm/contracts/providers.d.mts.map +1 -1
  8. package/esm/contracts/types.d.mts +53 -0
  9. package/esm/contracts/types.d.mts.map +1 -1
  10. package/esm/contracts/types.mjs.map +1 -1
  11. package/esm/errors/auth-provider-sdk-missing.error.mjs.map +1 -1
  12. package/esm/errors/email-not-verified.error.mjs.map +1 -1
  13. package/esm/errors/index.d.mts +2 -1
  14. package/esm/errors/index.mjs +2 -1
  15. package/esm/errors/invalid-one-time-token.error.mjs.map +1 -1
  16. package/esm/errors/invalid-passkey.error.mjs.map +1 -1
  17. package/esm/errors/invalid-provider-callback.error.mjs.map +1 -1
  18. package/esm/errors/notifications-unavailable.error.mjs.map +1 -1
  19. package/esm/errors/provider-account-link-blocked.error.d.mts +16 -0
  20. package/esm/errors/provider-account-link-blocked.error.d.mts.map +1 -0
  21. package/esm/errors/provider-account-link-blocked.error.mjs +22 -0
  22. package/esm/errors/provider-account-link-blocked.error.mjs.map +1 -0
  23. package/esm/errors/provider-email-not-verified.error.mjs.map +1 -1
  24. package/esm/index.d.mts +3 -2
  25. package/esm/index.mjs +2 -1
  26. package/esm/localization/ar.translations.mjs.map +1 -1
  27. package/esm/localization/auth-default-translations.mjs.map +1 -1
  28. package/esm/localization/en.translations.mjs.map +1 -1
  29. package/esm/localization/init.mjs.map +1 -1
  30. package/esm/localization/register-auth-translations.mjs.map +1 -1
  31. package/esm/middleware/auth.middleware.mjs +1 -1
  32. package/esm/middleware/auth.middleware.mjs.map +1 -1
  33. package/esm/middleware/csrf-origin-check.mjs.map +1 -1
  34. package/esm/middleware/localized-login-path.mjs.map +1 -1
  35. package/esm/middleware/login-throttle.middleware.d.mts +38 -8
  36. package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
  37. package/esm/middleware/login-throttle.middleware.mjs +93 -29
  38. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  39. package/esm/middleware/one-time-token-throttle.middleware.mjs.map +1 -1
  40. package/esm/middleware/otp-throttle.middleware.mjs.map +1 -1
  41. package/esm/middleware/require-verified-email.middleware.mjs.map +1 -1
  42. package/esm/models/access-token/access-token.model.d.mts +14 -3
  43. package/esm/models/access-token/access-token.model.d.mts.map +1 -1
  44. package/esm/models/access-token/access-token.model.mjs +15 -8
  45. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  46. package/esm/models/access-token/family-association.migration.mjs.map +1 -1
  47. package/esm/models/access-token/migration.mjs.map +1 -1
  48. package/esm/models/auth-token-family/auth-token-family.model.mjs.map +1 -1
  49. package/esm/models/auth-token-family/migration.mjs.map +1 -1
  50. package/esm/models/auth.model.d.mts +8 -0
  51. package/esm/models/auth.model.d.mts.map +1 -1
  52. package/esm/models/auth.model.mjs +3 -0
  53. package/esm/models/auth.model.mjs.map +1 -1
  54. package/esm/models/index.mjs.map +1 -1
  55. package/esm/models/one-time-token/migration.mjs.map +1 -1
  56. package/esm/models/one-time-token/one-time-token.model.d.mts +7 -2
  57. package/esm/models/one-time-token/one-time-token.model.d.mts.map +1 -1
  58. package/esm/models/one-time-token/one-time-token.model.mjs +8 -7
  59. package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -1
  60. package/esm/models/passkey-credential/migration.mjs.map +1 -1
  61. package/esm/models/passkey-credential/passkey-credential.model.mjs.map +1 -1
  62. package/esm/models/provider-account/migration.mjs.map +1 -1
  63. package/esm/models/provider-account/provider-account.model.mjs.map +1 -1
  64. package/esm/models/refresh-token/migration.mjs.map +1 -1
  65. package/esm/models/refresh-token/refresh-token.model.d.mts +15 -3
  66. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  67. package/esm/models/refresh-token/refresh-token.model.mjs +17 -12
  68. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  69. package/esm/models/refresh-token/successor-association.migration.mjs.map +1 -1
  70. package/esm/otp/otp.d.mts +5 -1
  71. package/esm/otp/otp.d.mts.map +1 -1
  72. package/esm/otp/otp.mjs +18 -3
  73. package/esm/otp/otp.mjs.map +1 -1
  74. package/esm/passkeys/passkey-authentication.mjs +2 -2
  75. package/esm/passkeys/passkey-authentication.mjs.map +1 -1
  76. package/esm/passkeys/passkey-challenges.mjs.map +1 -1
  77. package/esm/passkeys/passkey-registration.d.mts.map +1 -1
  78. package/esm/passkeys/passkey-registration.mjs +2 -2
  79. package/esm/passkeys/passkey-registration.mjs.map +1 -1
  80. package/esm/passkeys/simplewebauthn.mjs.map +1 -1
  81. package/esm/providers/apple-provider.d.mts +2 -0
  82. package/esm/providers/apple-provider.d.mts.map +1 -1
  83. package/esm/providers/apple-provider.mjs +4 -1
  84. package/esm/providers/apple-provider.mjs.map +1 -1
  85. package/esm/providers/discord-provider.d.mts +2 -0
  86. package/esm/providers/discord-provider.d.mts.map +1 -1
  87. package/esm/providers/discord-provider.mjs +7 -1
  88. package/esm/providers/discord-provider.mjs.map +1 -1
  89. package/esm/providers/facebook-provider.d.mts +2 -0
  90. package/esm/providers/facebook-provider.d.mts.map +1 -1
  91. package/esm/providers/facebook-provider.mjs +10 -2
  92. package/esm/providers/facebook-provider.mjs.map +1 -1
  93. package/esm/providers/github-provider.d.mts +2 -0
  94. package/esm/providers/github-provider.d.mts.map +1 -1
  95. package/esm/providers/github-provider.mjs +19 -10
  96. package/esm/providers/github-provider.mjs.map +1 -1
  97. package/esm/providers/google-provider.mjs.map +1 -1
  98. package/esm/providers/linkedin-provider.d.mts +2 -0
  99. package/esm/providers/linkedin-provider.d.mts.map +1 -1
  100. package/esm/providers/linkedin-provider.mjs +4 -1
  101. package/esm/providers/linkedin-provider.mjs.map +1 -1
  102. package/esm/providers/provider-login.mjs.map +1 -1
  103. package/esm/providers/provider-state-cookie.mjs.map +1 -1
  104. package/esm/providers/provider-timeout.mjs +17 -0
  105. package/esm/providers/provider-timeout.mjs.map +1 -0
  106. package/esm/providers/resolve-provider-user.mjs +21 -1
  107. package/esm/providers/resolve-provider-user.mjs.map +1 -1
  108. package/esm/providers/x-provider.d.mts +2 -0
  109. package/esm/providers/x-provider.d.mts.map +1 -1
  110. package/esm/providers/x-provider.mjs +7 -1
  111. package/esm/providers/x-provider.mjs.map +1 -1
  112. package/esm/services/auth-config.mjs +65 -6
  113. package/esm/services/auth-config.mjs.map +1 -1
  114. package/esm/services/auth-cookie-names.mjs +49 -0
  115. package/esm/services/auth-cookie-names.mjs.map +1 -0
  116. package/esm/services/auth-events.d.mts +4 -0
  117. package/esm/services/auth-events.d.mts.map +1 -1
  118. package/esm/services/auth-events.mjs.map +1 -1
  119. package/esm/services/auth.service.d.mts +8 -0
  120. package/esm/services/auth.service.d.mts.map +1 -1
  121. package/esm/services/auth.service.mjs +146 -20
  122. package/esm/services/auth.service.mjs.map +1 -1
  123. package/esm/services/current-user.mjs.map +1 -1
  124. package/esm/services/email-verification.mjs.map +1 -1
  125. package/esm/services/generate-jwt-secret.mjs.map +1 -1
  126. package/esm/services/jwt.d.mts.map +1 -1
  127. package/esm/services/jwt.mjs +92 -10
  128. package/esm/services/jwt.mjs.map +1 -1
  129. package/esm/services/one-time-tokens.mjs.map +1 -1
  130. package/esm/services/optional-peer.mjs.map +1 -1
  131. package/esm/services/password-reset.d.mts +5 -0
  132. package/esm/services/password-reset.d.mts.map +1 -1
  133. package/esm/services/password-reset.mjs +15 -1
  134. package/esm/services/password-reset.mjs.map +1 -1
  135. package/esm/services/resolve-request-user.d.mts.map +1 -1
  136. package/esm/services/resolve-request-user.mjs +17 -3
  137. package/esm/services/resolve-request-user.mjs.map +1 -1
  138. package/esm/services/token-family-operation.mjs.map +1 -1
  139. package/esm/services/token-notifications.mjs.map +1 -1
  140. package/esm/session/page-session.d.mts.map +1 -1
  141. package/esm/session/page-session.mjs +5 -3
  142. package/esm/session/page-session.mjs.map +1 -1
  143. package/esm/utils/auth-error-codes.d.mts +8 -1
  144. package/esm/utils/auth-error-codes.d.mts.map +1 -1
  145. package/esm/utils/auth-error-codes.mjs +7 -0
  146. package/esm/utils/auth-error-codes.mjs.map +1 -1
  147. package/esm/utils/normalize-credentials.mjs.map +1 -1
  148. package/esm/utils/safe-equal.mjs.map +1 -1
  149. package/esm/utils/token-digest.mjs +47 -0
  150. package/esm/utils/token-digest.mjs.map +1 -0
  151. package/esm/utils/token-expiry.d.mts +3 -1
  152. package/esm/utils/token-expiry.d.mts.map +1 -1
  153. package/esm/utils/token-expiry.mjs +7 -2
  154. package/esm/utils/token-expiry.mjs.map +1 -1
  155. package/llms-full.txt +70 -30
  156. package/llms.txt +2 -2
  157. package/package.json +9 -9
  158. package/skills/auth-basics/SKILL.md +9 -0
  159. package/skills/customize-token-storage/SKILL.md +10 -10
  160. package/skills/login-with-providers/SKILL.md +14 -3
  161. package/skills/manage-tokens/SKILL.md +6 -0
  162. package/skills/protect-routes/SKILL.md +5 -0
  163. package/skills/throttle-login-attempts/SKILL.md +23 -17
  164. package/skills/verify-email-and-reset-password/SKILL.md +3 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,46 @@ 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.53.0 - 2026-11-11
8
+
9
+ ### Upgrading
10
+
11
+ - `requestPasswordReset` / `requestOtp` no longer throw when the email or SMS send fails; listen to the `password.resetDeliveryFailed` / `otp.deliveryFailed` auth events, or set `auth.passwordReset.awaitDelivery: true` / `auth.otp.awaitDelivery: true` to get the old behaviour.
12
+ - **BREAKING** A first provider login whose email matches an existing account that has not verified that email fails with `ProviderAccountLinkBlockedError` (403, `EC012`) when your user schema declares the verification field (`emailVerifiedAt` by default). Set `auth.providers.linkExisting: "always"` to link as before.
13
+ - **BREAKING** `Auth` models no longer serialize `password`. If your model sets its own `static hidden`, it replaces the default: keep `"password"` in it. Code that reads the hash from `toJSON()` output or from lean query rows must read it from the model (`user.get("password")`), or set `public static hidden: string[] = []` on the model to restore the old output.
14
+ - Throttled routes count an attempt when it arrives: more than `max` simultaneous requests on one bucket (for example `max` concurrent refreshes from one IP) get `429` while the others are in flight. Raise `max` on that route if it legitimately receives such bursts.
15
+ - Login with an unknown email takes as long as a wrong password (one password-hash check).
16
+ - A token whose `id` / `userType` claims differ from its stored row is rejected, and a custom access-token payload can no longer override `id` / `userType`.
17
+ - GitHub, Discord, LinkedIn, Apple, Facebook and X logins fail (`code-exchange-failed` / `profile-fetch-failed`) when the provider takes longer than 5 seconds to answer; raise `timeoutMs` in that provider's block if needed. A `timeoutMs` that is not a positive integer throws when the provider is built.
18
+ - Expired or malformed tokens and CSRF Origin mismatches no longer appear in the error log; set the logger to `debug` to see them.
19
+ - In production, a signing secret shorter than 32 bytes or an access-token lifetime over 30 days logs a one-time warning.
20
+ - `AccessToken` / `RefreshToken` `findByToken`, `findForUser` and `deleteForUser` query `whereIn("token", [sha256(token), token])`. A model override that replaces these statics should match both forms if `hashTokensAtRest` is (or was) on.
21
+ - The new opt-in settings change nothing until you set them. Setting `auth.accessToken.issuer` or `auth.accessToken.audience` refuses tokens signed before it, so every user signs in again once. With `hashTokensAtRest` on, a row loaded from the database (`activeSessions()`, event payloads) holds only the digest in `token`.
22
+
23
+ ### Security
24
+
25
+ - Login, token-issue and OTP throttles count each attempt when it arrives, before the controller runs. A burst of concurrent requests used to read "not locked" all at once and reach the password check hundreds of times; now at most `max` attempts per window get through and the rest answer `429` (`EC004`). A lockout also restarts the counting window, so the identifier gets a fresh `max` once the lock ends.
26
+ - `loginThrottleMiddleware` takes `emailLock: "pair" | "global"` (default `"global"`, unchanged). `"pair"` locks the (email, IP) pair instead of the email for everyone, so a stranger can no longer keep a known account locked out; the email alone keeps a wider bucket, `accountMax` (default `max * 10`), against guessing spread over many IPs.
27
+ - Login with an unknown email runs the same password-hash check as a wrong password, so response timing no longer reveals which accounts exist.
28
+ - `requestPasswordReset` and `requestOtp` send the email or code in the background, so a known account no longer answers slower than an unknown one. A failed send is logged and emitted as the new `password.resetDeliveryFailed` / `otp.deliveryFailed` auth events. `auth.passwordReset.awaitDelivery` / `auth.otp.awaitDelivery` (default `false`) wait for the send instead.
29
+ - A provider login no longer links to an existing account that never verified its email (someone could pre-register a victim's address with a password and end up sharing the account). New `auth.providers.linkExisting: "verified" | "always" | "never"` (default `"verified"`); a refused link throws the new `ProviderAccountLinkBlockedError` (403, `EC012`). A user model whose schema has no verification field links as before.
30
+ - New `auth.hashTokensAtRest` (default `false`): access and refresh token rows store only the SHA-256 digest of the token, so a copied table cannot be replayed. No migration is needed: the digest goes in the existing `token` column, lookups accept both forms, and switching it on or off signs no one out. A freshly issued row exposes its raw token as `row.plainToken`.
31
+ - In production, a signing secret shorter than 32 bytes (`auth.accessToken.secret`, `auth.refreshToken.secret`) or an access-token lifetime over 30 days logs a one-time warning.
32
+ - New `auth.passkeys.userVerification: "required" | "preferred"` (default `"preferred"`, unchanged). `"required"` refuses passkey assertions made without a PIN or biometric.
33
+ - `auth.cleanup` removes spent one-time tokens (including anonymous passkey challenges) with two set-based deletes instead of loading every row into memory. The docs show a per-IP throttle on the passkey login-options route.
34
+ - GitHub, Discord, LinkedIn, Apple, Facebook and X provider requests time out after `timeoutMs` (default `5000`, per provider block), as Google already did, instead of waiting forever on a hanging provider.
35
+ - Expired or malformed tokens and CSRF Origin mismatches are logged at `debug` instead of `error`, so anonymous clients can no longer flood the error log.
36
+ - The route gate refuses a token whose `id` / `userType` claims name a different user than its `access_tokens` row, and issued tokens always carry the issuing user's `id` / `userType`, even when a custom payload sets them.
37
+ - New optional `auth.accessToken.issuer` / `auth.accessToken.audience`: stamped as `iss` / `aud` on every token the app signs and required on every token it accepts, so apps sharing a secret cannot accept each other's tokens. Unset (the default) changes nothing.
38
+ - The `Auth` base model hides `password` from serialized output (`static hidden = ["password"]`): `response.json(user)`, lean rows and embedded copies no longer carry the hash. `user.get("password")` still reads it.
39
+ - New `auth.cookie.hostPrefix` (default `false`): the auth cookies are written as `__Host-access_token` / `__Host-refresh_token` (Secure, `Path=/`, no Domain), so a subdomain or plain-HTTP page cannot plant or overwrite them. A cookie path other than `/` or a Domain throws naming the setting. The unprefixed cookie is still read while switching, and logout clears both.
40
+ - The minimum `fast-jwt` version is 6.3.4.
41
+
42
+ ### Changed
43
+
44
+ - The JWT verifier and signer are built once per settings and reused, instead of on every authenticated request.
45
+ - `revokeAllTokens` (logout without a refresh token, password reset) ensures each token family once instead of once per rotated refresh row.
46
+
7
47
  ## 5.52.0 - 2026-11-11
8
48
 
9
49
  ### Added
@@ -1 +1 @@
1
- {"version":3,"file":"auth-cleanup-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/auth-cleanup-command.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { command } from \"@warlock.js/core\";\nimport { authService } from \"../services/auth.service\";\n\n/**\n * Register the auth:cleanup CLI command\n *\n * @example\n * ```bash\n * warlock auth:cleanup\n * ```\n */\nexport function registerAuthCleanupCommand() {\n return command({\n name: \"auth.cleanup\",\n description: \"Remove expired access/refresh tokens and spent one-time tokens from the database\",\n preload: {\n env: true,\n config: [\"auth\", \"database\"],\n connectors: [\"database\"],\n },\n action: async () => {\n console.log(colors.cyan(\"🧹 Cleaning up expired tokens...\"));\n\n const count = await authService.cleanupExpiredTokens();\n\n if (count === 0) {\n console.log(colors.green(\"✅ No expired tokens found.\"));\n } else {\n console.log(colors.green(`✅ Removed ${count} expired token(s).`));\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,6BAA6B;CAC3C,OAAO,QAAQ;EACb,MAAM;EACN,aAAa;EACb,SAAS;GACP,KAAK;GACL,QAAQ,CAAC,QAAQ,UAAU;GAC3B,YAAY,CAAC,UAAU;EACzB;EACA,QAAQ,YAAY;GAClB,QAAQ,IAAI,OAAO,KAAK,kCAAkC,CAAC;GAE3D,MAAM,QAAQ,MAAM,YAAY,qBAAqB;GAErD,IAAI,UAAU,GACZ,QAAQ,IAAI,OAAO,MAAM,4BAA4B,CAAC;QAEtD,QAAQ,IAAI,OAAO,MAAM,aAAa,MAAM,mBAAmB,CAAC;EAEpE;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"auth-cleanup-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/auth-cleanup-command.ts"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,6BAA6B;CAC3C,OAAO,QAAQ;EACb,MAAM;EACN,aAAa;EACb,SAAS;GACP,KAAK;GACL,QAAQ,CAAC,QAAQ,UAAU;GAC3B,YAAY,CAAC,UAAU;EACzB;EACA,QAAQ,YAAY;GAClB,QAAQ,IAAI,OAAO,KAAK,kCAAkC,CAAC;GAE3D,MAAM,QAAQ,MAAM,YAAY,qBAAqB;GAErD,IAAI,UAAU,GACZ,QAAQ,IAAI,OAAO,MAAM,4BAA4B,CAAC;QAEtD,QAAQ,IAAI,OAAO,MAAM,aAAa,MAAM,mBAAmB,CAAC;EAEpE;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"auth-purge-never-expiring-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/auth-purge-never-expiring-command.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { command } from \"@warlock.js/core\";\nimport { authService } from \"../services/auth.service\";\n\n/**\n * Register the `auth.purge-never-expiring` CLI command — remediation for the\n * pre-4.12.0 `expiresIn` defect (#25).\n *\n * **Why a command and not a migration.** The rows this removes cannot be\n * selected by a date predicate (an `Invalid Date` compares `false` against\n * every date, so `WHERE expires_at < now()` never matches one) and the\n * definitive signal — a token with no `exp` claim — lives inside the JWT\n * string, not in a column. A migration would also run once, silently, at deploy\n * time; an operator dealing with possibly-leaked credentials needs to *look*\n * first, then act, and to repeat it. Hence `--dry-run`, which is the default\n * posture this command is expected to be run in first.\n *\n * A migration is additionally the wrong shape for a fix that must reach both\n * supported stores: the same row is a different thing in MongoDB and Postgres,\n * and this goes through the models so a registered override\n * (`config.auth.accessToken.model`) is honoured.\n *\n * @example\n * ```bash\n * warlock auth.purge-never-expiring --dry-run # report only\n * warlock auth.purge-never-expiring # report, then delete\n * ```\n */\nexport function registerAuthPurgeNeverExpiringCommand() {\n return command({\n name: \"auth.purge-never-expiring\",\n description:\n \"Find (and delete) token rows that can never expire — an unusable expires_at, or a token with no exp claim\",\n options: [\n {\n text: \"--dry-run\",\n description: \"Report the affected rows without deleting anything\",\n type: \"boolean\",\n },\n ],\n preload: {\n env: true,\n config: [\"auth\", \"database\"],\n connectors: [\"database\"],\n },\n action: async (data: { options?: Record<string, unknown> } = {}) => {\n // Core camelCases flags (`--dry-run` ⇒ `dryRun`); both spellings are read\n // so the command does not depend on that detail staying true.\n //\n // Read fail-safe: the flag counts as set unless it is *explicitly* false\n // (`--dry-run=false`). An operator who asked to look before deleting and\n // got a delete because a flag arrived as `\"true\"` instead of `true` would\n // lose live credentials to a parsing detail.\n const flags = data.options ?? {};\n const flag = flags[\"dryRun\"] ?? flags[\"dry-run\"];\n const dryRun = flag !== undefined && flag !== false && flag !== \"false\";\n\n console.log(colors.cyan(\"🔎 Scanning for tokens that can never expire...\"));\n\n const { accessTokens, refreshTokens } = await authService.findNeverExpiringTokens();\n const total = accessTokens.length + refreshTokens.length;\n\n if (total === 0) {\n console.log(colors.green(\"✅ No never-expiring tokens found.\"));\n\n return;\n }\n\n console.log(\n colors.yellow(\n `⚠️ ${total} never-expiring token(s): ` +\n `${accessTokens.length} access, ${refreshTokens.length} refresh.`,\n ),\n );\n\n // Identify each row so an operator can correlate with their own audit\n // trail before (or after) the rows are gone. The token string itself is\n // never printed — it is a live credential until this command removes it.\n for (const token of accessTokens) {\n console.log(\n colors.yellow(\n ` access id=${token.id} user_id=${token.get(\"user_id\")} ` +\n `user_type=${token.get(\"user_type\")} expires_at=${String(token.get(\"expires_at\"))}`,\n ),\n );\n }\n\n for (const token of refreshTokens) {\n console.log(\n colors.yellow(\n ` refresh id=${token.id} user_id=${token.get(\"user_id\")} ` +\n `user_type=${token.get(\"user_type\")} expires_at=${String(token.get(\"expires_at\"))}`,\n ),\n );\n }\n\n if (dryRun) {\n console.log(\n colors.cyan(\n \"Dry run — nothing deleted. Re-run without --dry-run to revoke these tokens.\",\n ),\n );\n\n return;\n }\n\n // Re-selects rather than deleting the rows just listed: the delete then\n // acts on the table's current state instead of a snapshot taken before\n // the operator read the report. A second full scan is affordable here —\n // this is a one-off remediation, not a request path.\n const purged = await authService.purgeNeverExpiringTokens();\n\n console.log(\n colors.green(\n `✅ Revoked ${purged.accessTokens} access token(s) and ` +\n `${purged.refreshTokens} refresh token(s). Affected users must log in again.`,\n ),\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,wCAAwC;CACtD,OAAO,QAAQ;EACb,MAAM;EACN,aACE;EACF,SAAS,CACP;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR,CACF;EACA,SAAS;GACP,KAAK;GACL,QAAQ,CAAC,QAAQ,UAAU;GAC3B,YAAY,CAAC,UAAU;EACzB;EACA,QAAQ,OAAO,OAA8C,CAAC,MAAM;GAQlE,MAAM,QAAQ,KAAK,WAAW,CAAC;GAC/B,MAAM,OAAO,MAAM,aAAa,MAAM;GACtC,MAAM,SAAS,SAAS,UAAa,SAAS,SAAS,SAAS;GAEhE,QAAQ,IAAI,OAAO,KAAK,iDAAiD,CAAC;GAE1E,MAAM,EAAE,cAAc,kBAAkB,MAAM,YAAY,wBAAwB;GAClF,MAAM,QAAQ,aAAa,SAAS,cAAc;GAElD,IAAI,UAAU,GAAG;IACf,QAAQ,IAAI,OAAO,MAAM,mCAAmC,CAAC;IAE7D;GACF;GAEA,QAAQ,IACN,OAAO,OACL,OAAO,MAAM,4BACR,aAAa,OAAO,WAAW,cAAc,OAAO,UAC3D,CACF;GAKA,KAAK,MAAM,SAAS,cAClB,QAAQ,IACN,OAAO,OACL,gBAAgB,MAAM,GAAG,WAAW,MAAM,IAAI,SAAS,EAAE,aAC1C,MAAM,IAAI,WAAW,EAAE,cAAc,OAAO,MAAM,IAAI,YAAY,CAAC,GACpF,CACF;GAGF,KAAK,MAAM,SAAS,eAClB,QAAQ,IACN,OAAO,OACL,gBAAgB,MAAM,GAAG,WAAW,MAAM,IAAI,SAAS,EAAE,aAC1C,MAAM,IAAI,WAAW,EAAE,cAAc,OAAO,MAAM,IAAI,YAAY,CAAC,GACpF,CACF;GAGF,IAAI,QAAQ;IACV,QAAQ,IACN,OAAO,KACL,6EACF,CACF;IAEA;GACF;GAMA,MAAM,SAAS,MAAM,YAAY,yBAAyB;GAE1D,QAAQ,IACN,OAAO,MACL,aAAa,OAAO,aAAa,uBAC5B,OAAO,cAAc,qDAC5B,CACF;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"auth-purge-never-expiring-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/auth-purge-never-expiring-command.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,wCAAwC;CACtD,OAAO,QAAQ;EACb,MAAM;EACN,aACE;EACF,SAAS,CACP;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR,CACF;EACA,SAAS;GACP,KAAK;GACL,QAAQ,CAAC,QAAQ,UAAU;GAC3B,YAAY,CAAC,UAAU;EACzB;EACA,QAAQ,OAAO,OAA8C,CAAC,MAAM;GAQlE,MAAM,QAAQ,KAAK,WAAW,CAAC;GAC/B,MAAM,OAAO,MAAM,aAAa,MAAM;GACtC,MAAM,SAAS,SAAS,UAAa,SAAS,SAAS,SAAS;GAEhE,QAAQ,IAAI,OAAO,KAAK,iDAAiD,CAAC;GAE1E,MAAM,EAAE,cAAc,kBAAkB,MAAM,YAAY,wBAAwB;GAClF,MAAM,QAAQ,aAAa,SAAS,cAAc;GAElD,IAAI,UAAU,GAAG;IACf,QAAQ,IAAI,OAAO,MAAM,mCAAmC,CAAC;IAE7D;GACF;GAEA,QAAQ,IACN,OAAO,OACL,OAAO,MAAM,4BACR,aAAa,OAAO,WAAW,cAAc,OAAO,UAC3D,CACF;GAKA,KAAK,MAAM,SAAS,cAClB,QAAQ,IACN,OAAO,OACL,gBAAgB,MAAM,GAAG,WAAW,MAAM,IAAI,SAAS,EAAE,aAC1C,MAAM,IAAI,WAAW,EAAE,cAAc,OAAO,MAAM,IAAI,YAAY,CAAC,GACpF,CACF;GAGF,KAAK,MAAM,SAAS,eAClB,QAAQ,IACN,OAAO,OACL,gBAAgB,MAAM,GAAG,WAAW,MAAM,IAAI,SAAS,EAAE,aAC1C,MAAM,IAAI,WAAW,EAAE,cAAc,OAAO,MAAM,IAAI,YAAY,CAAC,GACpF,CACF;GAGF,IAAI,QAAQ;IACV,QAAQ,IACN,OAAO,KACL,6EACF,CACF;IAEA;GACF;GAMA,MAAM,SAAS,MAAM,YAAY,yBAAyB;GAE1D,QAAQ,IACN,OAAO,MACL,aAAa,OAAO,aAAa,uBAC5B,OAAO,cAAc,qDAC5B,CACF;EACF;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"jwt-secret-generator-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/jwt-secret-generator-command.ts"],"sourcesContent":["import { command } from \"@warlock.js/core\";\nimport { generateJWTSecret } from \"../services/generate-jwt-secret\";\n\nexport function registerJWTSecretGeneratorCommand() {\n return command({\n name: \"jwt.generate\",\n description: \"Generate JWT Secret key in .env file\",\n action: generateJWTSecret,\n });\n}\n"],"mappings":";;;;AAGA,SAAgB,oCAAoC;CAClD,OAAO,QAAQ;EACb,MAAM;EACN,aAAa;EACb,QAAQ;CACV,CAAC;AACH"}
1
+ {"version":3,"file":"jwt-secret-generator-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/jwt-secret-generator-command.ts"],"mappings":";;;;AAGA,SAAgB,oCAAoC;CAClD,OAAO,QAAQ;EACb,MAAM;EACN,aAAa;EACb,QAAQ;CACV,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
- import { AppleProviderConfig, AuthProvider, DiscordProviderConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LinkedInProviderConfig, OtpConfig, OtpMessage, OtpSender, PasskeysConfig, ProviderAuthorizationState, ProviderCallbackParams, ProviderProfile, ProviderUserCreator, ProvidersConfig, XProviderConfig } from "./providers.mjs";
1
+ import { AppleProviderConfig, AuthProvider, DiscordProviderConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LinkedInProviderConfig, OtpConfig, OtpMessage, OtpSender, PasskeysConfig, ProviderAuthorizationState, ProviderCallbackParams, ProviderLinkExisting, ProviderProfile, ProviderUserCreator, ProvidersConfig, XProviderConfig } from "./providers.mjs";
2
2
  import { AccessTokenConfig, AccessTokenOutput, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthRefreshCredentialDescriptor, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, EmailVerificationConfig, LegacyJwtConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, PageAuthConfig, PasswordResetConfig, PasswordSetter, RefreshTokenConfig, SetAuthCookieOptions, TokenFrom, TokenPair } from "./types.mjs";
3
3
  import { Authenticable } from "./auth-contract.mjs";
4
4
  import { RequestUser } from "./request-locals.mjs";
5
- export { AccessTokenConfig, AccessTokenOutput, AppleProviderConfig, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthRefreshCredentialDescriptor, Authenticable, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, DiscordProviderConfig, EmailVerificationConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LegacyJwtConfig, LinkedInProviderConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAuthorizationState, ProviderCallbackParams, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshTokenConfig, RequestUser, SetAuthCookieOptions, TokenFrom, TokenPair, XProviderConfig };
5
+ export { AccessTokenConfig, AccessTokenOutput, AppleProviderConfig, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthRefreshCredentialDescriptor, Authenticable, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, DiscordProviderConfig, EmailVerificationConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LegacyJwtConfig, LinkedInProviderConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAuthorizationState, ProviderCallbackParams, ProviderLinkExisting, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshTokenConfig, RequestUser, SetAuthCookieOptions, TokenFrom, TokenPair, XProviderConfig };
@@ -80,6 +80,8 @@ export type GitHubProviderConfig = {
80
80
  redirectUri: string;
81
81
  /** @default ["read:user", "user:email"] */
82
82
  scopes?: string[];
83
+ /** Positive integer deadline per token, profile or key-set request, in milliseconds. @default 5000 */
84
+ timeoutMs?: number;
83
85
  };
84
86
  /** `auth.providers.discord`. */
85
87
  export type DiscordProviderConfig = {
@@ -89,6 +91,8 @@ export type DiscordProviderConfig = {
89
91
  redirectUri: string;
90
92
  /** @default ["identify", "email"] */
91
93
  scopes?: string[];
94
+ /** Positive integer deadline per token, profile or key-set request, in milliseconds. @default 5000 */
95
+ timeoutMs?: number;
92
96
  };
93
97
  /** `auth.providers.linkedin`. */
94
98
  export type LinkedInProviderConfig = {
@@ -98,6 +102,8 @@ export type LinkedInProviderConfig = {
98
102
  redirectUri: string;
99
103
  /** @default ["openid", "profile", "email"] */
100
104
  scopes?: string[];
105
+ /** Positive integer deadline per token, profile or key-set request, in milliseconds. @default 5000 */
106
+ timeoutMs?: number;
101
107
  };
102
108
  /** `auth.providers.apple`. */
103
109
  export type AppleProviderConfig = {
@@ -113,6 +119,8 @@ export type AppleProviderConfig = {
113
119
  redirectUri: string;
114
120
  /** @default ["name", "email"] */
115
121
  scopes?: string[];
122
+ /** Positive integer deadline per token, profile or key-set request, in milliseconds. @default 5000 */
123
+ timeoutMs?: number;
116
124
  };
117
125
  /** `auth.providers.facebook`. */
118
126
  export type FacebookProviderConfig = {
@@ -122,6 +130,8 @@ export type FacebookProviderConfig = {
122
130
  redirectUri: string;
123
131
  /** @default ["email", "public_profile"] */
124
132
  scopes?: string[];
133
+ /** Positive integer deadline per token, profile or key-set request, in milliseconds. @default 5000 */
134
+ timeoutMs?: number;
125
135
  };
126
136
  /** `auth.providers.x`. */
127
137
  export type XProviderConfig = {
@@ -131,10 +141,14 @@ export type XProviderConfig = {
131
141
  redirectUri: string;
132
142
  /** @default ["tweet.read", "users.read"] */
133
143
  scopes?: string[];
144
+ /** Positive integer deadline per token, profile or key-set request, in milliseconds. @default 5000 */
145
+ timeoutMs?: number;
134
146
  };
135
147
  /** Creates the app user for a verified provider profile with no matching account. */
136
148
  export type ProviderUserCreator = (profile: ProviderProfile, Model: ChildModel<Auth>) => Auth | Promise<Auth>;
137
149
  /** `auth.providers`. */
150
+ /** Policy for linking a provider login to an existing account by email. */
151
+ export type ProviderLinkExisting = "verified" | "always" | "never";
138
152
  export type ProvidersConfig = {
139
153
  google?: GoogleProviderConfig;
140
154
  github?: GitHubProviderConfig;
@@ -150,6 +164,24 @@ export type ProvidersConfig = {
150
164
  emailField?: string;
151
165
  /** Replace the default user creation (`{ email, name, <verification.field>: now }`). */
152
166
  createUser?: ProviderUserCreator;
167
+ /**
168
+ * Whether a first provider login may link to an existing account found by
169
+ * its (provider-verified) email.
170
+ *
171
+ * - `"verified"` — link only when that account has verified the email
172
+ * itself (`auth.verification.field` holds a value). A user model whose
173
+ * schema does not declare that field links as `"always"` does.
174
+ * - `"always"` — link to any account with that email.
175
+ * - `"never"` — never link by email; the user signs in another way and
176
+ * links the provider from a signed-in session.
177
+ *
178
+ * A refused link throws `ProviderAccountLinkBlockedError` (403, `EC012`).
179
+ * Linking an unverified account would hand the provider user an account
180
+ * someone else may have pre-registered with their address (and still holds
181
+ * the password for).
182
+ * @default "verified"
183
+ */
184
+ linkExisting?: ProviderLinkExisting;
153
185
  /** Providers auth does not ship, by name. */
154
186
  custom?: Record<string, AuthProvider>;
155
187
  };
@@ -168,6 +200,18 @@ export type PasskeysConfig = {
168
200
  challengeExpiresIn?: string;
169
201
  /** Account name shown by the authenticator. @default user email, else id */
170
202
  userName?: (user: Auth) => string;
203
+ /**
204
+ * Whether the authenticator must verify the user (PIN, biometric) during
205
+ * registration and login.
206
+ *
207
+ * - `"preferred"` — ask for it, but accept a passkey that only proves
208
+ * possession of the authenticator (e.g. a security key without a PIN).
209
+ * - `"required"` — refuse an assertion without user verification, so a
210
+ * passkey login is two factors (the device plus the PIN or biometric).
211
+ * Users whose authenticator cannot verify them cannot register or sign in.
212
+ * @default "preferred"
213
+ */
214
+ userVerification?: "required" | "preferred";
171
215
  };
172
216
  /** Data an OTP delivery receives. */
173
217
  export type OtpMessage = {
@@ -196,6 +240,15 @@ export type OtpConfig = {
196
240
  message?: (code: string) => string;
197
241
  /** Replace delivery entirely. */
198
242
  send?: OtpSender;
243
+ /**
244
+ * Wait for the code delivery before `requestOtp` resolves, so a delivery
245
+ * error reaches the caller. Off by default: the code is sent in the
246
+ * background, so the response time does not reveal whether the phone belongs
247
+ * to an account. A background failure is logged and emitted as
248
+ * `otp.deliveryFailed`.
249
+ * @default false
250
+ */
251
+ awaitDelivery?: boolean;
199
252
  };
200
253
  //#endregion
201
254
  //# sourceMappingURL=providers.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"providers.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/providers.ts"],"mappings":";;;;;;;YAOY;EACV;EACA;EACA;;;;;;;YAQU;EACV,OAAO;EACP,UAAU;;;YAIA;;EAEV;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA,KAAK;;;;;;;iBAQU;WACN;;;;;;;;WAQA;;EAET,iBAAiB,OAAO,sCAAsC;;EAE9D,eAAe,QAAQ,yBAAyB,QAAQ;;;YAI9C;EACV;EACA;;EAEA;;EAEA;;EAEA;;EAEA,eAAe,WAAW;;EAE1B;IAAc;IAAwB;IAAgB;;;;YAI5C;EACV;EACA;;EAEA;;EAEA;;;YAIU;EACV;EACA;;EAEA;;EAEA;;;YAIU;EACV;EACA;;EAEA;;EAEA;;;YAIU;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;YAIU;EACV;EACA;;EAEA;;EAEA;;;YAIU;EACV;EACA;;EAEA;;EAEA;;;YAIU,uBACV,SAAS,iBACT,OAAO,WAAW,UACf,OAAO,QAAQ;;YAGR;EACV,SAAS;EACT,SAAS;EACT,UAAU;EACV,WAAW;EACX,QAAQ;EACR,WAAW;EACX,IAAI;;;;;EAKJ;;EAEA,aAAa;;EAEb,SAAS,eAAe;;;YAId;;EAEV;;EAEA;;EAEA;;;;;EAKA;;EAEA,YAAY,MAAM;;;YAIR;;EAEV;EACA;EACA,WAAW;;;YAID,aAAa,eAAe,SAAS,YAAY;;YAGjD;;;;;;EAMV;;EAEA;;EAEA;;EAEA;;EAEA,WAAW;;EAEX,OAAO"}
1
+ {"version":3,"file":"providers.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/providers.ts"],"mappings":";;;;;;;YAOY;EACV;EACA;EACA;;;;;;;YAQU;EACV,OAAO;EACP,UAAU;;;YAIA;;EAEV;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA,KAAK;;;;;;;iBAQU;WACN;;;;;;;;WAQA;;EAET,iBAAiB,OAAO,sCAAsC;;EAE9D,eAAe,QAAQ,yBAAyB,QAAQ;;;YAI9C;EACV;EACA;;EAEA;;EAEA;;EAEA;;EAEA,eAAe,WAAW;;EAE1B;IAAc;IAAwB;IAAgB;;;;YAI5C;EACV;EACA;;EAEA;;EAEA;;EAEA;;;YAIU;EACV;EACA;;EAEA;;EAEA;;EAEA;;;YAIU;EACV;EACA;;EAEA;;EAEA;;EAEA;;;YAIU;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;YAIU;EACV;EACA;;EAEA;;EAEA;;EAEA;;;YAIU;EACV;EACA;;EAEA;;EAEA;;EAEA;;;YAIU,uBACV,SAAS,iBACT,OAAO,WAAW,UACf,OAAO,QAAQ;;;YAIR;YAEA;EACV,SAAS;EACT,SAAS;EACT,UAAU;EACV,WAAW;EACX,QAAQ;EACR,WAAW;EACX,IAAI;;;;;EAKJ;;EAEA,aAAa;;;;;;;;;;;;;;;;;;EAkBb,eAAe;;EAEf,SAAS,eAAe;;;YAId;;EAEV;;EAEA;;EAEA;;;;;EAKA;;EAEA,YAAY,MAAM;;;;;;;;;;;;EAYlB;;;YAIU;;EAEV;EACA;EACA,WAAW;;;YAID,aAAa,eAAe,SAAS,YAAY;;YAGjD;;;;;;EAMV;;EAEA;;EAEA;;EAEA;;EAEA,WAAW;;EAEX,OAAO;;;;;;;;;EASP"}
@@ -109,6 +109,25 @@ export type AccessTokenConfig = {
109
109
  * @default "1h"
110
110
  */
111
111
  expiresIn?: string;
112
+ /**
113
+ * Issuer (`iss` claim) stamped on every access and refresh token this app
114
+ * signs, and required on every token it accepts. Set it when several apps
115
+ * or services share a signing secret, so a token minted by one is refused
116
+ * by the others. Unset (the default) ⇒ no `iss` is stamped or checked.
117
+ *
118
+ * Tokens signed before it was set carry no `iss` and are refused once it is
119
+ * set, so every signed-in user signs in again once.
120
+ * @example "https://api.example.com"
121
+ */
122
+ issuer?: string;
123
+ /**
124
+ * Audience (`aud` claim) stamped on every token this app signs, and
125
+ * required on every token it accepts (a token matches when its `aud`
126
+ * includes one of the values). Unset (the default) ⇒ no `aud` is stamped or
127
+ * checked. Like `issuer`, setting it signs everyone out once.
128
+ * @example "web-app"
129
+ */
130
+ audience?: string | string[];
112
131
  };
113
132
  /**
114
133
  * Refresh-token configuration.
@@ -261,6 +280,15 @@ export type PasswordResetConfig = {
261
280
  * the stored value with `verifyPassword` either way.
262
281
  */
263
282
  setPassword?: PasswordSetter;
283
+ /**
284
+ * Wait for the reset notification before `requestPasswordReset` resolves,
285
+ * so a delivery error reaches the caller. Off by default: the notification
286
+ * is sent in the background, so the response time does not reveal whether
287
+ * the account exists. A background failure is logged and emitted as
288
+ * `password.resetDeliveryFailed`.
289
+ * @default false
290
+ */
291
+ awaitDelivery?: boolean;
264
292
  };
265
293
  /**
266
294
  * One-time token storage configuration (`auth.oneTimeToken`).
@@ -297,6 +325,19 @@ export type AuthConfigurations = {
297
325
  * @default trim string values, lower-case `email`
298
326
  */
299
327
  normalizeCredentials?: false | NormalizeCredentials;
328
+ /**
329
+ * Store only a SHA-256 digest of each access and refresh token in the
330
+ * database, never the token itself, so a copy of the token tables (a
331
+ * backup, a replica, a read-only injection) cannot be replayed as a login.
332
+ *
333
+ * No migration is needed: the digest goes in the existing `token` column,
334
+ * and lookups accept both forms, so rows issued before the switch keep
335
+ * working until they expire, and turning it off again signs no one out.
336
+ * A row loaded from storage no longer carries its raw token; a freshly
337
+ * issued one exposes it as `row.plainToken`.
338
+ * @default false
339
+ */
340
+ hashTokensAtRest?: boolean;
300
341
  /**
301
342
  * Access-token configuration (secret, expiry, algorithm, model override).
302
343
  */
@@ -432,6 +473,18 @@ export type CookieAuthConfig = {
432
473
  path?: string;
433
474
  /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */
434
475
  cookieDomain?: CookieDomainResolver;
476
+ /**
477
+ * Write the auth cookies under a `__Host-` name prefix (`__Host-access_token`,
478
+ * `__Host-refresh_token`). Browsers accept such a cookie only when it is
479
+ * Secure, has `Path=/` and no `Domain`, so a subdomain or a plain-HTTP page
480
+ * cannot plant or overwrite the session cookie. Requires `path: "/"` and no
481
+ * `cookieDomain`; a write that breaks either rule throws naming the setting.
482
+ *
483
+ * While switching, the unprefixed cookie is still read (so signed-in users
484
+ * stay signed in) and both names are cleared on logout.
485
+ * @default false
486
+ */
487
+ hostPrefix?: boolean;
435
488
  };
436
489
  /**
437
490
  * CSRF Origin-check configuration. Read via
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA4Ba;;;;;;YAOD;;YAGA;;iBAGK;EACf;EACA;;;iBAIe,wCAAwC;;EAEvD;;;iBAIe,8BAA8B,QAAQ;EACrD;;;;;;;;EAQA,UAAU;;EAEV,UAAU;EACV;IAAa;IAAY;;;;YAIf,mBAAmB,MAAM,mBAAmB;;YAG5C,kBAAkB;EAC5B;;;;;;YAOU,wBACV,aAAa,KAAK,iCACf,KAAK;;;;;;;YAQE;;;;;;EAMV,eAAe;;;;EAIf;;;;;EAKA,YAAY;;;;;;;;;;EAUZ;;;;;YAMU;;;;;EAKV,eAAe;;;;;EAKf;;;;;EAKA;;;;;;;;EAQA;;;;;EAKA;;;;;EAKA;;;;;EAKA,qBAAqB;;;;;;;;YASX;EACV;EACA,YAAY;EACZ;EACA;IACE;IACA;IACA;IACA;IACA;IACA,qBAAqB;;;;;;;;;;;YAYb;;;;;;EAMV;;;;;;EAMA;;;;;YAMU;;EAEV;;EAEA,WAAW;;EAEX;;;;;;YAOU;EACV,OAAO,IAAI,MAAM,MAAM;;;YAIb,0BAA0B,eAAe,MAAM;;YAG/C,kBAAkB,MAAM,MAAM,iCAAiC;;;;YAK/D;;;;;EAKV;;;;;;EAMA;;EAEA,eAAe;;EAEf,MAAM;;;;;YAMI;;;;;EAKV;;;;;EAKA;;EAEA,eAAe;;EAEf,MAAM;;;;;;;EAON,cAAc;;;;;YAMJ;;EAEV,eAAe;;YAGL;;;;;EAKV;KACG,mBAAmB,WAAW;;;EAGjC;;;;;EAKA,kBAAkB;;;;;;;;;;;;;EAalB,+BAA+B;;;;EAI/B,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;;;;;;YAOL;;;;;;EAMV;;;;;;;;YASU;;EAEV;;EAEA;;EAEA;;;;;;;EAOA;;;YAIU;;EAEV;;EAEA"}
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA4Ba;;;;;;YAOD;;YAGA;;iBAGK;EACf;EACA;;;iBAIe,wCAAwC;;EAEvD;;;iBAIe,8BAA8B,QAAQ;EACrD;;;;;;;;EAQA,UAAU;;EAEV,UAAU;EACV;IAAa;IAAY;;;;YAIf,mBAAmB,MAAM,mBAAmB;;YAG5C,kBAAkB;EAC5B;;;;;;YAOU,wBACV,aAAa,KAAK,iCACf,KAAK;;;;;;;YAQE;;;;;;EAMV,eAAe;;;;EAIf;;;;;EAKA,YAAY;;;;;;;;;;EAUZ;;;;;;;;;;;EAWA;;;;;;;;EAQA;;;;;YAMU;;;;;EAKV,eAAe;;;;;EAKf;;;;;EAKA;;;;;;;;EAQA;;;;;EAKA;;;;;EAKA;;;;;EAKA,qBAAqB;;;;;;;;YASX;EACV;EACA,YAAY;EACZ;EACA;IACE;IACA;IACA;IACA;IACA;IACA,qBAAqB;;;;;;;;;;;YAYb;;;;;;EAMV;;;;;;EAMA;;;;;YAMU;;EAEV;;EAEA,WAAW;;EAEX;;;;;;YAOU;EACV,OAAO,IAAI,MAAM,MAAM;;;YAIb,0BAA0B,eAAe,MAAM;;YAG/C,kBAAkB,MAAM,MAAM,iCAAiC;;;;YAK/D;;;;;EAKV;;;;;;EAMA;;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;;;;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 * JWT algorithm.\n * @default \"HS256\"\n */\n algorithm?: Algorithm;\n /**\n * Access-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\n * first token issue: each of them would otherwise sign a token with no `exp`\n * claim at all.\n * @example \"1h\" or NO_EXPIRATION\n * @default \"1h\"\n */\n expiresIn?: string;\n};\n\n/**\n * Refresh-token configuration.\n */\nexport type RefreshTokenConfig = {\n /**\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\n * Defaults to the package's `RefreshToken`.\n */\n model?: typeof RefreshToken;\n /**\n * Enable refresh tokens.\n * @default true\n */\n enabled?: boolean;\n /**\n * Separate secret for refresh tokens (recommended for security). Falls back\n * to the access-token secret when omitted.\n */\n secret?: string;\n /**\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds; an unusable value throws naming this key on issue\n * (see {@link AccessTokenConfig.expiresIn}).\n * @example \"7d\" or \"1w\"\n * @default \"7d\"\n */\n expiresIn?: string;\n /**\n * Rotate the refresh token on each use (old token revoked, replay detected).\n * @default true\n */\n rotation?: boolean;\n /**\n * Maximum active refresh tokens per user; the oldest are revoked past it.\n * @default 5\n */\n maxPerUser?: number;\n /**\n * Behavior when logout is called without a refresh token.\n * @default \"revoke-all\"\n */\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n};\n\n/**\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\n * deprecation warning.\n *\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\n */\nexport type LegacyJwtConfig = {\n secret?: string;\n algorithm?: Algorithm;\n expiresIn?: string;\n refresh?: {\n secret?: string;\n enabled?: boolean;\n expiresIn?: string;\n rotation?: boolean;\n maxPerUser?: number;\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n };\n};\n\n/**\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\n * to a login page instead of returning the API-style JSON 401.\n *\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\n * always keep the JSON 401 contract regardless of this setting.\n */\nexport type PageAuthConfig = {\n /**\n * Login path a guarded page route redirects a logged-out browser to (e.g.\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\n * behavior is opt-in and backward-compatible.\n */\n loginPath?: string;\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed.\n * @default \"returnUrl\"\n */\n returnUrlParam?: string;\n};\n\n/**\n * Data every email-verification / password-reset notification receives.\n */\nexport type OneTimeTokenNotificationData = {\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\n token: string;\n /** When the token stops working. */\n expiresAt: Date;\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\n url?: string;\n};\n\n/**\n * Anything auth can deliver a token through — a `defineNotification(...)`\n * result satisfies it, as does any object with a compatible `send`.\n */\nexport type AuthNotification = {\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\n};\n\n/** Builds the link a token notification points at. */\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\n\n/** Persists a new plaintext password for a user during a password reset. */\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\n\n/**\n * Email-verification configuration (`auth.verification`).\n */\nexport type EmailVerificationConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"24h\"\n */\n expiresIn?: string;\n /**\n * User attribute stamped with the verification `Date`. Declare it in the\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\n * @default \"emailVerifiedAt\"\n */\n field?: string;\n /** Replace the default verification email. */\n notification?: AuthNotification;\n /** Build the verification link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n};\n\n/**\n * Password-reset configuration (`auth.passwordReset`).\n */\nexport type PasswordResetConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"60m\"\n */\n expiresIn?: string;\n /**\n * User attribute `requestPasswordReset` looks the account up by.\n * @default \"email\"\n */\n identifierField?: string;\n /** Replace the default reset email. */\n notification?: AuthNotification;\n /** Build the reset link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n /**\n * Persist the new password yourself. By default auth saves a hash made by\n * the same `hashPassword` login verifies against, and falls back to the\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\n * the stored value with `verifyPassword` either way.\n */\n setPassword?: PasswordSetter;\n};\n\n/**\n * One-time token storage configuration (`auth.oneTimeToken`).\n */\nexport type OneTimeTokenConfig = {\n /** Override the persisted model — extend {@link OneTimeToken}. */\n model?: typeof OneTimeToken;\n};\n\nexport type AuthConfigurations = {\n /**\n * Define all user types — maps a user-type slug to its `Auth` model class so\n * tokens and the middleware can resolve the right model.\n */\n userType: {\n [userType: string]: ChildModel<Auth>;\n };\n /** Default user type used by `authMiddleware()` and options-only overloads. */\n defaultUserType?: string;\n /**\n * Decide whether a resolved user may authenticate or receive new tokens.\n * @default () => true\n */\n canAuthenticate?: CanAuthenticate;\n /**\n * How login identifiers are normalized before the user lookup. Default:\n * string values are trimmed and the `email` field is lower-cased, so\n * `\" Sara@x.io\"` finds the account stored as `sara@x.io`. If that finds no\n * user and the normalized value differs from what was sent (trimmed), the\n * lookup is retried once with the value as sent, so rows stored with capitals\n * keep working. Pass a function to normalize your own way (the retry still\n * applies), or `false` for exact matching.\n *\n * The login throttle buckets `email` by trimmed, lower-cased value either way.\n * @default trim string values, lower-case `email`\n */\n normalizeCredentials?: false | NormalizeCredentials;\n /**\n * Access-token configuration (secret, expiry, algorithm, model override).\n */\n accessToken?: AccessTokenConfig;\n /**\n * Refresh-token configuration (rotation, lifetime, cap, model override).\n */\n refreshToken?: RefreshTokenConfig;\n /**\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\n */\n pageAuth?: PageAuthConfig;\n /**\n * Cookie auth session config — read by `authService.setAuthCookie` /\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\n */\n cookie?: CookieAuthConfig;\n /**\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\n */\n csrf?: CsrfConfig;\n /**\n * Email verification — token lifetime, verified field, notification override.\n */\n verification?: EmailVerificationConfig;\n /**\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\n */\n passwordReset?: PasswordResetConfig;\n /**\n * One-time token (verification / reset) storage — model override.\n */\n oneTimeToken?: OneTimeTokenConfig;\n /**\n * Redirect login providers (`google`, `custom`) and account-linking policy.\n */\n providers?: ProvidersConfig;\n /**\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\n */\n passkeys?: PasskeysConfig;\n /**\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\n */\n otp?: OtpConfig;\n /**\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\n */\n jwt?: LegacyJwtConfig;\n};\n\nexport type AccessTokenOutput = {\n /**\n * JWT Token\n */\n token: string;\n /**\n * Exprie time in ISO format UTC time\n */\n expiresAt: string;\n};\n\n/**\n * Token pair returned after login or token refresh\n */\nexport type TokenPair = {\n /**\n * JWT access token (short-lived)\n */\n accessToken: AccessTokenOutput;\n /**\n * JWT refresh token (long-lived)\n */\n refreshToken?: AccessTokenOutput;\n};\n\n/**\n * Device information for session tracking\n */\nexport type DeviceInfo = {\n /**\n * User agent string from request\n */\n userAgent?: string;\n /**\n * Client IP address\n */\n ip?: string;\n /**\n * Optional device identifier\n */\n deviceId?: string;\n /**\n * Token family ID (for rotation tracking)\n * @internal\n */\n familyId?: string;\n /**\n * Access token payload\n */\n payload?: Record<string, unknown>;\n};\n\nexport type LoginResult<UserType extends Auth> = {\n user: UserType;\n tokens: TokenPair;\n};\n\n/** Selects a cookie Domain for one request; return `undefined` for a host-only cookie. */\nexport type CookieDomainResolver = (request: Request) => string | undefined;\n\n/**\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\n * configurable here — they come from core's `secureCookieDefaults()`, the\n * same floor every `response.cookie()` call gets, so a cookie auth session can\n * never be weakened to a laxer policy than the framework default.\n */\nexport type CookieAuthConfig = {\n /**\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\n * `cookie:<name>` token source must match to read it back.\n * @default \"access_token\"\n */\n name?: string;\n /**\n * Cookie name the session helpers write and clear for the refresh token.\n * @default \"refresh_token\"\n */\n refreshName?: string;\n /**\n * Cookie `Path` attribute.\n * @default \"/\"\n */\n path?: string;\n /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */\n cookieDomain?: CookieDomainResolver;\n};\n\n/**\n * CSRF Origin-check configuration. Read via\n * `authConfig.csrf.allowedOrigins()`.\n */\nexport type CsrfConfig = {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * in addition to the request's own origin.\n * @default []\n */\n allowedOrigins?: string[];\n};\n\n/**\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\n * falls back to `auth.cookie.*` config, then the package default. Cookie\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\n * see {@link CookieAuthConfig}.\n */\nexport type SetAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\n path?: string;\n /** Cookie `Domain` attribute. Omit for a host-only cookie. */\n domain?: string;\n /**\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\n * bare token string with no `maxAge` produces a session cookie (cleared\n * when the browser closes).\n */\n maxAge?: number;\n};\n\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\nexport type ClearAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\n path?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
1
+ {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
@@ -1 +1 @@
1
- {"version":3,"file":"auth-provider-sdk-missing.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/auth-provider-sdk-missing.error.ts"],"sourcesContent":["import { ServerError } from \"@warlock.js/core\";\n\n/**\n * A login method needs a vendor SDK that is an optional peer of\n * `@warlock.js/auth` and is not installed. The message names the package and\n * the `warlock add` command that installs it; the resolver failure is kept on\n * `cause`.\n */\nexport class AuthProviderSdkMissingError extends ServerError {\n public constructor(\n public readonly packageName: string,\n public readonly feature: string,\n cause?: unknown,\n ) {\n super(\n `@warlock.js/auth: this login method needs \"${packageName}\", which is not installed — ` +\n `run \\`warlock add ${feature}\\`.`,\n );\n this.name = \"AuthProviderSdkMissingError\";\n this.cause = cause;\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,8BAAb,cAAiD,YAAY;CAC3D,AAAO,YACL,AAAgB,aAChB,AAAgB,SAChB,OACA;EACA,MACE,8CAA8C,YAAY,gDACnC,QAAQ,IACjC;EAPgB;EACA;EAOhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
1
+ {"version":3,"file":"auth-provider-sdk-missing.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/auth-provider-sdk-missing.error.ts"],"mappings":";;;;;;;;;AAQA,IAAa,8BAAb,cAAiD,YAAY;CAC3D,AAAO,YACL,AAAgB,aAChB,AAAgB,SAChB,OACA;EACA,MACE,8CAA8C,YAAY,gDACnC,QAAQ,IACjC;EAPgB;EACA;EAOhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"email-not-verified.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/email-not-verified.error.ts"],"sourcesContent":["import { ForbiddenError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * The authenticated user has not verified their email address. Thrown by\n * `requireVerifiedEmail()`; core's error handler answers it with `403` and a\n * `payload.errorCode` of `EC007`.\n */\nexport class EmailNotVerifiedError extends ForbiddenError {\n public readonly code = AuthErrorCodes.EmailNotVerified;\n\n public constructor(message = \"Email address is not verified.\") {\n super(message, { errorCode: AuthErrorCodes.EmailNotVerified });\n this.name = \"EmailNotVerifiedError\";\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CAGxD,AAAO,YAAY,UAAU,kCAAkC;EAC7D,MAAM,SAAS,EAAE,mBAA2C,CAAC;;EAC7D,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"email-not-verified.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/email-not-verified.error.ts"],"mappings":";;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CAGxD,AAAO,YAAY,UAAU,kCAAkC;EAC7D,MAAM,SAAS,EAAE,mBAA2C,CAAC;;EAC7D,KAAK,OAAO;CACd;AACF"}
@@ -4,5 +4,6 @@ import { InvalidOneTimeTokenError } from "./invalid-one-time-token.error.mjs";
4
4
  import { InvalidPasskeyError } from "./invalid-passkey.error.mjs";
5
5
  import { InvalidProviderCallbackError } from "./invalid-provider-callback.error.mjs";
6
6
  import { NotificationsUnavailableError } from "./notifications-unavailable.error.mjs";
7
+ import { ProviderAccountLinkBlockedError } from "./provider-account-link-blocked.error.mjs";
7
8
  import { ProviderEmailNotVerifiedError } from "./provider-email-not-verified.error.mjs";
8
- export { AuthProviderSdkMissingError, EmailNotVerifiedError, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, NotificationsUnavailableError, ProviderEmailNotVerifiedError };
9
+ export { AuthProviderSdkMissingError, EmailNotVerifiedError, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, NotificationsUnavailableError, ProviderAccountLinkBlockedError, ProviderEmailNotVerifiedError };
@@ -4,6 +4,7 @@ import { InvalidOneTimeTokenError } from "./invalid-one-time-token.error.mjs";
4
4
  import { InvalidPasskeyError } from "./invalid-passkey.error.mjs";
5
5
  import { InvalidProviderCallbackError } from "./invalid-provider-callback.error.mjs";
6
6
  import { NotificationsUnavailableError } from "./notifications-unavailable.error.mjs";
7
+ import { ProviderAccountLinkBlockedError } from "./provider-account-link-blocked.error.mjs";
7
8
  import { ProviderEmailNotVerifiedError } from "./provider-email-not-verified.error.mjs";
8
9
 
9
- export { AuthProviderSdkMissingError, EmailNotVerifiedError, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, NotificationsUnavailableError, ProviderEmailNotVerifiedError };
10
+ export { AuthProviderSdkMissingError, EmailNotVerifiedError, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, NotificationsUnavailableError, ProviderAccountLinkBlockedError, ProviderEmailNotVerifiedError };
@@ -1 +1 @@
1
- {"version":3,"file":"invalid-one-time-token.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-one-time-token.error.ts"],"sourcesContent":["import { BadRequestError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * An email-verification or password-reset token was rejected: unknown, issued\n * for the other purpose, expired, or already consumed (including losing a\n * concurrent consumption race). Deliberately ONE error for all of them, so a\n * caller cannot probe which case applies. Answers `400` with `EC008`.\n */\nexport class InvalidOneTimeTokenError extends BadRequestError {\n public readonly code = AuthErrorCodes.InvalidOneTimeToken;\n\n public constructor(message = \"Invalid or expired token.\") {\n super(message, { errorCode: AuthErrorCodes.InvalidOneTimeToken });\n this.name = \"InvalidOneTimeTokenError\";\n }\n}\n"],"mappings":";;;;;;;;;;AASA,IAAa,2BAAb,cAA8C,gBAAgB;CAG5D,AAAO,YAAY,UAAU,6BAA6B;EACxD,MAAM,SAAS,EAAE,mBAA8C,CAAC;;EAChE,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"invalid-one-time-token.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-one-time-token.error.ts"],"mappings":";;;;;;;;;;AASA,IAAa,2BAAb,cAA8C,gBAAgB;CAG5D,AAAO,YAAY,UAAU,6BAA6B;EACxD,MAAM,SAAS,EAAE,mBAA8C,CAAC;;EAChE,KAAK,OAAO;CACd;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"invalid-passkey.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-passkey.error.ts"],"sourcesContent":["import { BadRequestError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * A passkey registration or authentication was rejected — unknown, expired\n * or used challenge, unknown credential, failed verification, or a signature\n * counter that did not advance. `reason` is for logs; the message stays\n * generic. Answers `400` with `EC011`.\n */\nexport class InvalidPasskeyError extends BadRequestError {\n public readonly code = AuthErrorCodes.InvalidPasskey;\n\n public constructor(\n public readonly reason: string,\n cause?: unknown,\n ) {\n super(\"Passkey verification failed.\", { errorCode: AuthErrorCodes.InvalidPasskey });\n this.name = \"InvalidPasskeyError\";\n this.cause = cause;\n }\n}\n"],"mappings":";;;;;;;;;;AASA,IAAa,sBAAb,cAAyC,gBAAgB;CAGvD,AAAO,YACL,AAAgB,QAChB,OACA;EACA,MAAM,gCAAgC,EAAE,mBAAyC,CAAC;EAHlE;;EAIhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
1
+ {"version":3,"file":"invalid-passkey.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-passkey.error.ts"],"mappings":";;;;;;;;;;AASA,IAAa,sBAAb,cAAyC,gBAAgB;CAGvD,AAAO,YACL,AAAgB,QAChB,OACA;EACA,MAAM,gCAAgC,EAAE,mBAAyC,CAAC;EAHlE;;EAIhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"invalid-provider-callback.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-provider-callback.error.ts"],"sourcesContent":["import { BadRequestError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * A redirect-provider callback was rejected — missing, forged or expired\n * state cookie, `state` mismatch, failed code exchange, or an id_token with a\n * bad signature, issuer, audience, expiry or nonce. `reason` is for logs;\n * the response message stays generic. Answers `400` with `EC009`.\n */\nexport class InvalidProviderCallbackError extends BadRequestError {\n public readonly code = AuthErrorCodes.InvalidProviderCallback;\n\n public constructor(\n public readonly reason: string,\n cause?: unknown,\n ) {\n super(\"Login with the provider failed.\", {\n errorCode: AuthErrorCodes.InvalidProviderCallback,\n });\n this.name = \"InvalidProviderCallbackError\";\n this.cause = cause;\n }\n}\n"],"mappings":";;;;;;;;;;AASA,IAAa,+BAAb,cAAkD,gBAAgB;CAGhE,AAAO,YACL,AAAgB,QAChB,OACA;EACA,MAAM,mCAAmC,EACvC,mBACF,CAAC;EALe;;EAMhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
1
+ {"version":3,"file":"invalid-provider-callback.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-provider-callback.error.ts"],"mappings":";;;;;;;;;;AASA,IAAa,+BAAb,cAAkD,gBAAgB;CAGhE,AAAO,YACL,AAAgB,QAChB,OACA;EACA,MAAM,mCAAmC,EACvC,mBACF,CAAC;EALe;;EAMhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"notifications-unavailable.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/notifications-unavailable.error.ts"],"sourcesContent":["import { ServerError } from \"@warlock.js/core\";\n\n/**\n * Email verification / password reset could not send its notification because\n * `@warlock.js/notifications` is not installed or not configured. Thrown BEFORE\n * any token is issued — auth never issues a token it cannot deliver, and never\n * skips the send silently. The original failure is kept on `cause`.\n */\nexport class NotificationsUnavailableError extends ServerError {\n public constructor(reason: \"not-installed\" | \"not-configured\", cause?: unknown) {\n super(\n reason === \"not-installed\"\n ? \"@warlock.js/auth: email verification and password reset send through \" +\n \"@warlock.js/notifications, which is not installed — add it to the app's dependencies.\"\n : \"@warlock.js/auth: email verification and password reset send through \" +\n \"@warlock.js/notifications, which is not configured — add `src/config/notifications.ts` \" +\n \"with a `mail` channel.\",\n );\n this.name = \"NotificationsUnavailableError\";\n this.cause = cause;\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,gCAAb,cAAmD,YAAY;CAC7D,AAAO,YAAY,QAA4C,OAAiB;EAC9E,MACE,WAAW,kBACP,+JAEA,oLAGN;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
1
+ {"version":3,"file":"notifications-unavailable.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/notifications-unavailable.error.ts"],"mappings":";;;;;;;;;AAQA,IAAa,gCAAb,cAAmD,YAAY;CAC7D,AAAO,YAAY,QAA4C,OAAiB;EAC9E,MACE,WAAW,kBACP,+JAEA,oLAGN;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
@@ -0,0 +1,16 @@
1
+ import { AuthErrorCodes } from "../utils/auth-error-codes.mjs";
2
+ import { ForbiddenError } from "@warlock.js/core";
3
+ //#region ../../packages/auth/src/errors/provider-account-link-blocked.error.d.ts
4
+ /**
5
+ * A provider login found an existing account with the same email, but
6
+ * `auth.providers.linkExisting` does not allow linking it automatically —
7
+ * by default because that account never verified the address. Answers `403`
8
+ * with `EC012`. The user signs in with their password (or verifies their
9
+ * email) first; the provider can then be linked from a signed-in session.
10
+ */
11
+ export declare class ProviderAccountLinkBlockedError extends ForbiddenError {
12
+ readonly code = AuthErrorCodes.ProviderAccountLinkBlocked;
13
+ constructor(message?: string);
14
+ }
15
+ //#endregion
16
+ //# sourceMappingURL=provider-account-link-blocked.error.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-account-link-blocked.error.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/errors/provider-account-link-blocked.error.ts"],"mappings":";;;;;;;;;;qBAUa,wCAAwC;WACnC,OAAI,eAAA;EAEpB,YACE"}
@@ -0,0 +1,22 @@
1
+ import { AuthErrorCodes } from "../utils/auth-error-codes.mjs";
2
+ import { ForbiddenError } from "@warlock.js/core";
3
+
4
+ //#region ../../packages/auth/src/errors/provider-account-link-blocked.error.ts
5
+ /**
6
+ * A provider login found an existing account with the same email, but
7
+ * `auth.providers.linkExisting` does not allow linking it automatically —
8
+ * by default because that account never verified the address. Answers `403`
9
+ * with `EC012`. The user signs in with their password (or verifies their
10
+ * email) first; the provider can then be linked from a signed-in session.
11
+ */
12
+ var ProviderAccountLinkBlockedError = class extends ForbiddenError {
13
+ constructor(message = "An account with this email already exists. Sign in with your password first, then link this provider from your account settings.") {
14
+ super(message, { errorCode: "EC012" });
15
+ this.code = "EC012";
16
+ this.name = "ProviderAccountLinkBlockedError";
17
+ }
18
+ };
19
+
20
+ //#endregion
21
+ export { ProviderAccountLinkBlockedError };
22
+ //# sourceMappingURL=provider-account-link-blocked.error.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-account-link-blocked.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/provider-account-link-blocked.error.ts"],"mappings":";;;;;;;;;;;AAUA,IAAa,kCAAb,cAAqD,eAAe;CAGlE,AAAO,YACL,UAAU,oIACV;EACA,MAAM,SAAS,EAAE,mBAAqD,CAAC;;EACvE,KAAK,OAAO;CACd;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"provider-email-not-verified.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/provider-email-not-verified.error.ts"],"sourcesContent":["import { ForbiddenError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * The provider did not verify the email on a profile with no existing link,\n * so auth refused to link it to (or create) an account. Answers `403` with\n * `EC010`.\n */\nexport class ProviderEmailNotVerifiedError extends ForbiddenError {\n public readonly code = AuthErrorCodes.ProviderEmailNotVerified;\n\n public constructor(message = \"The provider has not verified this email address.\") {\n super(message, { errorCode: AuthErrorCodes.ProviderEmailNotVerified });\n this.name = \"ProviderEmailNotVerifiedError\";\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,gCAAb,cAAmD,eAAe;CAGhE,AAAO,YAAY,UAAU,qDAAqD;EAChF,MAAM,SAAS,EAAE,mBAAmD,CAAC;;EACrE,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"provider-email-not-verified.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/provider-email-not-verified.error.ts"],"mappings":";;;;;;;;;AAQA,IAAa,gCAAb,cAAmD,eAAe;CAGhE,AAAO,YAAY,UAAU,qDAAqD;EAChF,MAAM,SAAS,EAAE,mBAAmD,CAAC;;EACrE,KAAK,OAAO;CACd;AACF"}
package/esm/index.d.mts CHANGED
@@ -4,7 +4,7 @@ import { registerJWTSecretGeneratorCommand } from "./commands/jwt-secret-generat
4
4
  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
- import { AppleProviderConfig, AuthProvider, DiscordProviderConfig, FacebookProviderConfig, GitHubProviderConfig, GoogleProviderConfig, LinkedInProviderConfig, OtpConfig, OtpMessage, OtpSender, PasskeysConfig, ProviderAuthorizationState, ProviderCallbackParams, ProviderProfile, ProviderUserCreator, ProvidersConfig, XProviderConfig } from "./contracts/providers.mjs";
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
8
  import { AccessTokenConfig, AccessTokenOutput, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthMiddlewareOptions, AuthNotification, AuthRefreshCredentialDescriptor, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainResolver, CsrfConfig, DeviceInfo, EmailVerificationConfig, LegacyJwtConfig, LoginResult, LogoutWithoutTokenBehavior, NO_EXPIRATION, NormalizeCredentials, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenUrlBuilder, PageAuthConfig, PasswordResetConfig, PasswordSetter, RefreshTokenConfig, SetAuthCookieOptions, TokenFrom, TokenPair } from "./contracts/types.mjs";
9
9
  import { RefreshToken, RefreshTokenIssueOptions, refreshTokenSchema } from "./models/refresh-token/refresh-token.model.mjs";
10
10
  import { Authenticable } from "./contracts/auth-contract.mjs";
@@ -17,6 +17,7 @@ import { InvalidOneTimeTokenError } from "./errors/invalid-one-time-token.error.
17
17
  import { InvalidPasskeyError } from "./errors/invalid-passkey.error.mjs";
18
18
  import { InvalidProviderCallbackError } from "./errors/invalid-provider-callback.error.mjs";
19
19
  import { NotificationsUnavailableError } from "./errors/notifications-unavailable.error.mjs";
20
+ import { ProviderAccountLinkBlockedError } from "./errors/provider-account-link-blocked.error.mjs";
20
21
  import { ProviderEmailNotVerifiedError } from "./errors/provider-email-not-verified.error.mjs";
21
22
  import "./errors/index.mjs";
22
23
  import { AuthErrorTranslations, AuthTranslations } from "./localization/auth-translations.type.mjs";
@@ -62,5 +63,5 @@ import { PageSessionOptions, PageSessionResolver, SessionMiddlewareOptions, Sess
62
63
  import "./session/index.mjs";
63
64
  import { safeEqual } from "./utils/safe-equal.mjs";
64
65
  import { isNeverExpiring, isUsableExpiry, tokenHasExpClaim } from "./utils/token-expiry.mjs";
65
- export { APPLE_AUTH_FEATURE, AUTH_MIDDLEWARE_DESCRIPTOR, AccessToken, AccessTokenConfig, AccessTokenOutput, AppleJoseModule, AppleProvider, AppleProviderConfig, Auth, AuthConfigurations, AuthCredentialDescriptor, AuthCredentials, AuthErrorCodes, AuthErrorTranslations, AuthEventCallback, AuthEventName, AuthEventPayloads, AuthMiddlewareDescriptor, AuthMiddlewareDescriptorSource, AuthMiddlewareOptions, AuthNotification, AuthProvider, AuthProviderSdkMissingError, AuthRefreshCredentialDescriptor, AuthTokenFamily, AuthTranslations, Authenticable, CanAuthenticate, ClearAuthCookieOptions, CookieAuthConfig, CookieDomainRequestRequiredError, CookieDomainResolver, CsrfConfig, CsrfOriginMismatchError, CsrfOriginMismatchReason, DeviceInfo, DiscordProvider, DiscordProviderConfig, EmailNotVerifiedError, EmailVerificationConfig, FacebookProvider, FacebookProviderConfig, GOOGLE_AUTH_FEATURE, GitHubProvider, GitHubProviderConfig, GoogleProvider, GoogleProviderConfig, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, IssuedOneTimeToken, JoseModule, LINKEDIN_AUTH_FEATURE, LegacyJwtConfig, LinkedInProvider, LinkedInProviderConfig, LoginResult, LoginThrottleIdentifier, LoginThrottleOptions, LogoutWithoutTokenBehavior, NO_EXPIRATION, NormalizeCredentials, NotificationsUnavailableError, OneTimeToken, OneTimeTokenConfig, OneTimeTokenNotificationData, OneTimeTokenPurpose, OneTimeTokenUrlBuilder, OtpConfig, OtpMessage, OtpSender, PageAuthConfig, PageSessionOptions, PageSessionResolver, PasskeyCredential, type PasskeyOptionsJSON, type PasskeyResponseJSON, PasskeysConfig, PasswordResetConfig, PasswordSetter, ProviderAccount, ProviderAuthorizationState, ProviderCallbackParams, ProviderEmailNotVerifiedError, ProviderProfile, ProviderUserCreator, ProvidersConfig, RefreshToken, RefreshTokenConfig, RefreshTokenIssueOptions, RequestUser, RequestUserFailure, RequestUserOutcome, ResolveRequestUserOptions, SessionMiddlewareOptions, SessionResolverOptions, SessionSource, SetAuthCookieOptions, TokenFrom, TokenPair, TokenType, TokenTypeError, XProvider, XProviderConfig, accessTokenSchema, assertCsrfOriginAllowed, authDefaultTranslations, authEvents, authMiddleware, authMigrations, authService, authTokenFamilySchema, completeProviderLogin, consumeOneTimeToken, currentUser, generateJWTSecret, generatePasskeyAuthenticationOptions, generatePasskeyRegistrationOptions, hashOneTimeToken, isEmailVerified, isInvalidCredentialError, isNeverExpiring, isUsableExpiry, issueOneTimeToken, jwt, loginThrottleMiddleware, oneTimeTokenModel, oneTimeTokenSchema, otpRequestThrottleMiddleware, otpVerifyThrottleMiddleware, pageSession, passkeyCredentialSchema, pkceChallenge, providerAccountSchema, readCredential, refreshTokenSchema, registerAuthCleanupCommand, registerAuthPurgeNeverExpiringCommand, registerAuthTranslations, registerJWTSecretGeneratorCommand, requestOtp, requestPasswordReset, requireVerifiedEmail, requiresCsrfOriginCheck, resetPassword, resolveAuthProvider, resolveRequestUser, resolveRequestUserOutcome, safeEqual, sendEmailVerification, sessionMiddleware, startProviderLogin, throttleIdentifierHash, tokenConsumeThrottleMiddleware, tokenHasExpClaim, tokenIssueThrottleMiddleware, verifyEmail, verifyOtp, verifyPasskeyAuthentication, verifyPasskeyRegistration };
66
+ 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
67
  import "./contracts/request-locals.mjs";
package/esm/index.mjs CHANGED
@@ -22,6 +22,7 @@ import { InvalidOneTimeTokenError } from "./errors/invalid-one-time-token.error.
22
22
  import { InvalidPasskeyError } from "./errors/invalid-passkey.error.mjs";
23
23
  import { InvalidProviderCallbackError } from "./errors/invalid-provider-callback.error.mjs";
24
24
  import { NotificationsUnavailableError } from "./errors/notifications-unavailable.error.mjs";
25
+ import { ProviderAccountLinkBlockedError } from "./errors/provider-account-link-blocked.error.mjs";
25
26
  import { ProviderEmailNotVerifiedError } from "./errors/provider-email-not-verified.error.mjs";
26
27
  import "./errors/index.mjs";
27
28
  import "./localization/index.mjs";
@@ -60,4 +61,4 @@ import { pageSession, sessionMiddleware } from "./session/page-session.mjs";
60
61
  import "./session/index.mjs";
61
62
  import "./utils/index.mjs";
62
63
 
63
- export { APPLE_AUTH_FEATURE, AUTH_MIDDLEWARE_DESCRIPTOR, AccessToken, AppleProvider, Auth, AuthErrorCodes, AuthProviderSdkMissingError, AuthTokenFamily, CookieDomainRequestRequiredError, CsrfOriginMismatchError, DiscordProvider, EmailNotVerifiedError, FacebookProvider, GOOGLE_AUTH_FEATURE, GitHubProvider, GoogleProvider, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, LINKEDIN_AUTH_FEATURE, LinkedInProvider, NO_EXPIRATION, NotificationsUnavailableError, OneTimeToken, PasskeyCredential, ProviderAccount, ProviderEmailNotVerifiedError, RefreshToken, TokenTypeError, XProvider, 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 };
64
+ export { APPLE_AUTH_FEATURE, AUTH_MIDDLEWARE_DESCRIPTOR, AccessToken, AppleProvider, Auth, AuthErrorCodes, AuthProviderSdkMissingError, AuthTokenFamily, CookieDomainRequestRequiredError, CsrfOriginMismatchError, DiscordProvider, EmailNotVerifiedError, FacebookProvider, GOOGLE_AUTH_FEATURE, GitHubProvider, GoogleProvider, InvalidOneTimeTokenError, InvalidPasskeyError, InvalidProviderCallbackError, LINKEDIN_AUTH_FEATURE, LinkedInProvider, NO_EXPIRATION, NotificationsUnavailableError, OneTimeToken, PasskeyCredential, ProviderAccount, ProviderAccountLinkBlockedError, ProviderEmailNotVerifiedError, RefreshToken, TokenTypeError, XProvider, 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 };
@@ -1 +1 @@
1
- {"version":3,"file":"ar.translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/ar.translations.ts"],"sourcesContent":["import type { AuthTranslations } from \"./auth-translations.type\";\n\n/**\n * Built-in Arabic text for auth's translation keys. Applications override\n * any of these by registering the same key in their own locale files.\n */\nexport const authArabicTranslations: AuthTranslations = {\n auth: {\n errors: {\n missingAccessToken: \"رمز الوصول مفقود.\",\n invalidAccessToken: \"رمز الوصول غير صالح أو منتهي الصلاحية.\",\n unauthorized: \"غير مصرح لك بالوصول إلى هذا المورد.\",\n csrfOriginMismatch: \"مصدر الطلب غير مسموح به.\",\n tooManyAttempts: \"محاولات كثيرة جدًا. يرجى المحاولة مرة أخرى لاحقًا.\",\n },\n },\n};\n"],"mappings":";;;;;AAMA,MAAa,yBAA2C,EACtD,MAAM,EACJ,QAAQ;CACN,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,oBAAoB;CACpB,iBAAiB;AACnB,EACF,EACF"}
1
+ {"version":3,"file":"ar.translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/ar.translations.ts"],"mappings":";;;;;AAMA,MAAa,yBAA2C,EACtD,MAAM,EACJ,QAAQ;CACN,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,oBAAoB;CACpB,iBAAiB;AACnB,EACF,EACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"auth-default-translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/auth-default-translations.ts"],"sourcesContent":["import { authArabicTranslations } from \"./ar.translations\";\nimport type { AuthTranslations } from \"./auth-translations.type\";\nimport { authEnglishTranslations } from \"./en.translations\";\n\n/**\n * Every locale auth ships default text for, keyed by locale code.\n */\nexport const authDefaultTranslations: Record<string, AuthTranslations> = {\n en: authEnglishTranslations,\n ar: authArabicTranslations,\n};\n"],"mappings":";;;;;;;AAOA,MAAa,0BAA4D;CACvE,IAAI;CACJ,IAAI;AACN"}
1
+ {"version":3,"file":"auth-default-translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/auth-default-translations.ts"],"mappings":";;;;;;;AAOA,MAAa,0BAA4D;CACvE,IAAI;CACJ,IAAI;AACN"}
@@ -1 +1 @@
1
- {"version":3,"file":"en.translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/en.translations.ts"],"sourcesContent":["import type { AuthTranslations } from \"./auth-translations.type\";\n\n/**\n * Built-in English text for auth's translation keys. Applications override\n * any of these by registering the same key in their own locale files.\n */\nexport const authEnglishTranslations: AuthTranslations = {\n auth: {\n errors: {\n missingAccessToken: \"Missing access token.\",\n invalidAccessToken: \"Invalid or expired access token.\",\n unauthorized: \"You are not authorized to access this resource.\",\n csrfOriginMismatch: \"Request origin is not allowed.\",\n tooManyAttempts: \"Too many attempts. Please try again later.\",\n },\n },\n};\n"],"mappings":";;;;;AAMA,MAAa,0BAA4C,EACvD,MAAM,EACJ,QAAQ;CACN,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,oBAAoB;CACpB,iBAAiB;AACnB,EACF,EACF"}
1
+ {"version":3,"file":"en.translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/en.translations.ts"],"mappings":";;;;;AAMA,MAAa,0BAA4C,EACvD,MAAM,EACJ,QAAQ;CACN,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,oBAAoB;CACpB,iBAAiB;AACnB,EACF,EACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"init.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/init.ts"],"sourcesContent":["import { registerAuthTranslations } from \"./register-auth-translations\";\n\n// Side-effect module: importing `@warlock.js/auth` registers its default\n// translations, so `t(\"auth.errors.*\")` never returns the raw key.\nregisterAuthTranslations();\n"],"mappings":";;;AAIA,yBAAyB"}
1
+ {"version":3,"file":"init.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/init.ts"],"mappings":";;;AAIA,yBAAyB"}
@@ -1 +1 @@
1
- {"version":3,"file":"register-auth-translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/register-auth-translations.ts"],"sourcesContent":["import { flatten, get, set } from \"@mongez/reinforcements\";\nimport { extend, getKeywordsListOf, type Keywords } from \"@warlock.js/core\";\nimport { authDefaultTranslations } from \"./auth-default-translations\";\n\n/**\n * Register auth's built-in translations with `@mongez/localization`, the\n * same store `t()` from `@warlock.js/core` reads.\n *\n * Only keys the application has NOT already translated are added, so an app\n * translation wins regardless of load order: registered before this runs, it\n * is left untouched; registered after, `extend()` merges it over the default.\n * An app locale file that predates a newer auth key therefore gets the\n * default text for that key instead of the raw key string.\n *\n * Runs once at import of `@warlock.js/auth`; safe to call again.\n */\nexport function registerAuthTranslations(): void {\n for (const [localeCode, translations] of Object.entries(authDefaultTranslations)) {\n const existing = getKeywordsListOf(localeCode) ?? {};\n const missing: Keywords = {};\n\n for (const [key, text] of Object.entries(flatten(translations))) {\n if (get(existing, key) === undefined) {\n set(missing, key, text);\n }\n }\n\n if (Object.keys(missing).length > 0) {\n extend(localeCode, missing);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,SAAgB,2BAAiC;CAC/C,KAAK,MAAM,CAAC,YAAY,iBAAiB,OAAO,QAAQ,uBAAuB,GAAG;EAChF,MAAM,WAAW,kBAAkB,UAAU,KAAK,CAAC;EACnD,MAAM,UAAoB,CAAC;EAE3B,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,QAAQ,YAAY,CAAC,GAC5D,IAAI,IAAI,UAAU,GAAG,MAAM,QACzB,IAAI,SAAS,KAAK,IAAI;EAI1B,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,GAChC,OAAO,YAAY,OAAO;CAE9B;AACF"}
1
+ {"version":3,"file":"register-auth-translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/register-auth-translations.ts"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,SAAgB,2BAAiC;CAC/C,KAAK,MAAM,CAAC,YAAY,iBAAiB,OAAO,QAAQ,uBAAuB,GAAG;EAChF,MAAM,WAAW,kBAAkB,UAAU,KAAK,CAAC;EACnD,MAAM,UAAoB,CAAC;EAE3B,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,QAAQ,YAAY,CAAC,GAC5D,IAAI,IAAI,UAAU,GAAG,MAAM,QACzB,IAAI,SAAS,KAAK,IAAI;EAI1B,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,GAChC,OAAO,YAAY,OAAO;CAE9B;AACF"}
@@ -85,7 +85,7 @@ function authMiddleware(userTypeOrOptions, legacyTokenFromOrOptions) {
85
85
  assertCsrfOriginAllowed(request);
86
86
  } catch (error) {
87
87
  if (!(error instanceof CsrfOriginMismatchError)) throw error;
88
- log.error("http", "auth", error);
88
+ log.debug("http", "auth", error);
89
89
  return response.forbidden({
90
90
  error: t("auth.errors.csrfOriginMismatch"),
91
91
  errorCode: "EC006"