@warlock.js/auth 5.51.0 → 5.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/esm/commands/auth-cleanup-command.mjs.map +1 -1
  3. package/esm/commands/auth-purge-never-expiring-command.mjs.map +1 -1
  4. package/esm/commands/jwt-secret-generator-command.mjs.map +1 -1
  5. package/esm/contracts/index.d.mts +3 -3
  6. package/esm/contracts/providers.d.mts +53 -0
  7. package/esm/contracts/providers.d.mts.map +1 -1
  8. package/esm/contracts/types.d.mts +71 -0
  9. package/esm/contracts/types.d.mts.map +1 -1
  10. package/esm/contracts/types.mjs.map +1 -1
  11. package/esm/errors/auth-provider-sdk-missing.error.mjs.map +1 -1
  12. package/esm/errors/email-not-verified.error.mjs.map +1 -1
  13. package/esm/errors/index.d.mts +2 -1
  14. package/esm/errors/index.mjs +2 -1
  15. package/esm/errors/invalid-one-time-token.error.mjs.map +1 -1
  16. package/esm/errors/invalid-passkey.error.mjs.map +1 -1
  17. package/esm/errors/invalid-provider-callback.error.mjs.map +1 -1
  18. package/esm/errors/notifications-unavailable.error.mjs.map +1 -1
  19. package/esm/errors/provider-account-link-blocked.error.d.mts +16 -0
  20. package/esm/errors/provider-account-link-blocked.error.d.mts.map +1 -0
  21. package/esm/errors/provider-account-link-blocked.error.mjs +22 -0
  22. package/esm/errors/provider-account-link-blocked.error.mjs.map +1 -0
  23. package/esm/errors/provider-email-not-verified.error.mjs.map +1 -1
  24. package/esm/index.d.mts +4 -3
  25. package/esm/index.mjs +2 -1
  26. package/esm/localization/ar.translations.mjs.map +1 -1
  27. package/esm/localization/auth-default-translations.mjs.map +1 -1
  28. package/esm/localization/en.translations.mjs.map +1 -1
  29. package/esm/localization/init.mjs.map +1 -1
  30. package/esm/localization/register-auth-translations.mjs.map +1 -1
  31. package/esm/middleware/auth.middleware.mjs +1 -1
  32. package/esm/middleware/auth.middleware.mjs.map +1 -1
  33. package/esm/middleware/csrf-origin-check.mjs.map +1 -1
  34. package/esm/middleware/localized-login-path.mjs.map +1 -1
  35. package/esm/middleware/login-throttle.middleware.d.mts +38 -8
  36. package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
  37. package/esm/middleware/login-throttle.middleware.mjs +95 -30
  38. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  39. package/esm/middleware/one-time-token-throttle.middleware.mjs.map +1 -1
  40. package/esm/middleware/otp-throttle.middleware.mjs.map +1 -1
  41. package/esm/middleware/require-verified-email.middleware.mjs.map +1 -1
  42. package/esm/models/access-token/access-token.model.d.mts +14 -3
  43. package/esm/models/access-token/access-token.model.d.mts.map +1 -1
  44. package/esm/models/access-token/access-token.model.mjs +15 -8
  45. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  46. package/esm/models/access-token/family-association.migration.mjs.map +1 -1
  47. package/esm/models/access-token/migration.mjs.map +1 -1
  48. package/esm/models/auth-token-family/auth-token-family.model.mjs.map +1 -1
  49. package/esm/models/auth-token-family/migration.mjs.map +1 -1
  50. package/esm/models/auth.model.d.mts +8 -0
  51. package/esm/models/auth.model.d.mts.map +1 -1
  52. package/esm/models/auth.model.mjs +3 -0
  53. package/esm/models/auth.model.mjs.map +1 -1
  54. package/esm/models/index.mjs.map +1 -1
  55. package/esm/models/one-time-token/migration.mjs.map +1 -1
  56. package/esm/models/one-time-token/one-time-token.model.d.mts +7 -2
  57. package/esm/models/one-time-token/one-time-token.model.d.mts.map +1 -1
  58. package/esm/models/one-time-token/one-time-token.model.mjs +8 -7
  59. package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -1
  60. package/esm/models/passkey-credential/migration.mjs.map +1 -1
  61. package/esm/models/passkey-credential/passkey-credential.model.mjs.map +1 -1
  62. package/esm/models/provider-account/migration.mjs.map +1 -1
  63. package/esm/models/provider-account/provider-account.model.mjs.map +1 -1
  64. package/esm/models/refresh-token/migration.mjs.map +1 -1
  65. package/esm/models/refresh-token/refresh-token.model.d.mts +15 -3
  66. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  67. package/esm/models/refresh-token/refresh-token.model.mjs +17 -12
  68. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  69. package/esm/models/refresh-token/successor-association.migration.mjs.map +1 -1
  70. package/esm/otp/otp.d.mts +5 -1
  71. package/esm/otp/otp.d.mts.map +1 -1
  72. package/esm/otp/otp.mjs +18 -3
  73. package/esm/otp/otp.mjs.map +1 -1
  74. package/esm/passkeys/passkey-authentication.mjs +2 -2
  75. package/esm/passkeys/passkey-authentication.mjs.map +1 -1
  76. package/esm/passkeys/passkey-challenges.mjs.map +1 -1
  77. package/esm/passkeys/passkey-registration.d.mts.map +1 -1
  78. package/esm/passkeys/passkey-registration.mjs +2 -2
  79. package/esm/passkeys/passkey-registration.mjs.map +1 -1
  80. package/esm/passkeys/simplewebauthn.mjs.map +1 -1
  81. package/esm/providers/apple-provider.d.mts +2 -0
  82. package/esm/providers/apple-provider.d.mts.map +1 -1
  83. package/esm/providers/apple-provider.mjs +4 -1
  84. package/esm/providers/apple-provider.mjs.map +1 -1
  85. package/esm/providers/discord-provider.d.mts +2 -0
  86. package/esm/providers/discord-provider.d.mts.map +1 -1
  87. package/esm/providers/discord-provider.mjs +7 -1
  88. package/esm/providers/discord-provider.mjs.map +1 -1
  89. package/esm/providers/facebook-provider.d.mts +2 -0
  90. package/esm/providers/facebook-provider.d.mts.map +1 -1
  91. package/esm/providers/facebook-provider.mjs +10 -2
  92. package/esm/providers/facebook-provider.mjs.map +1 -1
  93. package/esm/providers/github-provider.d.mts +2 -0
  94. package/esm/providers/github-provider.d.mts.map +1 -1
  95. package/esm/providers/github-provider.mjs +19 -10
  96. package/esm/providers/github-provider.mjs.map +1 -1
  97. package/esm/providers/google-provider.mjs.map +1 -1
  98. package/esm/providers/linkedin-provider.d.mts +2 -0
  99. package/esm/providers/linkedin-provider.d.mts.map +1 -1
  100. package/esm/providers/linkedin-provider.mjs +4 -1
  101. package/esm/providers/linkedin-provider.mjs.map +1 -1
  102. package/esm/providers/provider-login.mjs.map +1 -1
  103. package/esm/providers/provider-state-cookie.mjs.map +1 -1
  104. package/esm/providers/provider-timeout.mjs +17 -0
  105. package/esm/providers/provider-timeout.mjs.map +1 -0
  106. package/esm/providers/resolve-provider-user.mjs +21 -1
  107. package/esm/providers/resolve-provider-user.mjs.map +1 -1
  108. package/esm/providers/x-provider.d.mts +2 -0
  109. package/esm/providers/x-provider.d.mts.map +1 -1
  110. package/esm/providers/x-provider.mjs +7 -1
  111. package/esm/providers/x-provider.mjs.map +1 -1
  112. package/esm/services/auth-config.mjs +68 -6
  113. package/esm/services/auth-config.mjs.map +1 -1
  114. package/esm/services/auth-cookie-names.mjs +49 -0
  115. package/esm/services/auth-cookie-names.mjs.map +1 -0
  116. package/esm/services/auth-events.d.mts +4 -0
  117. package/esm/services/auth-events.d.mts.map +1 -1
  118. package/esm/services/auth-events.mjs.map +1 -1
  119. package/esm/services/auth.service.d.mts +14 -0
  120. package/esm/services/auth.service.d.mts.map +1 -1
  121. package/esm/services/auth.service.mjs +163 -21
  122. package/esm/services/auth.service.mjs.map +1 -1
  123. package/esm/services/current-user.mjs.map +1 -1
  124. package/esm/services/email-verification.mjs.map +1 -1
  125. package/esm/services/generate-jwt-secret.mjs.map +1 -1
  126. package/esm/services/jwt.d.mts.map +1 -1
  127. package/esm/services/jwt.mjs +92 -10
  128. package/esm/services/jwt.mjs.map +1 -1
  129. package/esm/services/one-time-tokens.mjs.map +1 -1
  130. package/esm/services/optional-peer.mjs.map +1 -1
  131. package/esm/services/password-reset.d.mts +5 -0
  132. package/esm/services/password-reset.d.mts.map +1 -1
  133. package/esm/services/password-reset.mjs +15 -1
  134. package/esm/services/password-reset.mjs.map +1 -1
  135. package/esm/services/resolve-request-user.d.mts.map +1 -1
  136. package/esm/services/resolve-request-user.mjs +17 -3
  137. package/esm/services/resolve-request-user.mjs.map +1 -1
  138. package/esm/services/token-family-operation.mjs.map +1 -1
  139. package/esm/services/token-notifications.mjs.map +1 -1
  140. package/esm/session/page-session.d.mts.map +1 -1
  141. package/esm/session/page-session.mjs +5 -3
  142. package/esm/session/page-session.mjs.map +1 -1
  143. package/esm/utils/auth-error-codes.d.mts +8 -1
  144. package/esm/utils/auth-error-codes.d.mts.map +1 -1
  145. package/esm/utils/auth-error-codes.mjs +7 -0
  146. package/esm/utils/auth-error-codes.mjs.map +1 -1
  147. package/esm/utils/normalize-credentials.mjs +32 -0
  148. package/esm/utils/normalize-credentials.mjs.map +1 -0
  149. package/esm/utils/safe-equal.mjs.map +1 -1
  150. package/esm/utils/token-digest.mjs +47 -0
  151. package/esm/utils/token-digest.mjs.map +1 -0
  152. package/esm/utils/token-expiry.d.mts +3 -1
  153. package/esm/utils/token-expiry.d.mts.map +1 -1
  154. package/esm/utils/token-expiry.mjs +7 -2
  155. package/esm/utils/token-expiry.mjs.map +1 -1
  156. package/llms-full.txt +72 -30
  157. package/llms.txt +2 -2
  158. package/package.json +9 -9
  159. package/skills/auth-basics/SKILL.md +9 -0
  160. package/skills/customize-token-storage/SKILL.md +10 -10
  161. package/skills/handle-login-and-logout/SKILL.md +2 -0
  162. package/skills/login-with-providers/SKILL.md +14 -3
  163. package/skills/manage-tokens/SKILL.md +6 -0
  164. package/skills/protect-routes/SKILL.md +5 -0
  165. package/skills/throttle-login-attempts/SKILL.md +23 -17
  166. package/skills/verify-email-and-reset-password/SKILL.md +3 -0
