@warlock.js/auth 5.53.1 → 5.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/esm/contracts/providers.d.mts +1 -1
  3. package/esm/contracts/types.d.mts +22 -0
  4. package/esm/contracts/types.d.mts.map +1 -1
  5. package/esm/contracts/types.mjs.map +1 -1
  6. package/esm/middleware/login-throttle.middleware.d.mts +1 -1
  7. package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
  8. package/esm/middleware/login-throttle.middleware.mjs +18 -1
  9. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  10. package/esm/models/auth-token-family/auth-token-family.model.d.mts +14 -0
  11. package/esm/models/auth-token-family/auth-token-family.model.d.mts.map +1 -1
  12. package/esm/models/auth-token-family/auth-token-family.model.mjs +43 -0
  13. package/esm/models/auth-token-family/auth-token-family.model.mjs.map +1 -1
  14. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  15. package/esm/models/refresh-token/refresh-token.model.mjs +6 -1
  16. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  17. package/esm/otp/otp.d.mts +5 -4
  18. package/esm/otp/otp.d.mts.map +1 -1
  19. package/esm/otp/otp.mjs +25 -20
  20. package/esm/otp/otp.mjs.map +1 -1
  21. package/esm/services/auth-config.mjs +40 -3
  22. package/esm/services/auth-config.mjs.map +1 -1
  23. package/esm/services/auth.service.d.mts +11 -2
  24. package/esm/services/auth.service.d.mts.map +1 -1
  25. package/esm/services/auth.service.mjs +36 -9
  26. package/esm/services/auth.service.mjs.map +1 -1
  27. package/esm/services/background-work.mjs +16 -0
  28. package/esm/services/background-work.mjs.map +1 -0
  29. package/esm/services/jwt.d.mts +2 -2
  30. package/esm/services/jwt.d.mts.map +1 -1
  31. package/esm/services/jwt.mjs +51 -26
  32. package/esm/services/jwt.mjs.map +1 -1
  33. package/esm/services/password-reset.d.mts +7 -5
  34. package/esm/services/password-reset.d.mts.map +1 -1
  35. package/esm/services/password-reset.mjs +25 -19
  36. package/esm/services/password-reset.mjs.map +1 -1
  37. package/llms-full.txt +8 -6
  38. package/package.json +11 -11
  39. package/skills/auth-basics/SKILL.md +1 -1
  40. package/skills/login-with-providers/SKILL.md +2 -2
  41. package/skills/manage-tokens/SKILL.md +2 -0
  42. package/skills/throttle-login-attempts/SKILL.md +2 -2
  43. package/skills/verify-email-and-reset-password/SKILL.md +1 -1
@@ -3,6 +3,7 @@ import { authEvents } from "./auth-events.mjs";
3
3
  import { authService } from "./auth.service.mjs";
4
4
  import { consumeOneTimeToken, issueOneTimeToken } from "./one-time-tokens.mjs";
5
5
  import { resolveTokenNotification } from "./token-notifications.mjs";
6
+ import { runInBackground } from "./background-work.mjs";
6
7
  import { log } from "@warlock.js/logger";
7
8
 
8
9
  //#region ../../packages/auth/src/services/password-reset.ts
