@warlock.js/auth 5.52.0 → 5.53.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/esm/contracts/index.d.mts +2 -2
  3. package/esm/contracts/providers.d.mts +53 -0
  4. package/esm/contracts/providers.d.mts.map +1 -1
  5. package/esm/contracts/types.d.mts +53 -0
  6. package/esm/contracts/types.d.mts.map +1 -1
  7. package/esm/contracts/types.mjs.map +1 -1
  8. package/esm/errors/index.d.mts +2 -1
  9. package/esm/errors/index.mjs +2 -1
  10. package/esm/errors/provider-account-link-blocked.error.d.mts +16 -0
  11. package/esm/errors/provider-account-link-blocked.error.d.mts.map +1 -0
  12. package/esm/errors/provider-account-link-blocked.error.mjs +22 -0
  13. package/esm/errors/provider-account-link-blocked.error.mjs.map +1 -0
  14. package/esm/index.d.mts +3 -2
  15. package/esm/index.mjs +2 -1
  16. package/esm/middleware/auth.middleware.mjs +1 -1
  17. package/esm/middleware/auth.middleware.mjs.map +1 -1
  18. package/esm/middleware/login-throttle.middleware.d.mts +38 -8
  19. package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
  20. package/esm/middleware/login-throttle.middleware.mjs +93 -29
  21. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  22. package/esm/models/access-token/access-token.model.d.mts +14 -3
  23. package/esm/models/access-token/access-token.model.d.mts.map +1 -1
  24. package/esm/models/access-token/access-token.model.mjs +15 -8
  25. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  26. package/esm/models/auth.model.d.mts +8 -0
  27. package/esm/models/auth.model.d.mts.map +1 -1
  28. package/esm/models/auth.model.mjs +3 -0
  29. package/esm/models/auth.model.mjs.map +1 -1
  30. package/esm/models/one-time-token/one-time-token.model.d.mts +7 -2
  31. package/esm/models/one-time-token/one-time-token.model.d.mts.map +1 -1
  32. package/esm/models/one-time-token/one-time-token.model.mjs +8 -7
  33. package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -1
  34. package/esm/models/refresh-token/refresh-token.model.d.mts +15 -3
  35. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  36. package/esm/models/refresh-token/refresh-token.model.mjs +17 -12
  37. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  38. package/esm/otp/otp.d.mts +5 -1
  39. package/esm/otp/otp.d.mts.map +1 -1
  40. package/esm/otp/otp.mjs +18 -3
  41. package/esm/otp/otp.mjs.map +1 -1
  42. package/esm/passkeys/passkey-authentication.mjs +2 -2
  43. package/esm/passkeys/passkey-authentication.mjs.map +1 -1
  44. package/esm/passkeys/passkey-registration.d.mts.map +1 -1
  45. package/esm/passkeys/passkey-registration.mjs +2 -2
  46. package/esm/passkeys/passkey-registration.mjs.map +1 -1
  47. package/esm/providers/apple-provider.d.mts +2 -0
  48. package/esm/providers/apple-provider.d.mts.map +1 -1
  49. package/esm/providers/apple-provider.mjs +4 -1
  50. package/esm/providers/apple-provider.mjs.map +1 -1
  51. package/esm/providers/discord-provider.d.mts +2 -0
  52. package/esm/providers/discord-provider.d.mts.map +1 -1
  53. package/esm/providers/discord-provider.mjs +7 -1
  54. package/esm/providers/discord-provider.mjs.map +1 -1
  55. package/esm/providers/facebook-provider.d.mts +2 -0
  56. package/esm/providers/facebook-provider.d.mts.map +1 -1
  57. package/esm/providers/facebook-provider.mjs +10 -2
  58. package/esm/providers/facebook-provider.mjs.map +1 -1
  59. package/esm/providers/github-provider.d.mts +2 -0
  60. package/esm/providers/github-provider.d.mts.map +1 -1
  61. package/esm/providers/github-provider.mjs +19 -10
  62. package/esm/providers/github-provider.mjs.map +1 -1
  63. package/esm/providers/linkedin-provider.d.mts +2 -0
  64. package/esm/providers/linkedin-provider.d.mts.map +1 -1
  65. package/esm/providers/linkedin-provider.mjs +4 -1
  66. package/esm/providers/linkedin-provider.mjs.map +1 -1
  67. package/esm/providers/provider-timeout.mjs +17 -0
  68. package/esm/providers/provider-timeout.mjs.map +1 -0
  69. package/esm/providers/resolve-provider-user.mjs +21 -1
  70. package/esm/providers/resolve-provider-user.mjs.map +1 -1
  71. package/esm/providers/x-provider.d.mts +2 -0
  72. package/esm/providers/x-provider.d.mts.map +1 -1
  73. package/esm/providers/x-provider.mjs +7 -1
  74. package/esm/providers/x-provider.mjs.map +1 -1
  75. package/esm/services/auth-config.mjs +65 -6
  76. package/esm/services/auth-config.mjs.map +1 -1
  77. package/esm/services/auth-cookie-names.mjs +49 -0
  78. package/esm/services/auth-cookie-names.mjs.map +1 -0
  79. package/esm/services/auth-events.d.mts +4 -0
  80. package/esm/services/auth-events.d.mts.map +1 -1
  81. package/esm/services/auth-events.mjs.map +1 -1
  82. package/esm/services/auth.service.d.mts +8 -0
  83. package/esm/services/auth.service.d.mts.map +1 -1
  84. package/esm/services/auth.service.mjs +146 -20
  85. package/esm/services/auth.service.mjs.map +1 -1
  86. package/esm/services/jwt.d.mts.map +1 -1
  87. package/esm/services/jwt.mjs +92 -10
  88. package/esm/services/jwt.mjs.map +1 -1
  89. package/esm/services/password-reset.d.mts +5 -0
  90. package/esm/services/password-reset.d.mts.map +1 -1
  91. package/esm/services/password-reset.mjs +15 -1
  92. package/esm/services/password-reset.mjs.map +1 -1
  93. package/esm/services/resolve-request-user.d.mts.map +1 -1
  94. package/esm/services/resolve-request-user.mjs +17 -3
  95. package/esm/services/resolve-request-user.mjs.map +1 -1
  96. package/esm/session/page-session.d.mts.map +1 -1
  97. package/esm/session/page-session.mjs +5 -3
  98. package/esm/session/page-session.mjs.map +1 -1
  99. package/esm/utils/auth-error-codes.d.mts +8 -1
  100. package/esm/utils/auth-error-codes.d.mts.map +1 -1
  101. package/esm/utils/auth-error-codes.mjs +7 -0
  102. package/esm/utils/auth-error-codes.mjs.map +1 -1
  103. package/esm/utils/token-digest.mjs +47 -0
  104. package/esm/utils/token-digest.mjs.map +1 -0
  105. package/esm/utils/token-expiry.d.mts +3 -1
  106. package/esm/utils/token-expiry.d.mts.map +1 -1
  107. package/esm/utils/token-expiry.mjs +7 -2
  108. package/esm/utils/token-expiry.mjs.map +1 -1
  109. package/llms-full.txt +70 -30
  110. package/llms.txt +2 -2
  111. package/package.json +9 -9
  112. package/skills/auth-basics/SKILL.md +9 -0
  113. package/skills/customize-token-storage/SKILL.md +10 -10
  114. package/skills/login-with-providers/SKILL.md +14 -3
  115. package/skills/manage-tokens/SKILL.md +6 -0
  116. package/skills/protect-routes/SKILL.md +5 -0
  117. package/skills/throttle-login-attempts/SKILL.md +23 -17
  118. 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,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,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;;;;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"],"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 * Issuer (`iss` claim) stamped on every access and refresh token this app\n * signs, and required on every token it accepts. Set it when several apps\n * or services share a signing secret, so a token minted by one is refused\n * by the others. Unset (the default) ⇒ no `iss` is stamped or checked.\n *\n * Tokens signed before it was set carry no `iss` and are refused once it is\n * set, so every signed-in user signs in again once.\n * @example \"https://api.example.com\"\n */\n issuer?: string;\n /**\n * Audience (`aud` claim) stamped on every token this app signs, and\n * required on every token it accepts (a token matches when its `aud`\n * includes one of the values). Unset (the default) ⇒ no `aud` is stamped or\n * checked. Like `issuer`, setting it signs everyone out once.\n * @example \"web-app\"\n */\n audience?: string | string[];\n};\n\n/**\n * Refresh-token configuration.\n */\nexport type RefreshTokenConfig = {\n /**\n * Override the persisted refresh-token model — extend {@link RefreshToken}.\n * Defaults to the package's `RefreshToken`.\n */\n model?: typeof RefreshToken;\n /**\n * Enable refresh tokens.\n * @default true\n */\n enabled?: boolean;\n /**\n * Separate secret for refresh tokens (recommended for security). Falls back\n * to the access-token secret when omitted.\n */\n secret?: string;\n /**\n * Refresh-token lifetime — a duration string `ms` parses to a **positive**\n * number of milliseconds; an unusable value throws naming this key on issue\n * (see {@link AccessTokenConfig.expiresIn}).\n * @example \"7d\" or \"1w\"\n * @default \"7d\"\n */\n expiresIn?: string;\n /**\n * Rotate the refresh token on each use (old token revoked, replay detected).\n * @default true\n */\n rotation?: boolean;\n /**\n * Maximum active refresh tokens per user; the oldest are revoked past it.\n * @default 5\n */\n maxPerUser?: number;\n /**\n * Behavior when logout is called without a refresh token.\n * @default \"revoke-all\"\n */\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n};\n\n/**\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\n * deprecation warning.\n *\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\n */\nexport type LegacyJwtConfig = {\n secret?: string;\n algorithm?: Algorithm;\n expiresIn?: string;\n refresh?: {\n secret?: string;\n enabled?: boolean;\n expiresIn?: string;\n rotation?: boolean;\n maxPerUser?: number;\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n };\n};\n\n/**\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\n * to a login page instead of returning the API-style JSON 401.\n *\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\n * always keep the JSON 401 contract regardless of this setting.\n */\nexport type PageAuthConfig = {\n /**\n * Login path a guarded page route redirects a logged-out browser to (e.g.\n * `\"/login\"`). Unset ⇒ page-route auth failures keep the JSON 401, so the\n * behavior is opt-in and backward-compatible.\n */\n loginPath?: string;\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed.\n * @default \"returnUrl\"\n */\n returnUrlParam?: string;\n};\n\n/**\n * Data every email-verification / password-reset notification receives.\n */\nexport type OneTimeTokenNotificationData = {\n /** The raw token — the only place it exists; only its SHA-256 hash is stored. */\n token: string;\n /** When the token stops working. */\n expiresAt: Date;\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\n url?: string;\n};\n\n/**\n * Anything auth can deliver a token through — a `defineNotification(...)`\n * result satisfies it, as does any object with a compatible `send`.\n */\nexport type AuthNotification = {\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\n};\n\n/** Builds the link a token notification points at. */\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\n\n/** Persists a new plaintext password for a user during a password reset. */\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\n\n/**\n * Email-verification configuration (`auth.verification`).\n */\nexport type EmailVerificationConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"24h\"\n */\n expiresIn?: string;\n /**\n * User attribute stamped with the verification `Date`. Declare it in the\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\n * @default \"emailVerifiedAt\"\n */\n field?: string;\n /** Replace the default verification email. */\n notification?: AuthNotification;\n /** Build the verification link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n};\n\n/**\n * Password-reset configuration (`auth.passwordReset`).\n */\nexport type PasswordResetConfig = {\n /**\n * Token lifetime — a positive `ms` duration string.\n * @default \"60m\"\n */\n expiresIn?: string;\n /**\n * User attribute `requestPasswordReset` looks the account up by.\n * @default \"email\"\n */\n identifierField?: string;\n /** Replace the default reset email. */\n notification?: AuthNotification;\n /** Build the reset link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n /**\n * Persist the new password yourself. By default auth saves a hash made by\n * the same `hashPassword` login verifies against, and falls back to the\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\n * the stored value with `verifyPassword` either way.\n */\n setPassword?: PasswordSetter;\n /**\n * Wait for the reset notification before `requestPasswordReset` resolves,\n * so a delivery error reaches the caller. Off by default: the notification\n * is sent in the background, so the response time does not reveal whether\n * the account exists. A background failure is logged and emitted as\n * `password.resetDeliveryFailed`.\n * @default false\n */\n awaitDelivery?: boolean;\n};\n\n/**\n * One-time token storage configuration (`auth.oneTimeToken`).\n */\nexport type OneTimeTokenConfig = {\n /** Override the persisted model — extend {@link OneTimeToken}. */\n model?: typeof OneTimeToken;\n};\n\nexport type AuthConfigurations = {\n /**\n * Define all user types — maps a user-type slug to its `Auth` model class so\n * tokens and the middleware can resolve the right model.\n */\n userType: {\n [userType: string]: ChildModel<Auth>;\n };\n /** Default user type used by `authMiddleware()` and options-only overloads. */\n defaultUserType?: string;\n /**\n * Decide whether a resolved user may authenticate or receive new tokens.\n * @default () => true\n */\n canAuthenticate?: CanAuthenticate;\n /**\n * How login identifiers are normalized before the user lookup. Default:\n * string values are trimmed and the `email` field is lower-cased, so\n * `\" Sara@x.io\"` finds the account stored as `sara@x.io`. If that finds no\n * user and the normalized value differs from what was sent (trimmed), the\n * lookup is retried once with the value as sent, so rows stored with capitals\n * keep working. Pass a function to normalize your own way (the retry still\n * applies), or `false` for exact matching.\n *\n * The login throttle buckets `email` by trimmed, lower-cased value either way.\n * @default trim string values, lower-case `email`\n */\n normalizeCredentials?: false | NormalizeCredentials;\n /**\n * Store only a SHA-256 digest of each access and refresh token in the\n * database, never the token itself, so a copy of the token tables (a\n * backup, a replica, a read-only injection) cannot be replayed as a login.\n *\n * No migration is needed: the digest goes in the existing `token` column,\n * and lookups accept both forms, so rows issued before the switch keep\n * working until they expire, and turning it off again signs no one out.\n * A row loaded from storage no longer carries its raw token; a freshly\n * issued one exposes it as `row.plainToken`.\n * @default false\n */\n hashTokensAtRest?: boolean;\n /**\n * Access-token configuration (secret, expiry, algorithm, model override).\n */\n accessToken?: AccessTokenConfig;\n /**\n * Refresh-token configuration (rotation, lifetime, cap, model override).\n */\n refreshToken?: RefreshTokenConfig;\n /**\n * Page-route auth-failure behavior — set `loginPath` to redirect a logged-out\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\n */\n pageAuth?: PageAuthConfig;\n /**\n * Cookie auth session config — read by `authService.setAuthCookie` /\n * `clearAuthCookie`. Opt-in: unset ⇒ the helpers fall back to their own\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\n */\n cookie?: CookieAuthConfig;\n /**\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\n */\n csrf?: CsrfConfig;\n /**\n * Email verification — token lifetime, verified field, notification override.\n */\n verification?: EmailVerificationConfig;\n /**\n * Password reset — token lifetime, lookup field, notification and password-writer overrides.\n */\n passwordReset?: PasswordResetConfig;\n /**\n * One-time token (verification / reset) storage — model override.\n */\n oneTimeToken?: OneTimeTokenConfig;\n /**\n * Redirect login providers (`google`, `custom`) and account-linking policy.\n */\n providers?: ProvidersConfig;\n /**\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\n */\n passkeys?: PasskeysConfig;\n /**\n * Phone one-time-code login — channel, lifetime, attempts, delivery.\n */\n otp?: OtpConfig;\n /**\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\n */\n jwt?: LegacyJwtConfig;\n};\n\nexport type AccessTokenOutput = {\n /**\n * JWT Token\n */\n token: string;\n /**\n * Exprie time in ISO format UTC time\n */\n expiresAt: string;\n};\n\n/**\n * Token pair returned after login or token refresh\n */\nexport type TokenPair = {\n /**\n * JWT access token (short-lived)\n */\n accessToken: AccessTokenOutput;\n /**\n * JWT refresh token (long-lived)\n */\n refreshToken?: AccessTokenOutput;\n};\n\n/**\n * Device information for session tracking\n */\nexport type DeviceInfo = {\n /**\n * User agent string from request\n */\n userAgent?: string;\n /**\n * Client IP address\n */\n ip?: string;\n /**\n * Optional device identifier\n */\n deviceId?: string;\n /**\n * Token family ID (for rotation tracking)\n * @internal\n */\n familyId?: string;\n /**\n * Access token payload\n */\n payload?: Record<string, unknown>;\n};\n\nexport type LoginResult<UserType extends Auth> = {\n user: UserType;\n tokens: TokenPair;\n};\n\n/** Selects a cookie Domain for one request; return `undefined` for a host-only cookie. */\nexport type CookieDomainResolver = (request: Request) => string | undefined;\n\n/**\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\n * configurable here — they come from core's `secureCookieDefaults()`, the\n * same floor every `response.cookie()` call gets, so a cookie auth session can\n * never be weakened to a laxer policy than the framework default.\n */\nexport type CookieAuthConfig = {\n /**\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\n * `cookie:<name>` token source must match to read it back.\n * @default \"access_token\"\n */\n name?: string;\n /**\n * Cookie name the session helpers write and clear for the refresh token.\n * @default \"refresh_token\"\n */\n refreshName?: string;\n /**\n * Cookie `Path` attribute.\n * @default \"/\"\n */\n path?: string;\n /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */\n cookieDomain?: CookieDomainResolver;\n /**\n * Write the auth cookies under a `__Host-` name prefix (`__Host-access_token`,\n * `__Host-refresh_token`). Browsers accept such a cookie only when it is\n * Secure, has `Path=/` and no `Domain`, so a subdomain or a plain-HTTP page\n * cannot plant or overwrite the session cookie. Requires `path: \"/\"` and no\n * `cookieDomain`; a write that breaks either rule throws naming the setting.\n *\n * While switching, the unprefixed cookie is still read (so signed-in users\n * stay signed in) and both names are cleared on logout.\n * @default false\n */\n hostPrefix?: boolean;\n};\n\n/**\n * CSRF Origin-check configuration. Read via\n * `authConfig.csrf.allowedOrigins()`.\n */\nexport type CsrfConfig = {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * in addition to the request's own origin.\n * @default []\n */\n allowedOrigins?: string[];\n};\n\n/**\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\n * falls back to `auth.cookie.*` config, then the package default. Cookie\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here —\n * see {@link CookieAuthConfig}.\n */\nexport type SetAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\n path?: string;\n /** Cookie `Domain` attribute. Omit for a host-only cookie. */\n domain?: string;\n /**\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\n * bare token string with no `maxAge` produces a session cookie (cleared\n * when the browser closes).\n */\n maxAge?: number;\n};\n\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\nexport type ClearAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\n path?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