@@ -0,0 +1,47 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ //#region ../../packages/auth/src/utils/token-digest.ts
4
+ /**
5
+ * SHA-256 hex digest of a raw access or refresh token — what a token row
6
+ * stores instead of the token when `auth.hashTokensAtRest` is on.
7
+ */
8
+ function tokenDigest(token) {
9
+ return createHash("sha256").update(token).digest("hex");
10
+ }
11
+ const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
12
+ /**
13
+ * Whether a stored token value is a digest rather than a raw JWT. A JWT always
14
+ * contains dots, so the two forms cannot be confused.
15
+ */
16
+ function isTokenDigest(stored) {
17
+ return typeof stored === "string" && DIGEST_PATTERN.test(stored);
18
+ }
19
+ /**
20
+ * Every stored form a presented token may have: its digest (rows issued with
21
+ * `auth.hashTokensAtRest` on) and the raw value (rows issued with it off, or
22
+ * before it was turned on). Lookups match either, so switching the option in
23
+ * either direction never signs anyone out.
24
+ */
25
+ function storedTokenForms(token) {
26
+ return [tokenDigest(token), token];
27
+ }
28
+ /** Raw tokens of rows issued in this process, for handing back to the caller. */
29
+ const plainTokens = /* @__PURE__ */ new WeakMap();
30
+ /** Remember the raw token of a freshly issued row whose column holds a digest. */
31
+ function rememberPlainToken(row, token) {
32
+ if (typeof row === "object" && row !== null) plainTokens.set(row, token);
33
+ }
34
+ /**
35
+ * The raw token of a row: the one remembered at issue, else the stored value
36
+ * when it is not a digest. `undefined` for a hashed row loaded from storage —
37
+ * its raw token exists only with the client.
38
+ */
39
+ function plainTokenOf(row, stored) {
40
+ const remembered = plainTokens.get(row);
41
+ if (remembered !== void 0) return remembered;
42
+ return typeof stored === "string" && !isTokenDigest(stored) ? stored : void 0;
43
+ }
44
+
45
+ //#endregion
46
+ export { isTokenDigest, plainTokenOf, rememberPlainToken, storedTokenForms, tokenDigest };
47
+ //# sourceMappingURL=token-digest.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-digest.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-digest.ts"],"mappings":";;;;;;;AAMA,SAAgB,YAAY,OAAuB;CACjD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,MAAM,iBAAiB;;;;;AAMvB,SAAgB,cAAc,QAA0B;CACtD,OAAO,OAAO,WAAW,YAAY,eAAe,KAAK,MAAM;AACjE;;;;;;;AAQA,SAAgB,iBAAiB,OAAyB;CACxD,OAAO,CAAC,YAAY,KAAK,GAAG,KAAK;AACnC;;AAGA,MAAM,8BAAc,IAAI,QAAwB;;AAGhD,SAAgB,mBAAmB,KAAc,OAAqB;CACpE,IAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM,YAAY,IAAI,KAAK,KAAK;AACzE;;;;;;AAOA,SAAgB,aAAa,KAAa,QAAqC;CAC7E,MAAM,aAAa,YAAY,IAAI,GAAG;CAEtC,IAAI,eAAe,QAAW,OAAO;CAErC,OAAO,OAAO,WAAW,YAAY,CAAC,cAAc,MAAM,IAAI,SAAS;AACzE"}
@@ -25,7 +25,9 @@ export declare function tokenHasExpClaim(token: unknown): boolean;
25
25
  *
26
26
  * Two independent ways to answer "no", either of which is enough:
27
27
  * - the persisted expiry is unusable, so no date check can ever retire the row;
28
- * - the token itself carries no `exp`, so signature verification never retires it.
28
+ * - the token itself carries no `exp`, so signature verification never retires it
29
+ * (not checkable for a row stored as a digest, which this package only ever
30
+ * writes for tokens it signed with an `exp`).
29
31
  *
30
32
  * This is the predicate the `auth.purge-never-expiring` remediation selects on.
31
33
  */
@@ -1 +1 @@
1
- {"version":3,"file":"token-expiry.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-expiry.ts"],"mappings":";;;;;;;;;;;wBAqBgB,eAAe;;;;;;;;;;wBAef,iBAAiB;;;;;;;;;;wBAqBjB,gBAAgB,gBAAgB"}
1
+ {"version":3,"file":"token-expiry.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-expiry.ts"],"mappings":";;;;;;;;;;;wBAsBgB,eAAe;;;;;;;;;;wBAef,iBAAiB;;;;;;;;;;;;wBAuBjB,gBAAgB,gBAAgB"}
@@ -1,3 +1,4 @@
1
+ import { isTokenDigest } from "./token-digest.mjs";
1
2
  import { createDecoder } from "fast-jwt";
2
3
 
3
4
  //#region ../../packages/auth/src/utils/token-expiry.ts
@@ -46,12 +47,16 @@ function tokenHasExpClaim(token) {
46
47
  *
47
48
  * Two independent ways to answer "no", either of which is enough:
48
49
  * - the persisted expiry is unusable, so no date check can ever retire the row;
49
- * - the token itself carries no `exp`, so signature verification never retires it.
50
+ * - the token itself carries no `exp`, so signature verification never retires it
51
+ * (not checkable for a row stored as a digest, which this package only ever
52
+ * writes for tokens it signed with an `exp`).
50
53
  *
51
54
  * This is the predicate the `auth.purge-never-expiring` remediation selects on.
52
55
  */
53
56
  function isNeverExpiring(token, expiresAt) {
54
- return !isUsableExpiry(expiresAt) || !tokenHasExpClaim(token);
57
+ if (!isUsableExpiry(expiresAt)) return true;
58
+ if (isTokenDigest(token)) return false;
59
+ return !tokenHasExpClaim(token);
55
60
  }
56
61
 
57
62
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"token-expiry.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-expiry.ts"],"sourcesContent":["import { createDecoder } from \"fast-jwt\";\n\n/**\n * Payload decoder. Deliberately signature-*unaware*: these helpers answer\n * \"does this token carry a deadline at all\", which is a property of the claims,\n * not of the signature. Every caller that acts on the answer (the middleware,\n * the purge command) has already verified the signature or is about to delete\n * the row anyway.\n */\nconst decodePayload = createDecoder();\n\n/**\n * Whether a persisted `expires_at` can serve as a deadline at all.\n *\n * Answers `false` for absent, empty, and — the case that matters — `Invalid\n * Date`, which is what a pre-4.12.0 unparseable `expiresIn` wrote to the token\n * row. An `Invalid Date` compares `false` against *every* other date, so a row\n * holding one satisfies neither `expires_at < now` (cleanup never purges it)\n * nor `expires_at > now` (it never shows as an active session): it is outside\n * the reach of every date predicate rather than merely wrong.\n */\nexport function isUsableExpiry(value: unknown): boolean {\n if (value === undefined || value === null || value === \"\") return false;\n\n return !Number.isNaN(new Date(value as string | number | Date).getTime());\n}\n\n/**\n * Whether the JWT carries a finite numeric `exp` claim.\n *\n * This is the store-independent signal for a never-expiring credential: a\n * token with no `exp` has nothing for a verifier to check, so it verifies\n * indefinitely no matter what the row beside it says. An undecodable string\n * answers `false` — it cannot be shown to expire, and a row whose token cannot\n * even be parsed is unusable regardless.\n */\nexport function tokenHasExpClaim(token: unknown): boolean {\n if (typeof token !== \"string\" || token === \"\") return false;\n\n try {\n const payload = decodePayload(token) as { exp?: unknown } | null;\n\n return typeof payload?.exp === \"number\" && Number.isFinite(payload.exp);\n } catch {\n return false;\n }\n}\n\n/**\n * Whether a token row can ever stop being accepted on its own.\n *\n * Two independent ways to answer \"no\", either of which is enough:\n * - the persisted expiry is unusable, so no date check can ever retire the row;\n * - the token itself carries no `exp`, so signature verification never retires it.\n *\n * This is the predicate the `auth.purge-never-expiring` remediation selects on.\n */\nexport function isNeverExpiring(token: unknown, expiresAt: unknown): boolean {\n return !isUsableExpiry(expiresAt) || !tokenHasExpClaim(token);\n}\n"],"mappings":";;;;;;;;;;AASA,MAAM,gBAAgB,cAAc;;;;;;;;;;;AAYpC,SAAgB,eAAe,OAAyB;CACtD,IAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,IAAI,OAAO;CAElE,OAAO,CAAC,OAAO,MAAM,IAAI,KAAK,KAA+B,CAAC,CAAC,QAAQ,CAAC;AAC1E;;;;;;;;;;AAWA,SAAgB,iBAAiB,OAAyB;CACxD,IAAI,OAAO,UAAU,YAAY,UAAU,IAAI,OAAO;CAEtD,IAAI;EACF,MAAM,UAAU,cAAc,KAAK;EAEnC,OAAO,OAAO,SAAS,QAAQ,YAAY,OAAO,SAAS,QAAQ,GAAG;CACxE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAgB,gBAAgB,OAAgB,WAA6B;CAC3E,OAAO,CAAC,eAAe,SAAS,KAAK,CAAC,iBAAiB,KAAK;AAC9D"}
1
+ {"version":3,"file":"token-expiry.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-expiry.ts"],"mappings":";;;;;;;;;;;AAUA,MAAM,gBAAgB,cAAc;;;;;;;;;;;AAYpC,SAAgB,eAAe,OAAyB;CACtD,IAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,IAAI,OAAO;CAElE,OAAO,CAAC,OAAO,MAAM,IAAI,KAAK,KAA+B,CAAC,CAAC,QAAQ,CAAC;AAC1E;;;;;;;;;;AAWA,SAAgB,iBAAiB,OAAyB;CACxD,IAAI,OAAO,UAAU,YAAY,UAAU,IAAI,OAAO;CAEtD,IAAI;EACF,MAAM,UAAU,cAAc,KAAK;EAEnC,OAAO,OAAO,SAAS,QAAQ,YAAY,OAAO,SAAS,QAAQ,GAAG;CACxE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,OAAgB,WAA6B;CAC3E,IAAI,CAAC,eAAe,SAAS,GAAG,OAAO;CAKvC,IAAI,cAAc,KAAK,GAAG,OAAO;CAEjC,OAAO,CAAC,iBAAiB,KAAK;AAChC"}
package/llms-full.txt CHANGED
@@ -141,9 +141,18 @@ export default {
141
141
  rotation: true,
142
142
  maxPerUser: 5,
143
143
  },