@@ -36,11 +37,13 @@ async function writePassword(user, plainPassword) {
36
37
  * **Anti-enumeration:** resolves `undefined` whether or not the account exists
37
38
  * — an unknown identifier simply sends nothing. Notification availability is
38
39
  * checked before the lookup, so a misconfigured app fails identically for both.
39
- * The notification is sent in the background: awaiting it (an SMTP round trip
40
- * for a known account, nothing for an unknown one) would let response timing
41
- * reveal which accounts exist. A send that fails is logged and emitted as
42
- * `password.resetDeliveryFailed`; set `auth.passwordReset.awaitDelivery: true`
43
- * to wait for it (and receive its error) instead.
40
+ * The account lookup, the token writes and the notification all run in the
41
+ * background: doing any of them before answering (a database write and an SMTP
42
+ * round trip for a known account, nothing for an unknown one) would let
43
+ * response timing reveal which accounts exist. A failure is logged and
44
+ * emitted as `password.resetDeliveryFailed`; set
45
+ * `auth.passwordReset.awaitDelivery: true` to wait for all of it (and receive
46
+ * its error) instead.
44
47
  *
45
48
  * @throws NotificationsUnavailableError when `@warlock.js/notifications` is not installed or not configured.
46
49
  *
@@ -51,24 +54,27 @@ async function writePassword(user, plainPassword) {
51
54
  async function requestPasswordReset(Model, identifier) {
52
55
  const notification = await resolveTokenNotification("password-reset");
53
56
  if (typeof identifier !== "string" || identifier.length === 0) return;
54
- const user = await Model.first({ [authConfig.passwordReset.identifierField()]: identifier });
55
- if (!user) return;
56
- const { token, expiresAt } = await issueOneTimeToken(user, "password-reset", authConfig.passwordReset.expiresInMs(), true);
57
- authEvents.emit("password.resetRequested", user, token);
58
- const url = authConfig.passwordReset.url()?.(token, user);
59
- const delivery = Promise.resolve().then(() => notification.send(user, {
60
- token,
61
- expiresAt,
62
- ...url ? { url } : {}
63
- }));
57
+ let user = null;
58
+ const issueAndDeliver = async () => {
59
+ user = await Model.first({ [authConfig.passwordReset.identifierField()]: identifier });
60
+ if (!user) return;
61
+ const { token, expiresAt } = await issueOneTimeToken(user, "password-reset", authConfig.passwordReset.expiresInMs(), true);
62
+ authEvents.emit("password.resetRequested", user, token);
63
+ const url = authConfig.passwordReset.url()?.(token, user);
64
+ await notification.send(user, {
65
+ token,
66
+ expiresAt,
67
+ ...url ? { url } : {}
68
+ });
69
+ };
64
70
  if (authConfig.passwordReset.awaitDelivery()) {
65
- await delivery;
71
+ await issueAndDeliver();
66
72
  return;
67
73
  }
68
- delivery.catch((error) => {
74
+ runInBackground(() => issueAndDeliver().catch((error) => {
69
75
  log.error("auth", "password-reset", error);
70
- authEvents.emit("password.resetDeliveryFailed", user, error);
71
- });
76
+ if (user) authEvents.emit("password.resetDeliveryFailed", user, error);
77
+ }));
72
78
  }
73
79
  /**
74
80
  * Complete a password reset: consume the token, store the new password, then
@@ -1 +1 @@
1
- {"version":3,"file":"password-reset.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/password-reset.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"./auth-config\";\nimport { authEvents } from \"./auth-events\";\nimport { authService } from \"./auth.service\";\nimport { consumeOneTimeToken, issueOneTimeToken } from \"./one-time-tokens\";\nimport { resolveTokenNotification } from \"./token-notifications\";\n\n/**\n * Default password writer. Login verifies with `authService.verifyPassword`,\n * so that is the authority on what \"stored correctly\" means:\n *\n * 1. Save `hashPassword(plain)` — right for a model that stores what it's given.\n * 2. If that no longer verifies, the model hashed on save (core's\n * `useHashedPassword()`), double-hashing it: save the plaintext so the\n * model's own transformer hashes it once.\n * 3. Still not verifiable ⇒ throw. Never leave a reset that \"succeeded\" with a\n * password nobody can log in with.\n *\n * The first write is always a hash, so a model without a transformer never\n * has plaintext written.\n */\nasync function writePassword(user: Auth, plainPassword: string): Promise<void> {\n await user.merge({ password: await authService.hashPassword(plainPassword) } as never).save();\n\n if (await authService.verifyPassword(plainPassword, user.string(\"password\") ?? \"\")) return;\n\n await user.merge({ password: plainPassword } as never).save();\n\n const stored = user.string(\"password\") ?? \"\";\n\n if (stored !== plainPassword && (await authService.verifyPassword(plainPassword, stored))) {\n return;\n }\n\n throw new Error(\n \"@warlock.js/auth: resetPassword could not store a password that verifies — \" +\n \"set `auth.passwordReset.setPassword` to write it the way your user model expects.\",\n );\n}\n\n/**\n * Start a password reset for the account whose `auth.passwordReset.identifierField`\n * (default `email`) equals `identifier`: invalidate the account's unused reset\n * tokens, issue a new one, and send it through the reset notification.\n *\n * **Anti-enumeration:** resolves `undefined` whether or not the account exists\n * — an unknown identifier simply sends nothing. Notification availability is\n * checked before the lookup, so a misconfigured app fails identically for both.\n * The notification is sent in the background: awaiting it (an SMTP round trip\n * for a known account, nothing for an unknown one) would let response timing\n * reveal which accounts exist. A send that fails is logged and emitted as\n * `password.resetDeliveryFailed`; set `auth.passwordReset.awaitDelivery: true`\n * to wait for it (and receive its error) instead.\n *\n * @throws NotificationsUnavailableError when `@warlock.js/notifications` is not installed or not configured.\n *\n * @example\n * await requestPasswordReset(User, request.input(\"email\"));\n * return response.success({ message: \"If the account exists, we sent a reset link.\" });\n */\nexport async function requestPasswordReset<T extends Auth>(\n Model: ChildModel<T>,\n identifier: string,\n): Promise<void> {\n const notification = await resolveTokenNotification(\"password-reset\");\n\n if (typeof identifier !== \"string\" || identifier.length === 0) return;\n\n const user = (await Model.first({\n [authConfig.passwordReset.identifierField()]: identifier,\n })) as T | null;\n\n if (!user) return;\n\n const { token, expiresAt } = await issueOneTimeToken(\n user,\n \"password-reset\",\n authConfig.passwordReset.expiresInMs(),\n true,\n );\n\n authEvents.emit(\"password.resetRequested\", user, token);\n\n const url = authConfig.passwordReset.url()?.(token, user);\n\n const delivery = Promise.resolve().then(() =>\n notification.send(user, { token, expiresAt, ...(url ? { url } : {}) }),\n );\n\n if (authConfig.passwordReset.awaitDelivery()) {\n await delivery;\n\n return;\n }\n\n delivery.catch((error: unknown) => {\n log.error(\"auth\", \"password-reset\", error);\n authEvents.emit(\"password.resetDeliveryFailed\", user, error);\n });\n}\n\n/**\n * Complete a password reset: consume the token, store the new password, then\n * revoke every access token, refresh token and cookie session the user holds\n * (`authService.revokeAllTokens`). Resolves to the user.\n *\n * Validate password strength BEFORE calling this — the token is consumed first.\n *\n * @throws InvalidOneTimeTokenError for an unknown, verification-purpose,\n * expired, superseded or already-used token.\n */\nexport async function resetPassword(token: string, newPassword: string): Promise<Auth> {\n const user = await consumeOneTimeToken(token, \"password-reset\");\n\n const setPassword = authConfig.passwordReset.setPassword();\n\n if (setPassword) {\n await setPassword(user, newPassword);\n } else {\n await writePassword(user, newPassword);\n }\n\n await authService.revokeAllTokens(user);\n\n authEvents.emit(\"password.reset\", user);\n\n return user;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuBA,eAAe,cAAc,MAAY,eAAsC;CAC7E,MAAM,KAAK,MAAM,EAAE,UAAU,MAAM,YAAY,aAAa,aAAa,EAAE,CAAU,CAAC,CAAC,KAAK;CAE5F,IAAI,MAAM,YAAY,eAAe,eAAe,KAAK,OAAO,UAAU,KAAK,EAAE,GAAG;CAEpF,MAAM,KAAK,MAAM,EAAE,UAAU,cAAc,CAAU,CAAC,CAAC,KAAK;CAE5D,MAAM,SAAS,KAAK,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"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"./auth-config\";\nimport { authEvents } from \"./auth-events\";\nimport { runInBackground } from \"./background-work\";\nimport { authService } from \"./auth.service\";\nimport { consumeOneTimeToken, issueOneTimeToken } from \"./one-time-tokens\";\nimport { resolveTokenNotification } from \"./token-notifications\";\n\n/**\n * Default password writer. Login verifies with `authService.verifyPassword`,\n * so that is the authority on what \"stored correctly\" means:\n *\n * 1. Save `hashPassword(plain)` — right for a model that stores what it's given.\n * 2. If that no longer verifies, the model hashed on save (core's\n * `useHashedPassword()`), double-hashing it: save the plaintext so the\n * model's own transformer hashes it once.\n * 3. Still not verifiable ⇒ throw. Never leave a reset that \"succeeded\" with a\n * password nobody can log in with.\n *\n * The first write is always a hash, so a model without a transformer never\n * has plaintext written.\n */\nasync function writePassword(user: Auth, plainPassword: string): Promise<void> {\n await user.merge({ password: await authService.hashPassword(plainPassword) } as never).save();\n\n if (await authService.verifyPassword(plainPassword, user.string(\"password\") ?? \"\")) return;\n\n await user.merge({ password: plainPassword } as never).save();\n\n const stored = user.string(\"password\") ?? \"\";\n\n if (stored !== plainPassword && (await authService.verifyPassword(plainPassword, stored))) {\n return;\n }\n\n throw new Error(\n \"@warlock.js/auth: resetPassword could not store a password that verifies — \" +\n \"set `auth.passwordReset.setPassword` to write it the way your user model expects.\",\n );\n}\n\n/**\n * Start a password reset for the account whose `auth.passwordReset.identifierField`\n * (default `email`) equals `identifier`: invalidate the account's unused reset\n * tokens, issue a new one, and send it through the reset notification.\n *\n * **Anti-enumeration:** resolves `undefined` whether or not the account exists\n * — an unknown identifier simply sends nothing. Notification availability is\n * checked before the lookup, so a misconfigured app fails identically for both.\n * The account lookup, the token writes and the notification all run in the\n * background: doing any of them before answering (a database write and an SMTP\n * round trip for a known account, nothing for an unknown one) would let\n * response timing reveal which accounts exist. A failure is logged and\n * emitted as `password.resetDeliveryFailed`; set\n * `auth.passwordReset.awaitDelivery: true` to wait for all of it (and receive\n * its error) instead.\n *\n * @throws NotificationsUnavailableError when `@warlock.js/notifications` is not installed or not configured.\n *\n * @example\n * await requestPasswordReset(User, request.input(\"email\"));\n * return response.success({ message: \"If the account exists, we sent a reset link.\" });\n */\nexport async function requestPasswordReset<T extends Auth>(\n Model: ChildModel<T>,\n identifier: string,\n): Promise<void> {\n const notification = await resolveTokenNotification(\"password-reset\");\n\n if (typeof identifier !== \"string\" || identifier.length === 0) return;\n\n let user: T | null = null;\n\n const issueAndDeliver = async (): Promise<void> => {\n user = (await Model.first({\n [authConfig.passwordReset.identifierField()]: identifier,\n })) as T | null;\n\n if (!user) return;\n\n const { token, expiresAt } = await issueOneTimeToken(\n user,\n \"password-reset\",\n authConfig.passwordReset.expiresInMs(),\n true,\n );\n\n authEvents.emit(\"password.resetRequested\", user, token);\n\n const url = authConfig.passwordReset.url()?.(token, user);\n\n await notification.send(user, { token, expiresAt, ...(url ? { url } : {}) });\n };\n\n if (authConfig.passwordReset.awaitDelivery()) {\n await issueAndDeliver();\n\n return;\n }\n\n // The lookup, the token writes and the delivery all run after the response,\n // so a known and an unknown account answer in the same time.\n runInBackground(() =>\n issueAndDeliver().catch((error: unknown) => {\n log.error(\"auth\", \"password-reset\", error);\n\n if (user) authEvents.emit(\"password.resetDeliveryFailed\", user, error);\n }),\n );\n}\n\n/**\n * Complete a password reset: consume the token, store the new password, then\n * revoke every access token, refresh token and cookie session the user holds\n * (`authService.revokeAllTokens`). Resolves to the user.\n *\n * Validate password strength BEFORE calling this — the token is consumed first.\n *\n * @throws InvalidOneTimeTokenError for an unknown, verification-purpose,\n * expired, superseded or already-used token.\n */\nexport async function resetPassword(token: string, newPassword: string): Promise<Auth> {\n const user = await consumeOneTimeToken(token, \"password-reset\");\n\n const setPassword = authConfig.passwordReset.setPassword();\n\n if (setPassword) {\n await setPassword(user, newPassword);\n } else {\n await writePassword(user, newPassword);\n }\n\n await authService.revokeAll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C,IAAI,MAAM,WAAW,KAAK,gCAAgC,MAAM,KAAK;CACvE,CAAC,CACH;AACF;;;;;;;;;;;AAYA,eAAsB,cAAc,OAAe,aAAoC;CACrF,MAAM,OAAO,MAAM,oBAAoB,OAAO,gBAAgB;CAE9D,MAAM,cAAc,WAAW,cAAc,YAAY;CAEzD,IAAI,aACF,MAAM,YAAY,MAAM,WAAW;MAEnC,MAAM,cAAc,MAAM,WAAW;CAGvC,MAAM,YAAY,gBAAgB,IAAI;CAEtC,WAAW,KAAK,kBAAkB,IAAI;CAEtC,OAAO;AACT"}
package/llms-full.txt CHANGED
@@ -150,7 +150,7 @@ export default {
150
150
  - `hashTokensAtRest: true` (default `false`) — `access_tokens.token` / `refresh_tokens.token` hold the SHA-256 digest, never the JWT, so a copied table cannot be replayed. No migration; lookups accept both forms, so switching it on or off signs no one out. A row loaded from the DB has no raw token any more; a freshly issued row exposes it as `row.plainToken`. Automatic cookie renewal parks the successor pair encrypted in the cache for the overlap window.
151
151
  - `accessToken.issuer` / `accessToken.audience` (default unset) — stamped as `iss` / `aud` on every token signed and required on every token accepted. Setting either signs everyone out once (old tokens lack the claim).
152
152
  - `cookie.hostPrefix: true` (default `false`) — auth cookies become `__Host-access_token` / `__Host-refresh_token` (Secure, `Path=/`, no Domain; a write with another path or a Domain throws naming the setting). The unprefixed cookie is still read during the switch, and both are cleared on logout.
153
- - In production a signing secret under 32 bytes, or an access-token lifetime over 30 days, logs a one-time warning.
153
+ - In production a signing secret under 32 bytes, or an access-token lifetime over 30 days, logs a one-time warning (a secret under 32 bytes becomes a boot error in 6.0). `auth.rehashPasswords` (default `true`) re-hashes a stored password after a correct login when `encryption.password` asks for another algorithm or cost.
154
154
  - `Auth` hides `password` from serialized output (`static hidden = ["password"]`); a model that sets its own `hidden` must keep `"password"` in it.
155
155
 
156
156
  ### Token lifetimes are validated — a bad one throws
@@ -972,7 +972,7 @@ passkeys: {
972
972
  rpID: "example.com",
973
973
  rpName: "Example",
974
974
  origin: "https://example.com",
975
- userVerification: "preferred", // default; "required" refuses assertions without PIN/biometric
975
+ userVerification: "required", // "preferred" (default until 6.0, warns if unset) also accepts possession only
976
976
  },
977
977
  ```
978
978
 
@@ -1071,7 +1071,7 @@ router.post(
1071
1071
  - Codes have 6 digits and are stored in `one_time_tokens` (purpose `otp`) as a salted HMAC keyed from your access-token secret, never as plain SHA-256, which is trivially reversible for 6 digits. A new request invalidates the previous code.
1072
1072
  - Every verify counts an attempt atomically first. After `maxAttempts` the code is invalidated, even if the right code comes next, and even under concurrent guesses.
1073
1073
  - Delivery: `notify.channel(channel).send(phone, { body, code, expiresAt })`. Register that channel in `config/notifications.ts`, or set `auth.otp.send(phone, message, channel)`. `auth.otp.message(code)` changes the text.
1074
- - **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`. The code is delivered in the background (failures: log + `otp.deliveryFailed` event); `auth.otp.awaitDelivery: true` awaits it instead.
1074
+ - **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`. The lookup, the code writes and the delivery run in the background (failures: log + `otp.deliveryFailed` event); `auth.otp.awaitDelivery: true` awaits it instead.
1075
1075
  - CSRF: `verifyOtp` is a POST. If the route uses cookie auth, the 5.12 Origin check applies. Otherwise there is no ambient credential to ride.
1076
1076
 
1077
1077
  ## Gotchas
@@ -1280,6 +1280,8 @@ If tokens minted before 4.12.0 may lack an `exp`, see `warlock auth.purge-never-
1280
1280
 
1281
1281
  The package signs access and refresh tokens with independent secrets — `config.auth.accessToken.secret` and `config.auth.refreshToken.secret`. Setting a distinct `refresh.secret` is recommended: it prevents an access-token compromise from forging refresh tokens (and vice versa). The refresh secret is **optional** — when `config.auth.refreshToken.secret` is unset, refresh tokens fall back to the main `config.auth.accessToken.secret`, so refresh works out of the box without a second secret.
1282
1282
 
1283
+ **Rotating a secret:** set the new `accessToken.secret` / `refreshToken.secret` and list the old ones in `accessToken.previousSecrets` / `refreshToken.previousSecrets`. Tokens signed with a retired secret still verify (only on a signature miss; expiry and claim checks stay final), new tokens always use the current secret, and without a refresh secret the retired access secrets apply to refresh tokens too. Remove a retired secret once its tokens have expired.
1284
+
1283
1285
  ## Things NOT to do
1284
1286
 
1285
1287
  - Don't use raw JWT libraries directly. The package handles signing, verification, secret loading, and the access/refresh split.
@@ -2065,10 +2067,10 @@ loginThrottleMiddleware({
2065
2067
  | `errorMessage` | i18n `auth.errors.tooManyAttempts` | 429 message override |
2066
2068
  | `isFailure` | `(res) => !res.isOk` | What counts as a failed attempt |
2067
2069
  | `identify` | built-in email + ip extraction | Custom identifier list |
2068
- | `emailLock` | `"global"` | `"pair"` locks the (email, IP) pair instead of the email for everyone |
2070
+ | `emailLock` | `"global"` (`"pair"` in 6.0) | `"pair"` locks the (email, IP) pair instead of the email for everyone |
2069
2071
  | `accountMax` | `max * 10` | Email-wide limit across all IPs when `emailLock: "pair"` |
2070
2072
 
2071
- `emailLock: "pair"` stops a stranger from locking a known account out: their `max` failures lock only their own (email, IP) pair, while the email-wide bucket (`accountMax`) still stops guessing spread over many IPs. It applies when `by` tracks both `"email"` and `"ip"` and no `identify` is set.
2073
+ `emailLock: "pair"` stops a stranger from locking a known account out: their `max` failures lock only their own (email, IP) pair, while the email-wide bucket (`accountMax`) still stops guessing spread over many IPs. It applies when `by` tracks both `"email"` and `"ip"` and no `identify` is set. Leaving it unset in that case logs a one-time warning because the default changes in 6.0: set it explicitly. A successful login clears the account buckets only; the shared IP bucket expires with its window (with `by: ["ip"]` alone a success still resets it).
2072
2074
 
2073
2075
  Throttle the anonymous passkey options route the same way, counting every request: `loginThrottleMiddleware({ by: ["ip"], isFailure: () => true, max: 30, window: "1m" })`.
2074
2076
 
@@ -2215,7 +2217,7 @@ router.post("/auth/reset-password", resetPasswordController, {
2215
2217
  });
2216
2218
  ```
2217
2219
 
2218
- `requestPasswordReset` sends the notification **in the background**, so a known account answers as fast as an unknown one (no SMTP round trip on the response path). A failed send is logged and emitted as `password.resetDeliveryFailed` (`(user, error)`); set `auth.passwordReset.awaitDelivery: true` (default `false`) to await it and get its error instead.
2220
+ `requestPasswordReset` runs the account lookup, the token writes and the notification **in the background**, so a known account answers as fast as an unknown one (no database write or SMTP round trip on the response path). A failed send is logged and emitted as `password.resetDeliveryFailed` (`(user, error)`); set `auth.passwordReset.awaitDelivery: true` (default `false`) to await all of it and get its error instead.
2219
2221
 
2220
2222
  `resetPassword` writes the password, then calls `authService.revokeAllTokens(user)`: every refresh token is revoked and every access token deleted, which also kills cookie sessions (a cookie holds an access token). It emits `password.reset`; `requestPasswordReset` emits `password.resetRequested`.
2221
2223
 
package/package.json CHANGED
@@ -5,20 +5,20 @@
5
5
  "environment": "server"
6
6
  },
7
7
  "dependencies": {
8
- "@mongez/copper": "^2.1.3",
9
- "@mongez/events": "^2.2.8",
10
- "@mongez/reinforcements": "^4.0.2",
8
+ "@mongez/copper": "^2.1.4",
9
+ "@mongez/events": "^2.2.10",
10
+ "@mongez/reinforcements": "^4.1.0",
11
11
  "fast-jwt": "^6.3.4",
12
12
  "ms": "^2.1.3"
13
13
  },
14
14
  "peerDependencies": {
15
- "@warlock.js/fs": "5.53.1",
16
- "@warlock.js/cache": "5.53.1",
17
- "@warlock.js/cascade": "5.53.1",
18
- "@warlock.js/core": "5.53.1",
19
- "@warlock.js/logger": "5.53.1",
20
- "@warlock.js/seal": "5.53.1",
21
- "@warlock.js/notifications": "5.53.1",
15
+ "@warlock.js/fs": "5.54.0",
16
+ "@warlock.js/cache": "5.54.0",
17
+ "@warlock.js/cascade": "5.54.0",
18
+ "@warlock.js/core": "5.54.0",
19
+ "@warlock.js/logger": "5.54.0",
20
+ "@warlock.js/seal": "5.54.0",
21
+ "@warlock.js/notifications": "5.54.0",
22
22
  "@simplewebauthn/server": "^13.1.0",
23
23
  "jose": "^6.1.0"
24
24
  },
@@ -48,7 +48,7 @@
48
48
  ],
49
49
  "author": "hassanzohdy",
50
50
  "license": "MIT",
51
- "version": "5.53.1",
51
+ "version": "5.54.0",
52
52
  "type": "module",
53
53
  "main": "./esm/index.mjs",
54
54
  "module": "./esm/index.mjs",
@@ -89,7 +89,7 @@ export default {
89
89
  - `hashTokensAtRest: true` (default `false`) — `access_tokens.token` / `refresh_tokens.token` hold the SHA-256 digest, never the JWT, so a copied table cannot be replayed. No migration; lookups accept both forms, so switching it on or off signs no one out. A row loaded from the DB has no raw token any more; a freshly issued row exposes it as `row.plainToken`. Automatic cookie renewal parks the successor pair encrypted in the cache for the overlap window.
90
90
  - `accessToken.issuer` / `accessToken.audience` (default unset) — stamped as `iss` / `aud` on every token signed and required on every token accepted. Setting either signs everyone out once (old tokens lack the claim).
91
91
  - `cookie.hostPrefix: true` (default `false`) — auth cookies become `__Host-access_token` / `__Host-refresh_token` (Secure, `Path=/`, no Domain; a write with another path or a Domain throws naming the setting). The unprefixed cookie is still read during the switch, and both are cleared on logout.
92
- - In production a signing secret under 32 bytes, or an access-token lifetime over 30 days, logs a one-time warning.
92
+ - In production a signing secret under 32 bytes, or an access-token lifetime over 30 days, logs a one-time warning (a secret under 32 bytes becomes a boot error in 6.0). `auth.rehashPasswords` (default `true`) re-hashes a stored password after a correct login when `encryption.password` asks for another algorithm or cost.
93
93
  - `Auth` hides `password` from serialized output (`static hidden = ["password"]`); a model that sets its own `hidden` must keep `"password"` in it.
94
94
 
95
95
  ### Token lifetimes are validated — a bad one throws
@@ -234,7 +234,7 @@ passkeys: {
234
234
  rpID: "example.com",
235
235
  rpName: "Example",
236
236
  origin: "https://example.com",
237
- userVerification: "preferred", // default; "required" refuses assertions without PIN/biometric
237
+ userVerification: "required", // "preferred" (default until 6.0, warns if unset) also accepts possession only
238
238
  },
239
239
  ```
240
240
 
@@ -333,7 +333,7 @@ router.post(
333
333
  - Codes have 6 digits and are stored in `one_time_tokens` (purpose `otp`) as a salted HMAC keyed from your access-token secret, never as plain SHA-256, which is trivially reversible for 6 digits. A new request invalidates the previous code.
334
334
  - Every verify counts an attempt atomically first. After `maxAttempts` the code is invalidated, even if the right code comes next, and even under concurrent guesses.
335
335
  - Delivery: `notify.channel(channel).send(phone, { body, code, expiresAt })`. Register that channel in `config/notifications.ts`, or set `auth.otp.send(phone, message, channel)`. `auth.otp.message(code)` changes the text.
336
- - **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`. The code is delivered in the background (failures: log + `otp.deliveryFailed` event); `auth.otp.awaitDelivery: true` awaits it instead.
336
+ - **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`. The lookup, the code writes and the delivery run in the background (failures: log + `otp.deliveryFailed` event); `auth.otp.awaitDelivery: true` awaits it instead.
337
337
  - CSRF: `verifyOtp` is a POST. If the route uses cookie auth, the 5.12 Origin check applies. Otherwise there is no ambient credential to ride.
338
338
 
339
339
  ## Gotchas
@@ -187,6 +187,8 @@ If tokens minted before 4.12.0 may lack an `exp`, see `warlock auth.purge-never-
187
187
 
188
188
  The package signs access and refresh tokens with independent secrets — `config.auth.accessToken.secret` and `config.auth.refreshToken.secret`. Setting a distinct `refresh.secret` is recommended: it prevents an access-token compromise from forging refresh tokens (and vice versa). The refresh secret is **optional** — when `config.auth.refreshToken.secret` is unset, refresh tokens fall back to the main `config.auth.accessToken.secret`, so refresh works out of the box without a second secret.
189
189
 
190
+ **Rotating a secret:** set the new `accessToken.secret` / `refreshToken.secret` and list the old ones in `accessToken.previousSecrets` / `refreshToken.previousSecrets`. Tokens signed with a retired secret still verify (only on a signature miss; expiry and claim checks stay final), new tokens always use the current secret, and without a refresh secret the retired access secrets apply to refresh tokens too. Remove a retired secret once its tokens have expired.
191
+
190
192
  ## Things NOT to do
191
193
 
192
194
  - Don't use raw JWT libraries directly. The package handles signing, verification, secret loading, and the access/refresh split.
@@ -94,10 +94,10 @@ loginThrottleMiddleware({
94
94
  | `errorMessage` | i18n `auth.errors.tooManyAttempts` | 429 message override |
95
95
  | `isFailure` | `(res) => !res.isOk` | What counts as a failed attempt |
96
96
  | `identify` | built-in email + ip extraction | Custom identifier list |
97
- | `emailLock` | `"global"` | `"pair"` locks the (email, IP) pair instead of the email for everyone |
97
+ | `emailLock` | `"global"` (`"pair"` in 6.0) | `"pair"` locks the (email, IP) pair instead of the email for everyone |
98
98
  | `accountMax` | `max * 10` | Email-wide limit across all IPs when `emailLock: "pair"` |
99
99
 
100
- `emailLock: "pair"` stops a stranger from locking a known account out: their `max` failures lock only their own (email, IP) pair, while the email-wide bucket (`accountMax`) still stops guessing spread over many IPs. It applies when `by` tracks both `"email"` and `"ip"` and no `identify` is set.
100
+ `emailLock: "pair"` stops a stranger from locking a known account out: their `max` failures lock only their own (email, IP) pair, while the email-wide bucket (`accountMax`) still stops guessing spread over many IPs. It applies when `by` tracks both `"email"` and `"ip"` and no `identify` is set. Leaving it unset in that case logs a one-time warning because the default changes in 6.0: set it explicitly. A successful login clears the account buckets only; the shared IP bucket expires with its window (with `by: ["ip"]` alone a success still resets it).
101
101
 
102
102
  Throttle the anonymous passkey options route the same way, counting every request: `loginThrottleMiddleware({ by: ["ip"], isFailure: () => true, max: 30, window: "1m" })`.
103
103
 
@@ -86,7 +86,7 @@ router.post("/auth/reset-password", resetPasswordController, {
86
86
  });
87
87
  ```
88
88
 
89
- `requestPasswordReset` sends the notification **in the background**, so a known account answers as fast as an unknown one (no SMTP round trip on the response path). A failed send is logged and emitted as `password.resetDeliveryFailed` (`(user, error)`); set `auth.passwordReset.awaitDelivery: true` (default `false`) to await it and get its error instead.
89
+ `requestPasswordReset` runs the account lookup, the token writes and the notification **in the background**, so a known account answers as fast as an unknown one (no database write or SMTP round trip on the response path). A failed send is logged and emitted as `password.resetDeliveryFailed` (`(user, error)`); set `auth.passwordReset.awaitDelivery: true` (default `false`) to await all of it and get its error instead.
90
90
 
91
91
  `resetPassword` writes the password, then calls `authService.revokeAllTokens(user)`: every refresh token is revoked and every access token deleted, which also kills cookie sessions (a cookie holds an access token). It emits `password.reset`; `requestPasswordReset` emits `password.resetRequested`.
92
92