@@ -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 };
@@ -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"],"sourcesContent":["import { ForbiddenError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * A provider login found an existing account with the same email, but\n * `auth.providers.linkExisting` does not allow linking it automatically —\n * by default because that account never verified the address. Answers `403`\n * with `EC012`. The user signs in with their password (or verifies their\n * email) first; the provider can then be linked from a signed-in session.\n */\nexport class ProviderAccountLinkBlockedError extends ForbiddenError {\n public readonly code = AuthErrorCodes.ProviderAccountLinkBlocked;\n\n public constructor(\n message = \"An account with this email already exists. Sign in with your password first, then link this provider from your account settings.\",\n ) {\n super(message, { errorCode: AuthErrorCodes.ProviderAccountLinkBlocked });\n this.name = \"ProviderAccountLinkBlockedError\";\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,IAAa,kCAAb,cAAqD,eAAe;CAGlE,AAAO,YACL,UAAU,oIACV;EACA,MAAM,SAAS,EAAE,mBAAqD,CAAC;;EACvE,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 };
@@ -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"
@@ -1 +1 @@
1
- {"version":3,"file":"auth.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/auth.middleware.ts"],"sourcesContent":["import { config, type HttpContext, markAuthGuard, t, type Middleware } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport type {\n AuthCredentialDescriptor,\n AuthMiddlewareOptions,\n TokenFrom,\n} from \"../contracts/types\";\nimport { authConfig } from \"../services/auth-config\";\nimport { readCredential, resolveRequestUserOutcome } from \"../services/resolve-request-user\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport {\n assertCsrfOriginAllowed,\n CsrfOriginMismatchError,\n requiresCsrfOriginCheck,\n} from \"./csrf-origin-check\";\nimport { localizedLoginPath } from \"./localized-login-path\";\n\n/**\n * Well-known symbol under which `authMiddleware()` tags the middleware it\n * returns. Shared via the global symbol registry so other packages can read the\n * descriptor structurally (`Symbol.for(\"warlock.auth\")`) without importing auth.\n */\nexport const AUTH_MIDDLEWARE_DESCRIPTOR = Symbol.for(\"warlock.auth\");\n\n/** A credential source an auth middleware reads: the Authorization header or a named cookie. */\nexport type AuthMiddlewareDescriptorSource = \"header\" | { cookie: string };\n\n/**\n * Frozen, JSON-safe description of how an `authMiddleware()` instance\n * authenticates, stored (non-enumerably) under {@link AUTH_MIDDLEWARE_DESCRIPTOR}.\n */\nexport type AuthMiddlewareDescriptor = {\n /** Resolved credential sources; with dual sources the header comes first. */\n sources: AuthMiddlewareDescriptorSource[];\n required?: boolean;\n /** Resolved allowed user types; an empty array means any authenticated user. */\n userTypes: string[];\n};\n\n/** The 401 body shape every rejection in this middleware carries. */\ntype UnauthorizedPayload = { error: string; errorCode: string };\n\n/**\n * Reject an unauthenticated request, choosing the representation by ROUTE KIND.\n *\n * An API route always gets the JSON 401 it has always gotten. A PAGE route\n * (`request.route.isPage` — the React-SSR pages) instead redirects a logged-out\n * browser to the configured login path with a `returnUrl`, so a human\n * navigating to a guarded page lands on the login screen rather than reading a\n * raw JSON error blob — the defect in finding b9ab9804.\n *\n * The redirect is OPT-IN and backward-compatible: with no `auth.pageAuth.loginPath`\n * configured, even a page route falls back to the JSON 401, so an app that has\n * not asked for page-login UX keeps exactly its current behavior. The API 401\n * contract is never changed for API routes.\n *\n * `returnUrl` carries `request.url` — the relative path + query the browser was\n * on — never the absolute URL: a relative target cannot be turned into an\n * open-redirect off this app's origin.\n */\nfunction rejectUnauthorized(\n { request, response }: HttpContext,\n payload: UnauthorizedPayload,\n redirect?: AuthMiddlewareOptions[\"redirect\"],\n) {\n const loginPath = redirect?.to ?? authConfig.pageAuth.loginPath();\n const returnUrlParam = redirect?.returnUrlParam ?? authConfig.pageAuth.returnUrlParam();\n\n if (loginPath && request.route?.isPage) {\n // Under an active `web.localeRouting` strategy, the login destination\n // itself must carry the request's locale prefix — otherwise an anonymous\n // `/ar/admin` bounces to the DEFAULT locale's `/login` rather than\n // `/ar/login`, even though `returnUrl` below correctly points back at\n // `/ar/admin`. See `./localized-login-path.ts`.\n const destination = localizedLoginPath(loginPath, request.locale);\n const separator = destination.includes(\"?\") ? \"&\" : \"?\";\n const returnUrl = encodeURIComponent(request.url);\n\n return response.redirect(`${destination}${separator}${returnUrlParam}=${returnUrl}`);\n }\n\n return response.unauthorized(payload);\n}\n\nfunction tokenFromDescriptor(descriptor: Partial<AuthCredentialDescriptor>): TokenFrom {\n if (!descriptor.source || descriptor.source === \"header\") return \"header\";\n\n if (!descriptor.key) {\n throw new Error(\"authMiddleware cookie credentials require a cookie key.\");\n }\n\n return `cookie:${descriptor.key}`;\n}\n\nfunction descriptorSource(tokenFrom: TokenFrom): AuthMiddlewareDescriptorSource {\n return tokenFrom === \"header\" ? \"header\" : { cookie: tokenFrom.slice(\"cookie:\".length) };\n}\n\nfunction resolveAllowedTypes(value: string | string[] | undefined): string[] {\n if (value !== undefined) return Array.isArray(value) ? value : [value];\n\n const configuredDefault = config.key(\"auth.defaultUserType\") as string | undefined;\n\n if (configuredDefault) return [configuredDefault];\n\n const userTypes = config.key(\"auth.userType\", {}) as Record<string, unknown>;\n const configuredTypes = Object.keys(userTypes);\n\n if (configuredTypes.length === 1) return configuredTypes;\n\n throw new Error(\n \"authMiddleware requires a user type when auth.defaultUserType is unset and multiple user types exist.\",\n );\n}\n\n/**\n * Build a route gate. Authentication is required unless optional is explicit.\n *\n * An omitted user type selects the configured default; an explicit argument\n * selects which user types may pass:\n * - `[]` — any authenticated user (token required, type not checked).\n * - `\"admin\"` / `[\"admin\", \"staff\"]` — token required AND the user's\n * `userType` must be one of the listed types.\n *\n * `{ optional: true }` allows anonymous requests. All other forms reject\n * missing or invalid credentials with 401, or a configured page redirect.\n *\n * `tokenFrom` selects one credential source and defaults to `\"header\"`.\n * A single source avoids making credential precedence depend on array order.\n *\n * @example\n * router.get(\"/account\", authMiddleware([]), accountController);\n * router.get(\"/admin\", authMiddleware(\"admin\"), adminController);\n * router.get(\"/back-office\", authMiddleware([\"admin\", \"staff\"]), backOfficeController);\n * router.get(\"/browser-account\", authMiddleware([], \"cookie:token\"), accountController);\n */\nexport function authMiddleware(): Middleware;\nexport function authMiddleware(options: AuthMiddlewareOptions): Middleware;\nexport function authMiddleware(\n allowedUserType: string | string[],\n options?: AuthMiddlewareOptions,\n): Middleware;\nexport function authMiddleware(\n allowedUserType: string | string[],\n tokenFrom?: TokenFrom,\n): Middleware;\nexport function authMiddleware(\n userTypeOrOptions?: string | string[] | AuthMiddlewareOptions,\n legacyTokenFromOrOptions?: TokenFrom | AuthMiddlewareOptions,\n): Middleware {\n const options =\n typeof userTypeOrOptions === \"object\" && !Array.isArray(userTypeOrOptions)\n ? userTypeOrOptions\n : typeof legacyTokenFromOrOptions === \"object\"\n ? legacyTokenFromOrOptions\n : undefined;\n const selectedUserType =\n typeof userTypeOrOptions === \"string\" || Array.isArray(userTypeOrOptions)\n ? userTypeOrOptions\n : undefined;\n const allowedTypes = resolveAllowedTypes(selectedUserType);\n const legacyTokenFrom =\n typeof legacyTokenFromOrOptions === \"string\" ? legacyTokenFromOrOptions : undefined;\n const dualSources = options?.sources?.length\n ? options.sources.map(tokenFromDescriptor)\n : undefined;\n\n if (dualSources && options?.source) {\n throw new Error(\"authMiddleware accepts either `source` or `sources`, not both.\");\n }\n\n const dualHeader = dualSources?.includes(\"header\") ?? false;\n const dualCookies = dualSources?.filter((source) => source !== \"header\") ?? [];\n\n if (dualSources && (dualCookies.length > 1 || dualSources.length - dualCookies.length > 1)) {\n throw new Error(\"authMiddleware `sources` accepts at most one header and one cookie.\");\n }\n\n // With dual sources the configured cookie is the base credential; the header\n // is chosen per request, ahead of it.\n const cookieTokenFrom: TokenFrom = dualSources\n ? (dualCookies[0] ?? \"header\")\n : options\n ? tokenFromDescriptor(options)\n : (legacyTokenFrom ?? \"header\");\n const tokenFrom = cookieTokenFrom;\n const refreshCredential = options?.refresh ? tokenFromDescriptor(options.refresh) : undefined;\n const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : undefined;\n\n if (\n refreshCredential &&\n (tokenFrom === \"header\" || refreshCredential === \"header\" || !renewalUserType)\n ) {\n throw new Error(\n \"authMiddleware automatic renewal requires one allowed user type and cookie access and refresh credentials.\",\n );\n }\n\n const optional = options?.optional === true;\n\n const auth: Middleware = async ({ request, response }) => {\n const reject = (payload: UnauthorizedPayload) =>\n rejectUnauthorized({ request, response }, payload, options?.redirect);\n\n // A present Authorization header always wins and never falls back to the\n // cookie: the credential used is the header, so no renewal and no CSRF check.\n const headerWins = dualHeader && Boolean(request.authorizationValue);\n const usedTokenFrom: TokenFrom = headerWins ? \"header\" : tokenFrom;\n const usedRefresh = headerWins ? undefined : refreshCredential;\n\n // Renewal can mint cookies, so a cookie-authenticated unsafe request must\n // pass the same CSRF check even when its access cookie is missing.\n if (\n (readCredential(request, usedTokenFrom) ||\n (usedRefresh && readCredential(request, usedRefresh))) &&\n requiresCsrfOriginCheck(usedTokenFrom, request.method)\n ) {\n try {\n assertCsrfOriginAllowed(request);\n } catch (error) {\n if (!(error instanceof CsrfOriginMismatchError)) throw error;\n\n log.error(\"http\", \"auth\", error);\n return response.forbidden({\n error: t(\"auth.errors.csrfOriginMismatch\"),\n errorCode: AuthErrorCodes.CsrfOriginMismatch,\n });\n }\n }\n\n const outcome = await resolveRequestUserOutcome(request, response, {\n tokenFrom: usedTokenFrom,\n refreshCredential: usedRefresh,\n overlapMs: options?.refresh?.overlapMs,\n allowedTypes,\n renewalUserType,\n });\n\n if (outcome.user) {\n request.locals.user = outcome.user;\n return;\n }\n\n if (outcome.failure === \"forbidden\") {\n return response.forbidden({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n }\n\n if (optional) return;\n\n if (outcome.failure === \"missing\") {\n return reject({\n error: t(\"auth.errors.missingAccessToken\"),\n errorCode: AuthErrorCodes.MissingAccessToken,\n });\n }\n\n if (outcome.failure === \"unauthorized\") {\n return reject({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n }\n\n return reject({\n error: t(\"auth.errors.invalidAccessToken\"),\n errorCode: AuthErrorCodes.InvalidAccessToken,\n });\n };\n\n const descriptorSources: AuthMiddlewareDescriptorSource[] = dualSources\n ? [...(dualHeader ? ([\"header\"] as const) : []), ...dualCookies.map(descriptorSource)]\n : [descriptorSource(tokenFrom)];\n const descriptor: AuthMiddlewareDescriptor = Object.freeze({\n ...(optional ? { required: false } : {}),\n sources: Object.freeze(\n descriptorSources.map((source) =>\n typeof source === \"string\" ? source : Object.freeze({ ...source }),\n ),\n ) as AuthMiddlewareDescriptorSource[],\n userTypes: Object.freeze([...allowedTypes]) as string[],\n });\n\n // Non-enumerable so the tag never shows up in logs, spreads or JSON.\n Object.defineProperty(auth, AUTH_MIDDLEWARE_DESCRIPTOR, { value: descriptor, enumerable: false });\n\n // Tells `warlock dev` and `warlock inspect` that routes behind this\n // middleware are authenticated. `{ optional: true }`\n // lets anonymous requests through, so it does not count as a guard.\n return markAuthGuard(auth, !optional);\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,6BAA6B,OAAO,IAAI,cAAc;;;;;;;;;;;;;;;;;;;AAsCnE,SAAS,mBACP,EAAE,SAAS,YACX,SACA,UACA;CACA,MAAM,YAAY,UAAU,MAAM,WAAW,SAAS,UAAU;CAChE,MAAM,iBAAiB,UAAU,kBAAkB,WAAW,SAAS,eAAe;CAEtF,IAAI,aAAa,QAAQ,OAAO,QAAQ;EAMtC,MAAM,cAAc,mBAAmB,WAAW,QAAQ,MAAM;EAChE,MAAM,YAAY,YAAY,SAAS,GAAG,IAAI,MAAM;EACpD,MAAM,YAAY,mBAAmB,QAAQ,GAAG;EAEhD,OAAO,SAAS,SAAS,GAAG,cAAc,YAAY,eAAe,GAAG,WAAW;CACrF;CAEA,OAAO,SAAS,aAAa,OAAO;AACtC;AAEA,SAAS,oBAAoB,YAA0D;CACrF,IAAI,CAAC,WAAW,UAAU,WAAW,WAAW,UAAU,OAAO;CAEjE,IAAI,CAAC,WAAW,KACd,MAAM,IAAI,MAAM,yDAAyD;CAG3E,OAAO,UAAU,WAAW;AAC9B;AAEA,SAAS,iBAAiB,WAAsD;CAC9E,OAAO,cAAc,WAAW,WAAW,EAAE,QAAQ,UAAU,MAAM,CAAgB,EAAE;AACzF;AAEA,SAAS,oBAAoB,OAAgD;CAC3E,IAAI,UAAU,QAAW,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;CAErE,MAAM,oBAAoB,OAAO,IAAI,sBAAsB;CAE3D,IAAI,mBAAmB,OAAO,CAAC,iBAAiB;CAEhD,MAAM,YAAY,OAAO,IAAI,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AC,GAAG,YAAY,CAAC;CAC5C,CAAC;CAGD,OAAO,eAAe,MAAM,4BAA4B;EAAE,OAAO;EAAY,YAAY;CAAM,CAAC;CAKhG,OAAO,cAAc,MAAM,CAAC,QAAQ;AACtC"}
1
+ {"version":3,"file":"auth.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/auth.middleware.ts"],"sourcesContent":["import { config, type HttpContext, markAuthGuard, t, type Middleware } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport type {\n AuthCredentialDescriptor,\n AuthMiddlewareOptions,\n TokenFrom,\n} from \"../contracts/types\";\nimport { authConfig } from \"../services/auth-config\";\nimport { readCredential, resolveRequestUserOutcome } from \"../services/resolve-request-user\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport {\n assertCsrfOriginAllowed,\n CsrfOriginMismatchError,\n requiresCsrfOriginCheck,\n} from \"./csrf-origin-check\";\nimport { localizedLoginPath } from \"./localized-login-path\";\n\n/**\n * Well-known symbol under which `authMiddleware()` tags the middleware it\n * returns. Shared via the global symbol registry so other packages can read the\n * descriptor structurally (`Symbol.for(\"warlock.auth\")`) without importing auth.\n */\nexport const AUTH_MIDDLEWARE_DESCRIPTOR = Symbol.for(\"warlock.auth\");\n\n/** A credential source an auth middleware reads: the Authorization header or a named cookie. */\nexport type AuthMiddlewareDescriptorSource = \"header\" | { cookie: string };\n\n/**\n * Frozen, JSON-safe description of how an `authMiddleware()` instance\n * authenticates, stored (non-enumerably) under {@link AUTH_MIDDLEWARE_DESCRIPTOR}.\n */\nexport type AuthMiddlewareDescriptor = {\n /** Resolved credential sources; with dual sources the header comes first. */\n sources: AuthMiddlewareDescriptorSource[];\n required?: boolean;\n /** Resolved allowed user types; an empty array means any authenticated user. */\n userTypes: string[];\n};\n\n/** The 401 body shape every rejection in this middleware carries. */\ntype UnauthorizedPayload = { error: string; errorCode: string };\n\n/**\n * Reject an unauthenticated request, choosing the representation by ROUTE KIND.\n *\n * An API route always gets the JSON 401 it has always gotten. A PAGE route\n * (`request.route.isPage` — the React-SSR pages) instead redirects a logged-out\n * browser to the configured login path with a `returnUrl`, so a human\n * navigating to a guarded page lands on the login screen rather than reading a\n * raw JSON error blob — the defect in finding b9ab9804.\n *\n * The redirect is OPT-IN and backward-compatible: with no `auth.pageAuth.loginPath`\n * configured, even a page route falls back to the JSON 401, so an app that has\n * not asked for page-login UX keeps exactly its current behavior. The API 401\n * contract is never changed for API routes.\n *\n * `returnUrl` carries `request.url` — the relative path + query the browser was\n * on — never the absolute URL: a relative target cannot be turned into an\n * open-redirect off this app's origin.\n */\nfunction rejectUnauthorized(\n { request, response }: HttpContext,\n payload: UnauthorizedPayload,\n redirect?: AuthMiddlewareOptions[\"redirect\"],\n) {\n const loginPath = redirect?.to ?? authConfig.pageAuth.loginPath();\n const returnUrlParam = redirect?.returnUrlParam ?? authConfig.pageAuth.returnUrlParam();\n\n if (loginPath && request.route?.isPage) {\n // Under an active `web.localeRouting` strategy, the login destination\n // itself must carry the request's locale prefix — otherwise an anonymous\n // `/ar/admin` bounces to the DEFAULT locale's `/login` rather than\n // `/ar/login`, even though `returnUrl` below correctly points back at\n // `/ar/admin`. See `./localized-login-path.ts`.\n const destination = localizedLoginPath(loginPath, request.locale);\n const separator = destination.includes(\"?\") ? \"&\" : \"?\";\n const returnUrl = encodeURIComponent(request.url);\n\n return response.redirect(`${destination}${separator}${returnUrlParam}=${returnUrl}`);\n }\n\n return response.unauthorized(payload);\n}\n\nfunction tokenFromDescriptor(descriptor: Partial<AuthCredentialDescriptor>): TokenFrom {\n if (!descriptor.source || descriptor.source === \"header\") return \"header\";\n\n if (!descriptor.key) {\n throw new Error(\"authMiddleware cookie credentials require a cookie key.\");\n }\n\n return `cookie:${descriptor.key}`;\n}\n\nfunction descriptorSource(tokenFrom: TokenFrom): AuthMiddlewareDescriptorSource {\n return tokenFrom === \"header\" ? \"header\" : { cookie: tokenFrom.slice(\"cookie:\".length) };\n}\n\nfunction resolveAllowedTypes(value: string | string[] | undefined): string[] {\n if (value !== undefined) return Array.isArray(value) ? value : [value];\n\n const configuredDefault = config.key(\"auth.defaultUserType\") as string | undefined;\n\n if (configuredDefault) return [configuredDefault];\n\n const userTypes = config.key(\"auth.userType\", {}) as Record<string, unknown>;\n const configuredTypes = Object.keys(userTypes);\n\n if (configuredTypes.length === 1) return configuredTypes;\n\n throw new Error(\n \"authMiddleware requires a user type when auth.defaultUserType is unset and multiple user types exist.\",\n );\n}\n\n/**\n * Build a route gate. Authentication is required unless optional is explicit.\n *\n * An omitted user type selects the configured default; an explicit argument\n * selects which user types may pass:\n * - `[]` — any authenticated user (token required, type not checked).\n * - `\"admin\"` / `[\"admin\", \"staff\"]` — token required AND the user's\n * `userType` must be one of the listed types.\n *\n * `{ optional: true }` allows anonymous requests. All other forms reject\n * missing or invalid credentials with 401, or a configured page redirect.\n *\n * `tokenFrom` selects one credential source and defaults to `\"header\"`.\n * A single source avoids making credential precedence depend on array order.\n *\n * @example\n * router.get(\"/account\", authMiddleware([]), accountController);\n * router.get(\"/admin\", authMiddleware(\"admin\"), adminController);\n * router.get(\"/back-office\", authMiddleware([\"admin\", \"staff\"]), backOfficeController);\n * router.get(\"/browser-account\", authMiddleware([], \"cookie:token\"), accountController);\n */\nexport function authMiddleware(): Middleware;\nexport function authMiddleware(options: AuthMiddlewareOptions): Middleware;\nexport function authMiddleware(\n allowedUserType: string | string[],\n options?: AuthMiddlewareOptions,\n): Middleware;\nexport function authMiddleware(\n allowedUserType: string | string[],\n tokenFrom?: TokenFrom,\n): Middleware;\nexport function authMiddleware(\n userTypeOrOptions?: string | string[] | AuthMiddlewareOptions,\n legacyTokenFromOrOptions?: TokenFrom | AuthMiddlewareOptions,\n): Middleware {\n const options =\n typeof userTypeOrOptions === \"object\" && !Array.isArray(userTypeOrOptions)\n ? userTypeOrOptions\n : typeof legacyTokenFromOrOptions === \"object\"\n ? legacyTokenFromOrOptions\n : undefined;\n const selectedUserType =\n typeof userTypeOrOptions === \"string\" || Array.isArray(userTypeOrOptions)\n ? userTypeOrOptions\n : undefined;\n const allowedTypes = resolveAllowedTypes(selectedUserType);\n const legacyTokenFrom =\n typeof legacyTokenFromOrOptions === \"string\" ? legacyTokenFromOrOptions : undefined;\n const dualSources = options?.sources?.length\n ? options.sources.map(tokenFromDescriptor)\n : undefined;\n\n if (dualSources && options?.source) {\n throw new Error(\"authMiddleware accepts either `source` or `sources`, not both.\");\n }\n\n const dualHeader = dualSources?.includes(\"header\") ?? false;\n const dualCookies = dualSources?.filter((source) => source !== \"header\") ?? [];\n\n if (dualSources && (dualCookies.length > 1 || dualSources.length - dualCookies.length > 1)) {\n throw new Error(\"authMiddleware `sources` accepts at most one header and one cookie.\");\n }\n\n // With dual sources the configured cookie is the base credential; the header\n // is chosen per request, ahead of it.\n const cookieTokenFrom: TokenFrom = dualSources\n ? (dualCookies[0] ?? \"header\")\n : options\n ? tokenFromDescriptor(options)\n : (legacyTokenFrom ?? \"header\");\n const tokenFrom = cookieTokenFrom;\n const refreshCredential = options?.refresh ? tokenFromDescriptor(options.refresh) : undefined;\n const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : undefined;\n\n if (\n refreshCredential &&\n (tokenFrom === \"header\" || refreshCredential === \"header\" || !renewalUserType)\n ) {\n throw new Error(\n \"authMiddleware automatic renewal requires one allowed user type and cookie access and refresh credentials.\",\n );\n }\n\n const optional = options?.optional === true;\n\n const auth: Middleware = async ({ request, response }) => {\n const reject = (payload: UnauthorizedPayload) =>\n rejectUnauthorized({ request, response }, payload, options?.redirect);\n\n // A present Authorization header always wins and never falls back to the\n // cookie: the credential used is the header, so no renewal and no CSRF check.\n const headerWins = dualHeader && Boolean(request.authorizationValue);\n const usedTokenFrom: TokenFrom = headerWins ? \"header\" : tokenFrom;\n const usedRefresh = headerWins ? undefined : refreshCredential;\n\n // Renewal can mint cookies, so a cookie-authenticated unsafe request must\n // pass the same CSRF check even when its access cookie is missing.\n if (\n (readCredential(request, usedTokenFrom) ||\n (usedRefresh && readCredential(request, usedRefresh))) &&\n requiresCsrfOriginCheck(usedTokenFrom, request.method)\n ) {\n try {\n assertCsrfOriginAllowed(request);\n } catch (error) {\n if (!(error instanceof CsrfOriginMismatchError)) throw error;\n\n // A client error any cross-site page can trigger: debug, not error.\n log.debug(\"http\", \"auth\", error);\n return response.forbidden({\n error: t(\"auth.errors.csrfOriginMismatch\"),\n errorCode: AuthErrorCodes.CsrfOriginMismatch,\n });\n }\n }\n\n const outcome = await resolveRequestUserOutcome(request, response, {\n tokenFrom: usedTokenFrom,\n refreshCredential: usedRefresh,\n overlapMs: options?.refresh?.overlapMs,\n allowedTypes,\n renewalUserType,\n });\n\n if (outcome.user) {\n request.locals.user = outcome.user;\n return;\n }\n\n if (outcome.failure === \"forbidden\") {\n return response.forbidden({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n }\n\n if (optional) return;\n\n if (outcome.failure === \"missing\") {\n return reject({\n error: t(\"auth.errors.missingAccessToken\"),\n errorCode: AuthErrorCodes.MissingAccessToken,\n });\n }\n\n if (outcome.failure === \"unauthorized\") {\n return reject({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n }\n\n return reject({\n error: t(\"auth.errors.invalidAccessToken\"),\n errorCode: AuthErrorCodes.InvalidAccessToken,\n });\n };\n\n const descriptorSources: AuthMiddlewareDescriptorSource[] = dualSources\n ? [...(dualHeader ? ([\"header\"] as const) : []), ...dualCookies.map(descriptorSource)]\n : [descriptorSource(tokenFrom)];\n const descriptor: AuthMiddlewareDescriptor = Object.freeze({\n ...(optional ? { required: false } : {}),\n sources: Object.freeze(\n descriptorSources.map((source) =>\n typeof source === \"string\" ? source : Object.freeze({ ...source }),\n ),\n ) as AuthMiddlewareDescriptorSource[],\n userTypes: Object.freeze([...allowedTypes]) as string[],\n });\n\n // Non-enumerable so the tag never shows up in logs, spreads or JSON.\n Object.defineProperty(auth, AUTH_MIDDLEWARE_DESCRIPTOR, { value: descriptor, enumerable: false });\n\n // Tells `warlock dev` and `warlock inspect` that routes behind this\n // middleware are authenticated. `{ optional: true }`\n // lets anonymous requests through, so it does not count as a guard.\n return markAuthGuard(auth, !optional);\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,6BAA6B,OAAO,IAAI,cAAc;;;;;;;;;;;;;;;;;;;AAsCnE,SAAS,mBACP,EAAE,SAAS,YACX,SACA,UACA;CACA,MAAM,YAAY,UAAU,MAAM,WAAW,SAAS,UAAU;CAChE,MAAM,iBAAiB,UAAU,kBAAkB,WAAW,SAAS,eAAe;CAEtF,IAAI,aAAa,QAAQ,OAAO,QAAQ;EAMtC,MAAM,cAAc,mBAAmB,WAAW,QAAQ,MAAM;EAChE,MAAM,YAAY,YAAY,SAAS,GAAG,IAAI,MAAM;EACpD,MAAM,YAAY,mBAAmB,QAAQ,GAAG;EAEhD,OAAO,SAAS,SAAS,GAAG,cAAc,YAAY,eAAe,GAAG,WAAW;CACrF;CAEA,OAAO,SAAS,aAAa,OAAO;AACtC;AAEA,SAAS,oBAAoB,YAA0D;CACrF,IAAI,CAAC,WAAW,UAAU,WAAW,WAAW,UAAU,OAAO;CAEjE,IAAI,CAAC,WAAW,KACd,MAAM,IAAI,MAAM,yDAAyD;CAG3E,OAAO,UAAU,WAAW;AAC9B;AAEA,SAAS,iBAAiB,WAAsD;CAC9E,OAAO,cAAc,WAAW,WAAW,EAAE,QAAQ,UAAU,MAAM,CAAgB,EAAE;AACzF;AAEA,SAAS,oBAAoB,OAAgD;CAC3E,IAAI,UAAU,QAAW,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;CAErE,MAAM,oBAAoB,OAAO,IAAI,sBAAsB;CAE3D,IAAI,mBAAmB,OAAO,CAAC,iBAAiB;CAEhD,MAAM,YAAY,OAAO,IAAI,iBAAiB,CAAC,CAAC;CAChD,MAAM,kBAAkB,OAAO,KAAK,SAAS;CAE7C,IAAI,gBAAgB,WAAW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