144
+ hashTokensAtRest: true, // store only SHA-256 digests of access/refresh tokens
144
145
  };
145
146
  ```
146
147
 
148
+ ### Hardening options (5.53)
149
+
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
+ - `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
+ - `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.
154
+ - `Auth` hides `password` from serialized output (`static hidden = ["password"]`); a model that sets its own `hidden` must keep `"password"` in it.
155
+
147
156
  ### Token lifetimes are validated — a bad one throws
148
157
 
149
158
  `expiresIn` (both blocks) must be a duration string the [`ms`](https://github.com/vercel/ms) package parses to a **positive** number: `"1h"`, `"30m"`, `"7d"`, `"30 days"`, or `NO_EXPIRATION` (`"100y"`). Anything else throws on the first token issue, naming the key:
@@ -311,16 +320,16 @@ Token lookups go by the unique `token` string (`findByToken`), which already uni
311
320
 
312
321
  Your subclass inherits and may override these statics — the service calls them, never raw queries:
313
322
 
314
- | Static | Role |
315
- | ---------------------------------------------- | -------------------------------------------------------- |
316
- | `issue(user, token, …)` | persist a freshly-signed token (override to add columns) |
317
- | `findByToken(token)` | look a row up by its token string |
318
- | `findForUser(user, token)` | a user-scoped lookup (logout) |
319
- | `activeFor(user)` | active, unexpired sessions, newest-first |
320
- | `revokeAllFor(user)` / `revokeFamily(id)` | revoke a set, returning the revoked rows |
321
- | `enforceMax(user, max)` | cap concurrent refresh tokens |
322
- | `purgeExpired()` | delete expired rows (CLI cleanup) |
323
- | `findNeverExpiring()` / `purgeNeverExpiring()` | find/delete rows that can never expire (CLI remediation) |
323
+ | Static | Role |
324
+ | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
325
+ | `issue(user, token, …)` | persist a freshly-signed token (override to add columns); `token` is the value to store — the digest under `auth.hashTokensAtRest` |
326
+ | `findByToken(token)` | look a row up by its token string — must match the stored digest **or** the raw value (`whereIn("token", [sha256(token), token])`) |
327
+ | `findForUser(user, token)` | a user-scoped lookup (logout), same two forms |
328
+ | `activeFor(user)` | active, unexpired sessions, newest-first |
329
+ | `revokeAllFor(user)` / `revokeFamily(id)` | revoke a set, returning the revoked rows |
330
+ | `enforceMax(user, max)` | cap concurrent refresh tokens |
331
+ | `purgeExpired()` | delete expired rows (CLI cleanup) |
332
+ | `findNeverExpiring()` / `purgeNeverExpiring()` | find/delete rows that can never expire (CLI remediation) |
324
333
 
325
334
  Plus two instance getters, both of which the route gate consults on every request:
326
335
 
@@ -606,6 +615,8 @@ authService.login(User, { username: "ada", password: "..." });
606
615
  authService.login(User, { phone: "+1...", password: hashedOTP });
607
616
  ```
608
617
 
618
+ Identifiers are normalized before the lookup: string values are trimmed and `email` is lower-cased (`" Sara@x.io"` finds `sara@x.io`). If that finds no user and the normalized value differs from what was sent (trimmed), the lookup is retried once with the value as sent, so legacy rows stored with capitals still log in. The login throttle buckets by the same trimmed, lower-cased email. Configure with `auth.normalizeCredentials`: a function `(identifiers) => identifiers` (everything except `password`), or `false` for exact matching (the function type is `NormalizeCredentials`). Store new emails lower-cased.
619
+
609
620
  For lower-level credential verification (just check, don't issue tokens), use `authService.attemptLogin(Model, credentials)` — returns the user or null without creating tokens.
610
621
 
611
622
  ## Device info
@@ -727,7 +738,7 @@ For cookie sessions read by `@warlock.js/web` pages, log in with `authService.lo
727
738
 
728
739
  ---
729
740
  name: login-with-providers
730
- description: 'Log in without a password — Google (OIDC code + PKCE + state + nonce, id_token verified with `jose`), GitHub, Discord, LinkedIn, Apple (`form_post` callback), Facebook and X, passkeys (WebAuthn via `@simplewebauthn/server`) and phone one-time codes (delivered through a `@warlock.js/notifications` channel). Every method ends in `authService.completeLogin(user)`, the same tokens, rows and events as password login. `startProviderLogin`, `completeProviderLogin`, `generatePasskeyRegistrationOptions`, `verifyPasskeyRegistration`, `generatePasskeyAuthenticationOptions`, `verifyPasskeyAuthentication`, `requestOtp`, `verifyOtp`, `otpRequestThrottleMiddleware`, `otpVerifyThrottleMiddleware`, `AuthProvider`. Triggers: "login with Google", "sign in with Google", "login with GitHub", "Sign in with Apple", "login with Discord", "login with LinkedIn", "login with Facebook", "login with X", `auth.providers.github`, "OAuth", "OIDC", "passkeys", "WebAuthn", "passwordless", "SMS code login", "WhatsApp OTP", "phone login", `warlock add auth-google`, `warlock add auth-passkeys`, `AuthProviderSdkMissingError`, `InvalidProviderCallbackError`, `ProviderEmailNotVerifiedError`, `InvalidPasskeyError`, `EC009`, `EC010`, `EC011`, `auth.providers`, `auth.passkeys`, `auth.otp`; typical import `import { completeProviderLogin, verifyOtp } from "@warlock.js/auth"`. Skip: password login — the `handle-login-and-logout` topic; email tokens — the `verify-email-and-reset-password` topic; defining an SMS channel — the `define-channel` topic of the `warlock-js-notifications` skill.'
741
+ description: 'Log in without a password — Google (OIDC code + PKCE + state + nonce, id_token verified with `jose`), GitHub, Discord, LinkedIn, Apple (`form_post` callback), Facebook and X, passkeys (WebAuthn via `@simplewebauthn/server`) and phone one-time codes (delivered through a `@warlock.js/notifications` channel). Every method ends in `authService.completeLogin(user)`, the same tokens, rows and events as password login. `startProviderLogin`, `completeProviderLogin`, `generatePasskeyRegistrationOptions`, `verifyPasskeyRegistration`, `generatePasskeyAuthenticationOptions`, `verifyPasskeyAuthentication`, `requestOtp`, `verifyOtp`, `otpRequestThrottleMiddleware`, `otpVerifyThrottleMiddleware`, `AuthProvider`. Triggers: "login with Google", "sign in with Google", "login with GitHub", "Sign in with Apple", "login with Discord", "login with LinkedIn", "login with Facebook", "login with X", `auth.providers.github`, "OAuth", "OIDC", "passkeys", "WebAuthn", "passwordless", "SMS code login", "WhatsApp OTP", "phone login", `warlock add auth-google`, `warlock add auth-passkeys`, `AuthProviderSdkMissingError`, `InvalidProviderCallbackError`, `ProviderEmailNotVerifiedError`, `ProviderAccountLinkBlockedError`, `ProviderLinkExisting`, `InvalidPasskeyError`, `EC009`, `EC010`, `EC011`, `EC012`, `auth.providers`, `auth.passkeys`, `auth.otp`; typical import `import { completeProviderLogin, verifyOtp } from "@warlock.js/auth"`. Skip: password login — the `handle-login-and-logout` topic; email tokens — the `verify-email-and-reset-password` topic; defining an SMS channel — the `define-channel` topic of the `warlock-js-notifications` skill.'
731
742
  ---
732
743
 
733
744
  # Login with an OAuth provider, passkeys, or a phone code
@@ -790,6 +801,7 @@ Client side, the button is just a link. It must be a top-level navigation, not a
790
801
  - `state`, `nonce` and the PKCE verifier go into a signed, 10-minute, HttpOnly `auth_provider_state` cookie (SameSite=Lax, so it survives Google's redirect back). The callback clears the cookie, so a started login can complete only once.
791
802
  - The callback rejects, with `InvalidProviderCallbackError` (400, `EC009`): a missing, forged or expired cookie, a `state` mismatch, a `?error=` from Google, a failed code exchange, and an id_token with a bad signature, `iss`, `aud`, `exp` or `nonce`. `error.reason` says which. The response message is generic.
792
803
  - **Linking.** An existing `provider_accounts` row (provider plus Google `sub`) always decides the user. Without one, the Google email must be verified (`email_verified: true`), or the call throws `ProviderEmailNotVerifiedError` (403, `EC010`) and nothing is linked or created. A verified email links the matching user, or creates one with `{ email, name, emailVerifiedAt: now }`.
804
+ - **Linking an existing account** follows `auth.providers.linkExisting` (type `ProviderLinkExisting`, default `"verified"`): the account found by email is linked only if it verified that address itself (`auth.verification.field` set); otherwise `ProviderAccountLinkBlockedError` (403, `EC012`) is thrown and nothing is linked — this stops a pre-registered account (attacker knows its password) from being merged with the real owner. A user model whose schema has no verification field links as before. `"always"` restores the old behaviour; `"never"` never links by email.
793
805
  - Other OIDC providers: implement `AuthProvider` (`authorizationUrl(state)`, `handleCallback({ query, expected })`) and register it under `auth.providers.custom.<name>`.
794
806
 
795
807
  ### Google request deadlines and controlled providers
@@ -829,6 +841,8 @@ The implementation uses the `jose` 6 `customFetch` and `timeoutDuration` options
829
841
  Same shape as Google: a config block under `auth.providers.<name>`, a GET
830
842
  route that redirects to `startProviderLogin(response, "<name>")`, and a GET
831
843
  callback that calls `completeProviderLogin(User, "<name>", request, response)`.
844
+ Every provider (Apple, Facebook and X too) takes `timeoutMs` (positive integer,
845
+ default `5000`): the deadline for each token, profile and key-set request.
832
846
 
833
847
  ```ts
834
848
  // src/config/auth.ts
@@ -954,9 +968,17 @@ router.get("/auth/x/callback", async ({ request, response }) => {
954
968
  ## Passkeys
955
969
 
956
970
  ```ts
957
- passkeys: { rpID: "example.com", rpName: "Example", origin: "https://example.com" },
971
+ passkeys: {
972
+ rpID: "example.com",
973
+ rpName: "Example",
974
+ origin: "https://example.com",
975
+ userVerification: "preferred", // default; "required" refuses assertions without PIN/biometric
976
+ },
958
977
  ```
959
978
 
979
+ Throttle the anonymous `/auth/passkeys/login/options` route (each call stores
980
+ a challenge row): `loginThrottleMiddleware({ by: ["ip"], isFailure: () => true, max: 30, window: "1m" })`.
981
+
960
982
  ```ts
961
983
  // Register (logged in)
962
984
  router.post(
@@ -1049,7 +1071,7 @@ router.post(
1049
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.
1050
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.
1051
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.
1052
- - **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`.
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.
1053
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.
1054
1076
 
1055
1077
  ## Gotchas
@@ -1107,6 +1129,10 @@ const pair = await authService.createTokenPair(user, deviceInfo);
1107
1129
 
1108
1130
  `createTokenPair` is the typical issuance path. It respects `config.auth.refreshToken.enabled` — if disabled, returns only `accessToken`.
1109
1131
 
1132
+ A custom `payload` (`generateAccessToken(user, payload)` / `deviceInfo.payload`) may add claims, but `id` and `userType` are always stamped from `user`; the route gate also refuses a token whose claims name a different user than its row.
1133
+
1134
+ With `auth.hashTokensAtRest: true` the token columns hold SHA-256 digests. `createTokenPair` / `login` still return the raw tokens; the row `createRefreshToken` returns exposes its raw token as `row.plainToken` (`row.get("token")` is the digest).
1135
+
1110
1136
  ## Refresh with rotation — `refreshTokens`
1111
1137
 
1112
1138
  Refresh and family revocation use durable family revision checks inside a
@@ -1250,6 +1276,8 @@ If tokens minted before 4.12.0 may lack an `exp`, see `warlock auth.purge-never-
1250
1276
 
1251
1277
  `authService.generateAccessToken` / `createRefreshToken` read `config.auth.accessToken.expiresIn` / `config.auth.refreshToken.expiresIn`, validate them, and throw naming the key if the value is not a positive `ms` duration — before anything is signed, persisted, or capped.
1252
1278
 
1279
+ `config.auth.accessToken.issuer` / `audience` (optional) are stamped as `iss` / `aud` on every token `jwt.generate` / `generateRefreshToken` sign and **required** by `jwt.verify` / `verifyRefreshToken` — tokens signed before they were set are refused. The verifier and signer are prepared once per settings and reused (no per-request key parsing); passing your own extra options builds a fresh one.
1280
+
1253
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.
1254
1282
 
1255
1283
  ## Things NOT to do
@@ -1355,6 +1383,9 @@ A token passes three separate checks, in order — a token can fail any one of t
1355
1383
  1. **The JWT verifies** — signature, algorithm, `tokenType`, and (since 4.12.0) the presence of an `exp` claim that has not passed. A token with _no_ `exp` is rejected: there is no deadline to check, so it would otherwise verify indefinitely.
1356
1384
  2. **The access-token row still exists** — deleting it (logout) invalidates the token immediately, before its JWT expiry.
1357
1385
  3. **The row's own `expires_at` has not passed** (since 4.12.0). The database is the authority on the session: a row whose expiry has elapsed is rejected and deleted, even if the JWT itself is still within its lifetime. A row with a missing or unparseable `expires_at` is treated as expired, not as never-expiring.
1386
+ 4. **The claims name the row's user** (since 5.53): the token's `id` (and `userType`, when present) must equal the row's `user_id` / `user_type`, or it is `InvalidAccessToken`.
1387
+
1388
+ Expired or malformed tokens and CSRF Origin mismatches are logged at `debug`, not `error` — any anonymous client can produce them.
1358
1389
 
1359
1390
  Missing or invalid credentials return 401; an authenticated disallowed user type returns 403:
1360
1391
 
@@ -1557,6 +1588,8 @@ export default {
1557
1588
 
1558
1589
  The cookie name `setAuthCookie`/`clearAuthCookie` write **must match** the name a `cookie:<name>` token source reads — they are not linked automatically.
1559
1590
 
1591
+ `auth.cookie.hostPrefix: true` (default `false`) writes the auth cookies as `__Host-<name>` with `Secure`, so a subdomain or plain-HTTP page cannot plant or overwrite them. It requires `path: "/"` and no Domain (`cookie.cookieDomain`, `options.domain`, `http.cookies.options.domain`); a write that breaks this throws naming the setting. Reads (`cookie:<name>` sources, `pageSession`) try `__Host-<name>` first and fall back to `<name>`, and the clear helpers remove both, so switching it on signs no one out.
1592
+
1560
1593
  ### CSRF: an automatic Origin check on cookie-authenticated writes
1561
1594
 
1562
1595
  Cookie auth changes the CSRF picture that bearer-token auth doesn't have: a browser attaches cookies to same-site requests it didn't originate. `SameSite=Lax` already blocks the classic cross-site `<form method="post">` case, but not a same-site GET redirect chain or a client that ignores `SameSite`.
@@ -1938,14 +1971,14 @@ Register it the same way as the bundled commands — call the factory inside `de
1938
1971
 
1939
1972
  ---
1940
1973
  name: throttle-login-attempts
1941
- description: 'Brute-force / credential-stuffing protection via `loginThrottleMiddleware` — a failure-aware route gate that counts only failed logins (resets on success), locks per-account and per-source after a threshold, and rejects pre-controller with 429 so the DB lookup and bcrypt verify are skipped. Cache-backed (shared across replicas), fixed-window, fails open on a cache outage. Triggers: `loginThrottleMiddleware`, `AuthErrorCodes.TooManyAttempts`, `EC004`, "rate limit login", "brute force protection", "lock account after failed logins", "throttle login attempts", "too many login attempts 429"; typical import `import { loginThrottleMiddleware } from "@warlock.js/auth"`. Skip: generic per-route request rate limiting that counts every request (use core `middleware.rateLimit`); gating a route by auth — the `protect-routes` topic; issuing tokens — the `handle-login-and-logout` topic.'
1974
+ description: 'Brute-force / credential-stuffing protection via `loginThrottleMiddleware` — a failure-aware route gate that counts each attempt as it arrives and resets on a successful login, locks per-account and per-source after a threshold, and rejects pre-controller with 429 so the DB lookup and bcrypt verify are skipped. Cache-backed (shared across replicas), fixed-window, fails open on a cache outage. Triggers: `loginThrottleMiddleware`, `AuthErrorCodes.TooManyAttempts`, `EC004`, "rate limit login", "brute force protection", "lock account after failed logins", "throttle login attempts", "too many login attempts 429"; typical import `import { loginThrottleMiddleware } from "@warlock.js/auth"`. Skip: generic per-route request rate limiting that counts every request (use core `middleware.rateLimit`); gating a route by auth — the `protect-routes` topic; issuing tokens — the `handle-login-and-logout` topic.'
1942
1975
  ---
1943
1976
 
1944
1977
  # Throttle login attempts with `loginThrottleMiddleware`
1945
1978
 
1946
1979
  `loginThrottleMiddleware(options?)` returns a Warlock middleware that defends the login (and refresh / password-reset) routes against brute-force and credential-stuffing — without punishing a user who fat-fingers a password then gets it right.
1947
1980
 
1948
- The trick that makes it different from a plain rate limiter: it's **failure-aware**. It hooks the response _after_ your controller runs (`response.onSent`), counts only the attempts that actually failed, and **clears the counter the moment a login succeeds**. A generic request limiter can't do that — it runs before the controller and counts every hit, success or not.
1981
+ The trick that makes it different from a plain rate limiter: it's **failure-aware**. It counts each attempt before your controller runs (so concurrent bursts cannot outrun the limit), hooks the response _after_ the controller (`response.onSent`), locks only when a failure used the last allowed attempt, and **clears the counter the moment a login succeeds**. A generic request limiter can't do that — it counts every hit and never resets on success.
1949
1982
 
1950
1983
  ## The shortest version
1951
1984
 
@@ -1992,8 +2025,8 @@ router.post("/auth/reset-password", resetPasswordController, {
1992
2025
 
1993
2026
  ## How it behaves
1994
2027
 
1995
- 1. **Before the controller** — if the account or the IP is currently locked, it short-circuits with `429` and never touches the database or the bcrypt verify (this is also what neutralises the CPU-DoS angle of brute-forcing). The body carries `AuthErrorCodes.TooManyAttempts` (`EC004`).
1996
- 2. **After the controller** — it inspects the outcome. A non-2xx response is a failed login: it bumps a fixed-window counter for each tracked identifier, and once a counter reaches `max` it writes a lock key. A 2xx response is a success: it **clears** the counter and lock for that identifier.
2028
+ 1. **Before the controller** — if the account or the IP is currently locked, it short-circuits with `429` and never touches the database or the bcrypt verify (this is also what neutralises the CPU-DoS angle of brute-forcing). The body carries `AuthErrorCodes.TooManyAttempts` (`EC004`). Otherwise it **counts the attempt right away** (fixed-window counter per identifier) and answers `429` once the count passes `max`, so a burst of concurrent requests cannot outrun the limit: at most `max` attempts per window reach the controller.
2029
+ 2. **After the controller** — it inspects the outcome. A non-2xx response that used the last allowed attempt writes the lock key (the counter is rewritten with the lock's TTL so both end together), unless a success that finished meanwhile already reset the counter. A 2xx response is a success: it **resets** the counter to 0 and clears the lock for that identifier. If the counter cannot be read back (expired, evicted, a failed read), the failure locks: the check fails closed.
1997
2030
 
1998
2031
  Per-account tracking stops a password-spray against one user from many IPs; per-source tracking stops one IP from stuffing many accounts. A lock on **either** identifier rejects the request — defense-in-depth.
1999
2032
 
@@ -2022,16 +2055,22 @@ loginThrottleMiddleware({
2022
2055
  });
2023
2056
  ```
2024
2057
 
2025
- | Option | Default | Purpose |
2026
- | ----------------- | ---------------------------------- | ----------------------------------------- |
2027
- | `max` | `5` | Failures within the window before lockout |
2028
- | `window` | `"15m"` | Counting window (`ms`-string or seconds) |
2029
- | `lockoutDuration` | `"15m"` | Lock TTL once tripped |
2030
- | `by` | `["email", "ip"]` | Identifiers tracked independently |
2031
- | `identifierKey` | `"email"` | Credential field used as the account key |
2032
- | `errorMessage` | i18n `auth.errors.tooManyAttempts` | 429 message override |
2033
- | `isFailure` | `(res) => !res.isOk` | What counts as a failed attempt |
2034
- | `identify` | built-in email + ip extraction | Custom identifier list |
2058
+ | Option | Default | Purpose |
2059
+ | ----------------- | ---------------------------------- | --------------------------------------------------------------------- |
2060
+ | `max` | `5` | Failures within the window before lockout |
2061
+ | `window` | `"15m"` | Counting window (`ms`-string or seconds) |
2062
+ | `lockoutDuration` | `"15m"` | Lock TTL once tripped |
2063
+ | `by` | `["email", "ip"]` | Identifiers tracked independently |
2064
+ | `identifierKey` | `"email"` | Credential field used as the account key |
2065
+ | `errorMessage` | i18n `auth.errors.tooManyAttempts` | 429 message override |
2066
+ | `isFailure` | `(res) => !res.isOk` | What counts as a failed attempt |
2067
+ | `identify` | built-in email + ip extraction | Custom identifier list |
2068
+ | `emailLock` | `"global"` | `"pair"` locks the (email, IP) pair instead of the email for everyone |
2069
+ | `accountMax` | `max * 10` | Email-wide limit across all IPs when `emailLock: "pair"` |
2070
+
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.
2072
+
2073
+ Throttle the anonymous passkey options route the same way, counting every request: `loginThrottleMiddleware({ by: ["ip"], isFailure: () => true, max: 30, window: "1m" })`.
2035
2074
 
2036
2075
  ## The 429 response
2037
2076
 
@@ -2061,7 +2100,7 @@ router.post("/auth/forgot-password", forgotController, {
2061
2100
 
2062
2101
  | | `loginThrottleMiddleware` (auth) | `middleware.rateLimit` (core) |
2063
2102
  | ---------------------------- | -------------------------------------------- | ----------------------------- |
2064
- | Counts | only **failed** logins | **every** request |
2103
+ | Counts | every attempt, until a login succeeds | **every** request |
2065
2104
  | Resets on a successful login | yes | no |
2066
2105
  | Locks per account / per IP | yes | per key (default IP) |
2067
2106
  | Storage | `@warlock.js/cache` (shared across replicas) | in-process map |
@@ -2071,8 +2110,8 @@ They compose. For a hard ceiling on request volume _and_ failure-aware account l
2071
2110
  ## Gotchas
2072
2111
 
2073
2112
  - **Needs an initialised cache driver.** Storage is `@warlock.js/cache` (a peer dep, transitively present via core). If the driver isn't configured at runtime, the middleware **fails open** — it logs and lets the request through, because a throttle outage must never become an auth outage. That also means: no cache, no protection. Verify your cache config in production.
2074
- - **Account lockout can be weaponised.** An attacker who knows a victim's email can lock them out by spamming failures. The per-IP counter mitigates this (the attacker's IP locks too), but for purely anonymous endpoints prefer `by: ["ip"]`. For high-value accounts, consider a CAPTCHA step instead of a hard lock.
2075
- - **Counts are atomic and exact across servers (redis/pg).** Each failure does a create-only `cache.set(key, 0, { ttl: window })` (only the first failure opens the window and sets the TTL) followed by an atomic `cache.increment(key, 1, { ttl: window })`, so concurrent failures on different servers are never lost. Passing the TTL on the increment also expires a counter recreated after its seed expires, without extending an existing window. The memory cache driver is per-process — counts and locks are then per-process, so use redis/pg when running more than one instance.
2113
+ - **Account lockout can be weaponised.** With the default `emailLock: "global"`, an attacker who knows a victim's email can lock them out by spamming failures. Set `emailLock: "pair"` to lock the (email, IP) pair instead; for purely anonymous endpoints prefer `by: ["ip"]`. For high-value accounts, consider a CAPTCHA step instead of a hard lock.
2114
+ - **Counts are atomic and exact across servers (redis/pg).** Each attempt does a create-only `cache.set(key, 0, { ttl: window })` (only the first failure opens the window and sets the TTL) followed by an atomic `cache.increment(key, 1, { ttl: window })`, so concurrent failures on different servers are never lost. Passing the TTL on the increment also expires a counter recreated after its seed expires, without extending an existing window. The memory cache driver is per-process — counts and locks are then per-process, so use redis/pg when running more than one instance.
2076
2115
  - **Account and IP keys are hashed.** The built-in extractor keys both by an HMAC of the trimmed, lower-cased value (`email.<hmac>`, `ip.<hmac>`), keyed from `auth.accessToken.secret`, so cache logs never show the address or IP and a list of known emails cannot reverse the key. Without a configured secret it falls back to SHA-256. A custom `identify` is used as is — hash personal values yourself (`throttleIdentifierHash(kind, value)` is exported).
2077
2116
  - **Fixed window, not sliding.** The window is anchored at the first failure and does not extend on each subsequent one — predictable lockout timing. The lock key is independent and always lasts `lockoutDuration`: the lock stores its own deadline, so even a sliding-expiry driver (`memoryExtended`) cannot extend it.
2078
2117
  - **Needs a real cache driver.** The `null` driver stores nothing, so the throttle never locks; it warns once when that happens. On Redis, any version from 6 works.
@@ -2176,6 +2215,8 @@ router.post("/auth/reset-password", resetPasswordController, {
2176
2215
  });
2177
2216
  ```
2178
2217
 
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.
2219
+
2179
2220
  `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`.
2180
2221
 
2181
2222
  **Password hashing.** By default auth saves `hashPassword(plain)` and checks it with `verifyPassword`, the same check login uses. If your model hashes on save (`useHashedPassword()`), that first write gets hashed twice and fails the check, so auth saves the plaintext and lets your transformer hash it once. If neither write passes the check, it throws. Plaintext is never the first thing written. To write it yourself, set `auth.passwordReset.setPassword`.
@@ -2208,6 +2249,7 @@ const authConfigurations: AuthConfigurations = {
2208
2249
  setPassword: async (user, plain) => {
2209
2250
  /* optional */
2210
2251
  },
2252
+ awaitDelivery: false, // default: send in the background (anti-enumeration timing)
2211
2253
  },
2212
2254
  oneTimeToken: { model: AppOneTimeToken }, // optional model override
2213
2255
  };
package/llms.txt CHANGED
@@ -11,10 +11,10 @@
11
11
  - [customize-token-storage](@warlock.js/auth/skills/customize-token-storage/SKILL.md): Override the persisted AccessToken / RefreshToken models to add columns (multi-tenant `organization_id`, device metadata), rename, or change storage — without forking the package. Extend the model + `schema.extend(...)`, register it under `config.auth.accessToken.model` / `config.auth.refreshToken.model`, override `issue()` to populate the new column, and add a migration. Triggers: `accessToken.model`, `refreshToken.model`, `AccessToken.issue`, `RefreshToken.issue`, `accessTokenSchema`, `refreshTokenSchema`, "add a column to the token table", "multi-tenant tokens", "organization_id on access token", "override the token model", "custom token storage"; typical import `import { AccessToken, accessTokenSchema } from "@warlock.js/auth"`. Skip: multiple user TYPES (not token storage) — the `customize-user-type` topic; the token lifecycle API — the `manage-tokens` topic; the config blocks themselves — the `auth-basics` topic.
12
12
  - [customize-user-type](@warlock.js/auth/skills/customize-user-type/SKILL.md): Support multiple user types (user / admin / client / staff) in one auth system — each Auth subclass overrides userType, config.auth.userType.<slug> maps slug to model class, authMiddleware('admin') gates per type. Triggers: `Auth`, `userType`, `config.auth.userType`, `Authenticable`, `@RegisterModel`, `confirmPassword`; "add admins and users", "multiple user types", "separate client and vendor personas", "per-type login"; typical import `import { Auth } from "@warlock.js/auth"`. Skip: `authMiddleware` semantics — the `protect-routes` topic; login flow — the `handle-login-and-logout` topic; RBAC libs `casl`, `accesscontrol`, `rbac`.
13
13
  - [handle-login-and-logout](@warlock.js/auth/skills/handle-login-and-logout/SKILL.md): Run the full login flow via authService.login(Model, credentials, deviceInfo?) — verify password, create access + refresh token pair, fire events. Logout via authService.logout(user, accessToken?, refreshToken?) revokes tokens. Triggers: `authService.login`, `authService.logout`, `authService.attemptLogin`, `authService.refreshTokens`, `authService.revokeAllTokens`, `authEvents`; "build a login endpoint", "POST /login controller", "logout from all devices", "verify credentials and issue tokens"; typical import `import { authService, authEvents } from "@warlock.js/auth"`. Skip: token internals — the `manage-tokens` topic; sign-up — the `register-user` topic; competing libs `passport-local`, `next-auth` credentials.
14
- - [login-with-providers](@warlock.js/auth/skills/login-with-providers/SKILL.md): Log in without a password — Google (OIDC code + PKCE + state + nonce, id_token verified with `jose`), GitHub, Discord, LinkedIn, Apple (`form_post` callback), Facebook and X, passkeys (WebAuthn via `@simplewebauthn/server`) and phone one-time codes (delivered through a `@warlock.js/notifications` channel). Every method ends in `authService.completeLogin(user)`, the same tokens, rows and events as password login. `startProviderLogin`, `completeProviderLogin`, `generatePasskeyRegistrationOptions`, `verifyPasskeyRegistration`, `generatePasskeyAuthenticationOptions`, `verifyPasskeyAuthentication`, `requestOtp`, `verifyOtp`, `otpRequestThrottleMiddleware`, `otpVerifyThrottleMiddleware`, `AuthProvider`. Triggers: "login with Google", "sign in with Google", "login with GitHub", "Sign in with Apple", "login with Discord", "login with LinkedIn", "login with Facebook", "login with X", `auth.providers.github`, "OAuth", "OIDC", "passkeys", "WebAuthn", "passwordless", "SMS code login", "WhatsApp OTP", "phone login", `warlock add auth-google`, `warlock add auth-passkeys`, `AuthProviderSdkMissingError`, `InvalidProviderCallbackError`, `ProviderEmailNotVerifiedError`, `InvalidPasskeyError`, `EC009`, `EC010`, `EC011`, `auth.providers`, `auth.passkeys`, `auth.otp`; typical import `import { completeProviderLogin, verifyOtp } from "@warlock.js/auth"`. Skip: password login — the `handle-login-and-logout` topic; email tokens — the `verify-email-and-reset-password` topic; defining an SMS channel — the `define-channel` topic of the `warlock-js-notifications` skill.
14
+ - [login-with-providers](@warlock.js/auth/skills/login-with-providers/SKILL.md): Log in without a password — Google (OIDC code + PKCE + state + nonce, id_token verified with `jose`), GitHub, Discord, LinkedIn, Apple (`form_post` callback), Facebook and X, passkeys (WebAuthn via `@simplewebauthn/server`) and phone one-time codes (delivered through a `@warlock.js/notifications` channel). Every method ends in `authService.completeLogin(user)`, the same tokens, rows and events as password login. `startProviderLogin`, `completeProviderLogin`, `generatePasskeyRegistrationOptions`, `verifyPasskeyRegistration`, `generatePasskeyAuthenticationOptions`, `verifyPasskeyAuthentication`, `requestOtp`, `verifyOtp`, `otpRequestThrottleMiddleware`, `otpVerifyThrottleMiddleware`, `AuthProvider`. Triggers: "login with Google", "sign in with Google", "login with GitHub", "Sign in with Apple", "login with Discord", "login with LinkedIn", "login with Facebook", "login with X", `auth.providers.github`, "OAuth", "OIDC", "passkeys", "WebAuthn", "passwordless", "SMS code login", "WhatsApp OTP", "phone login", `warlock add auth-google`, `warlock add auth-passkeys`, `AuthProviderSdkMissingError`, `InvalidProviderCallbackError`, `ProviderEmailNotVerifiedError`, `ProviderAccountLinkBlockedError`, `ProviderLinkExisting`, `InvalidPasskeyError`, `EC009`, `EC010`, `EC011`, `EC012`, `auth.providers`, `auth.passkeys`, `auth.otp`; typical import `import { completeProviderLogin, verifyOtp } from "@warlock.js/auth"`. Skip: password login — the `handle-login-and-logout` topic; email tokens — the `verify-email-and-reset-password` topic; defining an SMS channel — the `define-channel` topic of the `warlock-js-notifications` skill.
15
15
  - [manage-tokens](@warlock.js/auth/skills/manage-tokens/SKILL.md): Token lifecycle — generateAccessToken, createRefreshToken, createTokenPair, refreshTokens (with rotation + replay detection), revokeAllTokens, revokeTokenFamily, cleanupExpiredTokens, getActiveSessions. Triggers: `createTokenPair`, `refreshTokens`, `revokeTokenFamily`, `cleanupExpiredTokens`, `getActiveSessions`, `jwt.generate`, `jwt.verify`, `AccessToken`, `RefreshToken`; "rotate refresh tokens", "detect token replay", "logout from all devices", "list active sessions", "clean up expired tokens"; typical import `import { authService, jwt } from "@warlock.js/auth"`. Skip: login flow — the `handle-login-and-logout` topic; CLI cleanup — the `run-auth-commands` topic; competing libs `jsonwebtoken`, `jose`, `fast-jwt`.
16
16
  - [protect-routes](@warlock.js/auth/skills/protect-routes/SKILL.md): Gate HTTP routes via authMiddleware(allowedUserType) — the argument is required and a valid token is always required: [] allows any authenticated user, a user-type restricts to those types. Sets request.locals.user + request.decodedAccessToken on success, 401 on failure. Triggers: `authMiddleware`, `request.locals.user`, `request.decodedAccessToken`, `AuthErrorCodes`, `MissingAccessToken`, `InvalidAccessToken`; "how do I protect a route", "restrict route by user type", "require any logged-in user"; typical import `import { authMiddleware } from "@warlock.js/auth"`. Skip: multi-user-type config — the `customize-user-type` topic; issuing the token — the `handle-login-and-logout` topic; competing libs `passport`, `express-jwt`, `next-auth` middleware.
17
17
  - [register-user](@warlock.js/auth/skills/register-user/SKILL.md): Sign up a new user and issue the initial token pair — User.create({...password: await hashPassword(plain)}) then authService.createTokenPair(user). Triggers: `User.create`, `hashPassword`, `verifyPassword`, `authService.createTokenPair`, `toJsonColumns`, `strongPassword`, `authEvents`; "build a register endpoint", "POST /register controller", "sign up a new user", "hash password on signup", "email verification flow"; typical import `import { authService } from "@warlock.js/auth"; import { hashPassword } from "@warlock.js/core"`. Skip: login — the `handle-login-and-logout` topic; token internals — the `manage-tokens` topic; competing libs `bcrypt`, `bcryptjs`, `argon2`.
18
18
  - [run-auth-commands](@warlock.js/auth/skills/run-auth-commands/SKILL.md): Three bundled CLI commands — warlock jwt.generate (creates strong JWT secret + writes to .env), warlock auth.cleanup (removes expired refresh tokens), and warlock auth.purge-never-expiring (finds and revokes token rows that can never expire). Register via registerJWTSecretGeneratorCommand(), registerAuthCleanupCommand() and registerAuthPurgeNeverExpiringCommand(). Triggers: `registerJWTSecretGeneratorCommand`, `registerAuthCleanupCommand`, `registerAuthPurgeNeverExpiringCommand`, `warlock jwt.generate`, `warlock auth.cleanup`, `warlock auth.purge-never-expiring`, `cleanupExpiredTokens`, `purgeNeverExpiringTokens`, `command`; "token never expires", "no exp claim", "Invalid Date expires_at"; "generate JWT secret", "bootstrap .env JWT_SECRET", "cron job for expired tokens", "schedule auth cleanup"; typical import `import { registerJWTSecretGeneratorCommand, registerAuthCleanupCommand, registerAuthPurgeNeverExpiringCommand } from "@warlock.js/auth"`. Skip: programmatic cleanup — the `manage-tokens` topic; in-process scheduling — the `scheduler-basics` topic of the `warlock-js-scheduler` skill; competing tools `dotenv-cli`, `node-cron`.
19
- - [throttle-login-attempts](@warlock.js/auth/skills/throttle-login-attempts/SKILL.md): Brute-force / credential-stuffing protection via `loginThrottleMiddleware` — a failure-aware route gate that counts only failed logins (resets on success), locks per-account and per-source after a threshold, and rejects pre-controller with 429 so the DB lookup and bcrypt verify are skipped. Cache-backed (shared across replicas), fixed-window, fails open on a cache outage. Triggers: `loginThrottleMiddleware`, `AuthErrorCodes.TooManyAttempts`, `EC004`, "rate limit login", "brute force protection", "lock account after failed logins", "throttle login attempts", "too many login attempts 429"; typical import `import { loginThrottleMiddleware } from "@warlock.js/auth"`. Skip: generic per-route request rate limiting that counts every request (use core `middleware.rateLimit`); gating a route by auth — the `protect-routes` topic; issuing tokens — the `handle-login-and-logout` topic.
19
+ - [throttle-login-attempts](@warlock.js/auth/skills/throttle-login-attempts/SKILL.md): Brute-force / credential-stuffing protection via `loginThrottleMiddleware` — a failure-aware route gate that counts each attempt as it arrives and resets on a successful login, locks per-account and per-source after a threshold, and rejects pre-controller with 429 so the DB lookup and bcrypt verify are skipped. Cache-backed (shared across replicas), fixed-window, fails open on a cache outage. Triggers: `loginThrottleMiddleware`, `AuthErrorCodes.TooManyAttempts`, `EC004`, "rate limit login", "brute force protection", "lock account after failed logins", "throttle login attempts", "too many login attempts 429"; typical import `import { loginThrottleMiddleware } from "@warlock.js/auth"`. Skip: generic per-route request rate limiting that counts every request (use core `middleware.rateLimit`); gating a route by auth — the `protect-routes` topic; issuing tokens — the `handle-login-and-logout` topic.
20
20
  - [verify-email-and-reset-password](@warlock.js/auth/skills/verify-email-and-reset-password/SKILL.md): Email verification and password reset with hashed, single-use, expiring, purpose-bound tokens delivered through `@warlock.js/notifications` — `sendEmailVerification(user)`, `verifyEmail(token)`, `requestPasswordReset(Model, email)`, `resetPassword(token, newPassword)`, the `requireVerifiedEmail()` guard, and the `tokenIssueThrottleMiddleware` / `tokenConsumeThrottleMiddleware` presets. Reset revokes every access token, refresh token and cookie session; a reset request answers the same for unknown emails. Triggers: `sendEmailVerification`, `verifyEmail`, `requestPasswordReset`, `resetPassword`, `requireVerifiedEmail`, `isEmailVerified`, `OneTimeToken`, `InvalidOneTimeTokenError`, `EmailNotVerifiedError`, `NotificationsUnavailableError`, `EC007`, `EC008`, `auth.verification`, `auth.passwordReset`; "verify email", "confirm email address", "forgot password", "reset password link", "block unverified users", "resend verification email"; typical import `import { requestPasswordReset, resetPassword } from "@warlock.js/auth"`. Skip: sign-up itself — the `register-user` topic; login throttling — the `throttle-login-attempts` topic; defining notifications — the `define-notification` topic of the `warlock-js-notifications` skill.
package/package.json CHANGED
@@ -8,17 +8,17 @@
8
8
  "@mongez/copper": "^2.1.3",
9
9
  "@mongez/events": "^2.2.8",
10
10
  "@mongez/reinforcements": "^4.0.2",
11
- "fast-jwt": "^6.1.0",
11
+ "fast-jwt": "^6.3.4",
12
12
  "ms": "^2.1.3"
13
13
  },
14
14
  "peerDependencies": {
15
- "@warlock.js/fs": "5.51.0",
16
- "@warlock.js/cache": "5.51.0",
17
- "@warlock.js/cascade": "5.51.0",
18
- "@warlock.js/core": "5.51.0",
19
- "@warlock.js/logger": "5.51.0",
20
- "@warlock.js/seal": "5.51.0",
21
- "@warlock.js/notifications": "5.51.0",
15
+ "@warlock.js/fs": "5.53.0",
16
+ "@warlock.js/cache": "5.53.0",
17
+ "@warlock.js/cascade": "5.53.0",
18
+ "@warlock.js/core": "5.53.0",
19
+ "@warlock.js/logger": "5.53.0",
20
+ "@warlock.js/seal": "5.53.0",
21
+ "@warlock.js/notifications": "5.53.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.51.0",
51
+ "version": "5.53.0",
52
52
  "type": "module",
53
53
  "main": "./esm/index.mjs",
54
54
  "module": "./esm/index.mjs",
@@ -80,9 +80,18 @@ export default {
80
80
  rotation: true,
81
81
  maxPerUser: 5,
82
82
  },
83
+ hashTokensAtRest: true, // store only SHA-256 digests of access/refresh tokens
83
84
  };
84
85
  ```
85
86
 
87
+ ### Hardening options (5.53)
88
+
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
+ - `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
+ - `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.
93
+ - `Auth` hides `password` from serialized output (`static hidden = ["password"]`); a model that sets its own `hidden` must keep `"password"` in it.
94
+
86
95
  ### Token lifetimes are validated — a bad one throws
87
96
 
88
97
  `expiresIn` (both blocks) must be a duration string the [`ms`](https://github.com/vercel/ms) package parses to a **positive** number: `"1h"`, `"30m"`, `"7d"`, `"30 days"`, or `NO_EXPIRATION` (`"100y"`). Anything else throws on the first token issue, naming the key:
@@ -129,16 +129,16 @@ Token lookups go by the unique `token` string (`findByToken`), which already uni
129
129
 
130
130
  Your subclass inherits and may override these statics — the service calls them, never raw queries:
131
131
 
132
- | Static | Role |
133
- | ---------------------------------------------- | -------------------------------------------------------- |
134
- | `issue(user, token, …)` | persist a freshly-signed token (override to add columns) |
135
- | `findByToken(token)` | look a row up by its token string |
136
- | `findForUser(user, token)` | a user-scoped lookup (logout) |
137
- | `activeFor(user)` | active, unexpired sessions, newest-first |
138
- | `revokeAllFor(user)` / `revokeFamily(id)` | revoke a set, returning the revoked rows |
139
- | `enforceMax(user, max)` | cap concurrent refresh tokens |
140
- | `purgeExpired()` | delete expired rows (CLI cleanup) |
141
- | `findNeverExpiring()` / `purgeNeverExpiring()` | find/delete rows that can never expire (CLI remediation) |
132
+ | Static | Role |
133
+ | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
134
+ | `issue(user, token, …)` | persist a freshly-signed token (override to add columns); `token` is the value to store — the digest under `auth.hashTokensAtRest` |
135
+ | `findByToken(token)` | look a row up by its token string — must match the stored digest **or** the raw value (`whereIn("token", [sha256(token), token])`) |
136
+ | `findForUser(user, token)` | a user-scoped lookup (logout), same two forms |
137
+ | `activeFor(user)` | active, unexpired sessions, newest-first |
138
+ | `revokeAllFor(user)` / `revokeFamily(id)` | revoke a set, returning the revoked rows |
139
+ | `enforceMax(user, max)` | cap concurrent refresh tokens |
140
+ | `purgeExpired()` | delete expired rows (CLI cleanup) |
141
+ | `findNeverExpiring()` / `purgeNeverExpiring()` | find/delete rows that can never expire (CLI remediation) |
142
142
 
143
143
  Plus two instance getters, both of which the route gate consults on every request:
144
144
 
@@ -81,6 +81,8 @@ authService.login(User, { username: "ada", password: "..." });
81
81
  authService.login(User, { phone: "+1...", password: hashedOTP });
82
82
  ```
83
83
 
84
+ Identifiers are normalized before the lookup: string values are trimmed and `email` is lower-cased (`" Sara@x.io"` finds `sara@x.io`). If that finds no user and the normalized value differs from what was sent (trimmed), the lookup is retried once with the value as sent, so legacy rows stored with capitals still log in. The login throttle buckets by the same trimmed, lower-cased email. Configure with `auth.normalizeCredentials`: a function `(identifiers) => identifiers` (everything except `password`), or `false` for exact matching (the function type is `NormalizeCredentials`). Store new emails lower-cased.
85
+
84
86
  For lower-level credential verification (just check, don't issue tokens), use `authService.attemptLogin(Model, credentials)` — returns the user or null without creating tokens.
85
87
 
86
88
  ## Device info
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: login-with-providers
3
- description: 'Log in without a password — Google (OIDC code + PKCE + state + nonce, id_token verified with `jose`), GitHub, Discord, LinkedIn, Apple (`form_post` callback), Facebook and X, passkeys (WebAuthn via `@simplewebauthn/server`) and phone one-time codes (delivered through a `@warlock.js/notifications` channel). Every method ends in `authService.completeLogin(user)`, the same tokens, rows and events as password login. `startProviderLogin`, `completeProviderLogin`, `generatePasskeyRegistrationOptions`, `verifyPasskeyRegistration`, `generatePasskeyAuthenticationOptions`, `verifyPasskeyAuthentication`, `requestOtp`, `verifyOtp`, `otpRequestThrottleMiddleware`, `otpVerifyThrottleMiddleware`, `AuthProvider`. Triggers: "login with Google", "sign in with Google", "login with GitHub", "Sign in with Apple", "login with Discord", "login with LinkedIn", "login with Facebook", "login with X", `auth.providers.github`, "OAuth", "OIDC", "passkeys", "WebAuthn", "passwordless", "SMS code login", "WhatsApp OTP", "phone login", `warlock add auth-google`, `warlock add auth-passkeys`, `AuthProviderSdkMissingError`, `InvalidProviderCallbackError`, `ProviderEmailNotVerifiedError`, `InvalidPasskeyError`, `EC009`, `EC010`, `EC011`, `auth.providers`, `auth.passkeys`, `auth.otp`; typical import `import { completeProviderLogin, verifyOtp } from "@warlock.js/auth"`. Skip: password login — the `handle-login-and-logout` topic; email tokens — the `verify-email-and-reset-password` topic; defining an SMS channel — the `define-channel` topic of the `warlock-js-notifications` skill.'
3
+ description: 'Log in without a password — Google (OIDC code + PKCE + state + nonce, id_token verified with `jose`), GitHub, Discord, LinkedIn, Apple (`form_post` callback), Facebook and X, passkeys (WebAuthn via `@simplewebauthn/server`) and phone one-time codes (delivered through a `@warlock.js/notifications` channel). Every method ends in `authService.completeLogin(user)`, the same tokens, rows and events as password login. `startProviderLogin`, `completeProviderLogin`, `generatePasskeyRegistrationOptions`, `verifyPasskeyRegistration`, `generatePasskeyAuthenticationOptions`, `verifyPasskeyAuthentication`, `requestOtp`, `verifyOtp`, `otpRequestThrottleMiddleware`, `otpVerifyThrottleMiddleware`, `AuthProvider`. Triggers: "login with Google", "sign in with Google", "login with GitHub", "Sign in with Apple", "login with Discord", "login with LinkedIn", "login with Facebook", "login with X", `auth.providers.github`, "OAuth", "OIDC", "passkeys", "WebAuthn", "passwordless", "SMS code login", "WhatsApp OTP", "phone login", `warlock add auth-google`, `warlock add auth-passkeys`, `AuthProviderSdkMissingError`, `InvalidProviderCallbackError`, `ProviderEmailNotVerifiedError`, `ProviderAccountLinkBlockedError`, `ProviderLinkExisting`, `InvalidPasskeyError`, `EC009`, `EC010`, `EC011`, `EC012`, `auth.providers`, `auth.passkeys`, `auth.otp`; typical import `import { completeProviderLogin, verifyOtp } from "@warlock.js/auth"`. Skip: password login — the `handle-login-and-logout` topic; email tokens — the `verify-email-and-reset-password` topic; defining an SMS channel — the `define-channel` topic of the `warlock-js-notifications` skill.'
4
4
  ---
5
5
 
6
6
  # Login with an OAuth provider, passkeys, or a phone code
@@ -63,6 +63,7 @@ Client side, the button is just a link. It must be a top-level navigation, not a
63
63
  - `state`, `nonce` and the PKCE verifier go into a signed, 10-minute, HttpOnly `auth_provider_state` cookie (SameSite=Lax, so it survives Google's redirect back). The callback clears the cookie, so a started login can complete only once.
64
64
  - The callback rejects, with `InvalidProviderCallbackError` (400, `EC009`): a missing, forged or expired cookie, a `state` mismatch, a `?error=` from Google, a failed code exchange, and an id_token with a bad signature, `iss`, `aud`, `exp` or `nonce`. `error.reason` says which. The response message is generic.
65
65
  - **Linking.** An existing `provider_accounts` row (provider plus Google `sub`) always decides the user. Without one, the Google email must be verified (`email_verified: true`), or the call throws `ProviderEmailNotVerifiedError` (403, `EC010`) and nothing is linked or created. A verified email links the matching user, or creates one with `{ email, name, emailVerifiedAt: now }`.
66
+ - **Linking an existing account** follows `auth.providers.linkExisting` (type `ProviderLinkExisting`, default `"verified"`): the account found by email is linked only if it verified that address itself (`auth.verification.field` set); otherwise `ProviderAccountLinkBlockedError` (403, `EC012`) is thrown and nothing is linked — this stops a pre-registered account (attacker knows its password) from being merged with the real owner. A user model whose schema has no verification field links as before. `"always"` restores the old behaviour; `"never"` never links by email.
66
67
  - Other OIDC providers: implement `AuthProvider` (`authorizationUrl(state)`, `handleCallback({ query, expected })`) and register it under `auth.providers.custom.<name>`.
67
68
 
68
69
  ### Google request deadlines and controlled providers
@@ -102,6 +103,8 @@ The implementation uses the `jose` 6 `customFetch` and `timeoutDuration` options
102
103
  Same shape as Google: a config block under `auth.providers.<name>`, a GET
103
104
  route that redirects to `startProviderLogin(response, "<name>")`, and a GET
104
105
  callback that calls `completeProviderLogin(User, "<name>", request, response)`.
106
+ Every provider (Apple, Facebook and X too) takes `timeoutMs` (positive integer,
107
+ default `5000`): the deadline for each token, profile and key-set request.
105
108
 
106
109
  ```ts
107
110
  // src/config/auth.ts
@@ -227,9 +230,17 @@ router.get("/auth/x/callback", async ({ request, response }) => {
227
230
  ## Passkeys
228
231
 
229
232
  ```ts
230
- passkeys: { rpID: "example.com", rpName: "Example", origin: "https://example.com" },
233
+ passkeys: {
234
+ rpID: "example.com",
235
+ rpName: "Example",
236
+ origin: "https://example.com",
237
+ userVerification: "preferred", // default; "required" refuses assertions without PIN/biometric
238
+ },
231
239
  ```
232
240
 
241
+ Throttle the anonymous `/auth/passkeys/login/options` route (each call stores
242
+ a challenge row): `loginThrottleMiddleware({ by: ["ip"], isFailure: () => true, max: 30, window: "1m" })`.
243
+
233
244
  ```ts
234
245
  // Register (logged in)
235
246
  router.post(
@@ -322,7 +333,7 @@ router.post(
322
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.
323
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.
324
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.
325
- - **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`.
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.
326
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.
327
338
 
328
339
  ## Gotchas
@@ -36,6 +36,10 @@ const pair = await authService.createTokenPair(user, deviceInfo);
36
36
 
37
37
  `createTokenPair` is the typical issuance path. It respects `config.auth.refreshToken.enabled` — if disabled, returns only `accessToken`.
38
38
 
39
+ A custom `payload` (`generateAccessToken(user, payload)` / `deviceInfo.payload`) may add claims, but `id` and `userType` are always stamped from `user`; the route gate also refuses a token whose claims name a different user than its row.
40
+
41
+ With `auth.hashTokensAtRest: true` the token columns hold SHA-256 digests. `createTokenPair` / `login` still return the raw tokens; the row `createRefreshToken` returns exposes its raw token as `row.plainToken` (`row.get("token")` is the digest).
42
+
39
43
  ## Refresh with rotation — `refreshTokens`
40
44
 
41
45
  Refresh and family revocation use durable family revision checks inside a
@@ -179,6 +183,8 @@ If tokens minted before 4.12.0 may lack an `exp`, see `warlock auth.purge-never-
179
183
 
180
184
  `authService.generateAccessToken` / `createRefreshToken` read `config.auth.accessToken.expiresIn` / `config.auth.refreshToken.expiresIn`, validate them, and throw naming the key if the value is not a positive `ms` duration — before anything is signed, persisted, or capped.
181
185
 
186
+ `config.auth.accessToken.issuer` / `audience` (optional) are stamped as `iss` / `aud` on every token `jwt.generate` / `generateRefreshToken` sign and **required** by `jwt.verify` / `verifyRefreshToken` — tokens signed before they were set are refused. The verifier and signer are prepared once per settings and reused (no per-request key parsing); passing your own extra options builds a fresh one.
187
+
182
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.
183
189
 
184
190
  ## Things NOT to do