@warlock.js/auth 5.52.0 → 5.53.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/esm/contracts/index.d.mts +2 -2
  3. package/esm/contracts/providers.d.mts +53 -0
  4. package/esm/contracts/providers.d.mts.map +1 -1
  5. package/esm/contracts/types.d.mts +53 -0
  6. package/esm/contracts/types.d.mts.map +1 -1
  7. package/esm/contracts/types.mjs.map +1 -1
  8. package/esm/errors/index.d.mts +2 -1
  9. package/esm/errors/index.mjs +2 -1
  10. package/esm/errors/provider-account-link-blocked.error.d.mts +16 -0
  11. package/esm/errors/provider-account-link-blocked.error.d.mts.map +1 -0
  12. package/esm/errors/provider-account-link-blocked.error.mjs +22 -0
  13. package/esm/errors/provider-account-link-blocked.error.mjs.map +1 -0
  14. package/esm/index.d.mts +3 -2
  15. package/esm/index.mjs +2 -1
  16. package/esm/middleware/auth.middleware.mjs +1 -1
  17. package/esm/middleware/auth.middleware.mjs.map +1 -1
  18. package/esm/middleware/login-throttle.middleware.d.mts +38 -8
  19. package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
  20. package/esm/middleware/login-throttle.middleware.mjs +93 -29
  21. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  22. package/esm/models/access-token/access-token.model.d.mts +14 -3
  23. package/esm/models/access-token/access-token.model.d.mts.map +1 -1
  24. package/esm/models/access-token/access-token.model.mjs +15 -8
  25. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  26. package/esm/models/auth.model.d.mts +8 -0
  27. package/esm/models/auth.model.d.mts.map +1 -1
  28. package/esm/models/auth.model.mjs +3 -0
  29. package/esm/models/auth.model.mjs.map +1 -1
  30. package/esm/models/one-time-token/one-time-token.model.d.mts +7 -2
  31. package/esm/models/one-time-token/one-time-token.model.d.mts.map +1 -1
  32. package/esm/models/one-time-token/one-time-token.model.mjs +8 -7
  33. package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -1
  34. package/esm/models/refresh-token/refresh-token.model.d.mts +15 -3
  35. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  36. package/esm/models/refresh-token/refresh-token.model.mjs +17 -12
  37. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  38. package/esm/otp/otp.d.mts +5 -1
  39. package/esm/otp/otp.d.mts.map +1 -1
  40. package/esm/otp/otp.mjs +18 -3
  41. package/esm/otp/otp.mjs.map +1 -1
  42. package/esm/passkeys/passkey-authentication.mjs +2 -2
  43. package/esm/passkeys/passkey-authentication.mjs.map +1 -1
  44. package/esm/passkeys/passkey-registration.d.mts.map +1 -1
  45. package/esm/passkeys/passkey-registration.mjs +2 -2
  46. package/esm/passkeys/passkey-registration.mjs.map +1 -1
  47. package/esm/providers/apple-provider.d.mts +2 -0
  48. package/esm/providers/apple-provider.d.mts.map +1 -1
  49. package/esm/providers/apple-provider.mjs +4 -1
  50. package/esm/providers/apple-provider.mjs.map +1 -1
  51. package/esm/providers/discord-provider.d.mts +2 -0
  52. package/esm/providers/discord-provider.d.mts.map +1 -1
  53. package/esm/providers/discord-provider.mjs +7 -1
  54. package/esm/providers/discord-provider.mjs.map +1 -1
  55. package/esm/providers/facebook-provider.d.mts +2 -0
  56. package/esm/providers/facebook-provider.d.mts.map +1 -1
  57. package/esm/providers/facebook-provider.mjs +10 -2
  58. package/esm/providers/facebook-provider.mjs.map +1 -1
  59. package/esm/providers/github-provider.d.mts +2 -0
  60. package/esm/providers/github-provider.d.mts.map +1 -1
  61. package/esm/providers/github-provider.mjs +19 -10
  62. package/esm/providers/github-provider.mjs.map +1 -1
  63. package/esm/providers/linkedin-provider.d.mts +2 -0
  64. package/esm/providers/linkedin-provider.d.mts.map +1 -1
  65. package/esm/providers/linkedin-provider.mjs +4 -1
  66. package/esm/providers/linkedin-provider.mjs.map +1 -1
  67. package/esm/providers/provider-timeout.mjs +17 -0
  68. package/esm/providers/provider-timeout.mjs.map +1 -0
  69. package/esm/providers/resolve-provider-user.mjs +21 -1
  70. package/esm/providers/resolve-provider-user.mjs.map +1 -1
  71. package/esm/providers/x-provider.d.mts +2 -0
  72. package/esm/providers/x-provider.d.mts.map +1 -1
  73. package/esm/providers/x-provider.mjs +7 -1
  74. package/esm/providers/x-provider.mjs.map +1 -1
  75. package/esm/services/auth-config.mjs +65 -6
  76. package/esm/services/auth-config.mjs.map +1 -1
  77. package/esm/services/auth-cookie-names.mjs +49 -0
  78. package/esm/services/auth-cookie-names.mjs.map +1 -0
  79. package/esm/services/auth-events.d.mts +4 -0
  80. package/esm/services/auth-events.d.mts.map +1 -1
  81. package/esm/services/auth-events.mjs.map +1 -1
  82. package/esm/services/auth.service.d.mts +8 -0
  83. package/esm/services/auth.service.d.mts.map +1 -1
  84. package/esm/services/auth.service.mjs +146 -20
  85. package/esm/services/auth.service.mjs.map +1 -1
  86. package/esm/services/jwt.d.mts.map +1 -1
  87. package/esm/services/jwt.mjs +92 -10
  88. package/esm/services/jwt.mjs.map +1 -1
  89. package/esm/services/password-reset.d.mts +5 -0
  90. package/esm/services/password-reset.d.mts.map +1 -1
  91. package/esm/services/password-reset.mjs +15 -1
  92. package/esm/services/password-reset.mjs.map +1 -1
  93. package/esm/services/resolve-request-user.d.mts.map +1 -1
  94. package/esm/services/resolve-request-user.mjs +17 -3
  95. package/esm/services/resolve-request-user.mjs.map +1 -1
  96. package/esm/session/page-session.d.mts.map +1 -1
  97. package/esm/session/page-session.mjs +5 -3
  98. package/esm/session/page-session.mjs.map +1 -1
  99. package/esm/utils/auth-error-codes.d.mts +8 -1
  100. package/esm/utils/auth-error-codes.d.mts.map +1 -1
  101. package/esm/utils/auth-error-codes.mjs +7 -0
  102. package/esm/utils/auth-error-codes.mjs.map +1 -1
  103. package/esm/utils/token-digest.mjs +47 -0
  104. package/esm/utils/token-digest.mjs.map +1 -0
  105. package/esm/utils/token-expiry.d.mts +3 -1
  106. package/esm/utils/token-expiry.d.mts.map +1 -1
  107. package/esm/utils/token-expiry.mjs +7 -2
  108. package/esm/utils/token-expiry.mjs.map +1 -1
  109. package/llms-full.txt +70 -30
  110. package/llms.txt +2 -2
  111. package/package.json +9 -9
  112. package/skills/auth-basics/SKILL.md +9 -0
  113. package/skills/customize-token-storage/SKILL.md +10 -10
  114. package/skills/login-with-providers/SKILL.md +14 -3
  115. package/skills/manage-tokens/SKILL.md +6 -0
  116. package/skills/protect-routes/SKILL.md +5 -0
  117. package/skills/throttle-login-attempts/SKILL.md +23 -17
  118. package/skills/verify-email-and-reset-password/SKILL.md +3 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-digest.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-digest.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/**\n * SHA-256 hex digest of a raw access or refresh token — what a token row\n * stores instead of the token when `auth.hashTokensAtRest` is on.\n */\nexport function tokenDigest(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\nconst DIGEST_PATTERN = /^[0-9a-f]{64}$/;\n\n/**\n * Whether a stored token value is a digest rather than a raw JWT. A JWT always\n * contains dots, so the two forms cannot be confused.\n */\nexport function isTokenDigest(stored: unknown): boolean {\n return typeof stored === \"string\" && DIGEST_PATTERN.test(stored);\n}\n\n/**\n * Every stored form a presented token may have: its digest (rows issued with\n * `auth.hashTokensAtRest` on) and the raw value (rows issued with it off, or\n * before it was turned on). Lookups match either, so switching the option in\n * either direction never signs anyone out.\n */\nexport function storedTokenForms(token: string): string[] {\n return [tokenDigest(token), token];\n}\n\n/** Raw tokens of rows issued in this process, for handing back to the caller. */\nconst plainTokens = new WeakMap<object, string>();\n\n/** Remember the raw token of a freshly issued row whose column holds a digest. */\nexport function rememberPlainToken(row: unknown, token: string): void {\n if (typeof row === \"object\" && row !== null) plainTokens.set(row, token);\n}\n\n/**\n * The raw token of a row: the one remembered at issue, else the stored value\n * when it is not a digest. `undefined` for a hashed row loaded from storage —\n * its raw token exists only with the client.\n */\nexport function plainTokenOf(row: object, stored: unknown): string | undefined {\n const remembered = plainTokens.get(row);\n\n if (remembered !== undefined) return remembered;\n\n return typeof stored === \"string\" && !isTokenDigest(stored) ? stored : undefined;\n}\n"],"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"],"sourcesContent":["import { createDecoder } from \"fast-jwt\";\nimport { isTokenDigest } from \"./token-digest\";\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 * (not checkable for a row stored as a digest, which this package only ever\n * writes for tokens it signed with an `exp`).\n *\n * This is the predicate the `auth.purge-never-expiring` remediation selects on.\n */\nexport function isNeverExpiring(token: unknown, expiresAt: unknown): boolean {\n if (!isUsableExpiry(expiresAt)) return true;\n\n // A row stored hashed (`auth.hashTokensAtRest`) holds a digest, not a JWT,\n // so its claims cannot be read; it was issued with an `exp` by construction,\n // and its persisted expiry is the deadline that applies.\n if (isTokenDigest(token)) return false;\n\n return !tokenHasExpClaim(token);\n}\n"],"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
 
@@ -729,7 +738,7 @@ For cookie sessions read by `@warlock.js/web` pages, log in with `authService.lo
729
738
 
730
739
  ---
731
740
  name: login-with-providers
732
- 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.'
733
742
  ---
734
743
 
735
744
  # Login with an OAuth provider, passkeys, or a phone code
@@ -792,6 +801,7 @@ Client side, the button is just a link. It must be a top-level navigation, not a
792
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.
793
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.
794
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.
795
805
  - Other OIDC providers: implement `AuthProvider` (`authorizationUrl(state)`, `handleCallback({ query, expected })`) and register it under `auth.providers.custom.<name>`.
796
806
 
797
807
  ### Google request deadlines and controlled providers
@@ -831,6 +841,8 @@ The implementation uses the `jose` 6 `customFetch` and `timeoutDuration` options
831
841
  Same shape as Google: a config block under `auth.providers.<name>`, a GET
832
842
  route that redirects to `startProviderLogin(response, "<name>")`, and a GET
833
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.
834
846
 
835
847
  ```ts
836
848
  // src/config/auth.ts
@@ -956,9 +968,17 @@ router.get("/auth/x/callback", async ({ request, response }) => {
956
968
  ## Passkeys
957
969
 
958
970
  ```ts
959
- 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
+ },
960
977
  ```
961
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
+
962
982
  ```ts
963
983
  // Register (logged in)
964
984
  router.post(
@@ -1051,7 +1071,7 @@ router.post(
1051
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.
1052
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.
1053
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.
1054
- - **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.
1055
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.
1056
1076
 
1057
1077
  ## Gotchas
@@ -1109,6 +1129,10 @@ const pair = await authService.createTokenPair(user, deviceInfo);
1109
1129
 
1110
1130
  `createTokenPair` is the typical issuance path. It respects `config.auth.refreshToken.enabled` — if disabled, returns only `accessToken`.
1111
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
+
1112
1136
  ## Refresh with rotation — `refreshTokens`
1113
1137
 
1114
1138
  Refresh and family revocation use durable family revision checks inside a
@@ -1252,6 +1276,8 @@ If tokens minted before 4.12.0 may lack an `exp`, see `warlock auth.purge-never-
1252
1276
 
1253
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.
1254
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
+
1255
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.
1256
1282
 
1257
1283
  ## Things NOT to do
@@ -1357,6 +1383,9 @@ A token passes three separate checks, in order — a token can fail any one of t
1357
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.
1358
1384
  2. **The access-token row still exists** — deleting it (logout) invalidates the token immediately, before its JWT expiry.
1359
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.
1360
1389
 
1361
1390
  Missing or invalid credentials return 401; an authenticated disallowed user type returns 403:
1362
1391
 
@@ -1559,6 +1588,8 @@ export default {
1559
1588
 
1560
1589
  The cookie name `setAuthCookie`/`clearAuthCookie` write **must match** the name a `cookie:<name>` token source reads — they are not linked automatically.
1561
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
+
1562
1593
  ### CSRF: an automatic Origin check on cookie-authenticated writes
1563
1594
 
1564
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`.
@@ -1940,14 +1971,14 @@ Register it the same way as the bundled commands — call the factory inside `de
1940
1971
 
1941
1972
  ---
1942
1973
  name: throttle-login-attempts
1943
- 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.'
1944
1975
  ---
1945
1976
 
1946
1977
  # Throttle login attempts with `loginThrottleMiddleware`
1947
1978
 
1948
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.
1949
1980
 
1950
- 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.
1951
1982
 
1952
1983
  ## The shortest version
1953
1984
 
@@ -1994,8 +2025,8 @@ router.post("/auth/reset-password", resetPasswordController, {
1994
2025
 
1995
2026
  ## How it behaves
1996
2027
 
1997
- 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`).
1998
- 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.
1999
2030
 
2000
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.
2001
2032
 
@@ -2024,16 +2055,22 @@ loginThrottleMiddleware({
2024
2055
  });
2025
2056
  ```
2026
2057
 
2027
- | Option | Default | Purpose |
2028
- | ----------------- | ---------------------------------- | ----------------------------------------- |
2029
- | `max` | `5` | Failures within the window before lockout |
2030
- | `window` | `"15m"` | Counting window (`ms`-string or seconds) |
2031
- | `lockoutDuration` | `"15m"` | Lock TTL once tripped |
2032
- | `by` | `["email", "ip"]` | Identifiers tracked independently |
2033
- | `identifierKey` | `"email"` | Credential field used as the account key |
2034
- | `errorMessage` | i18n `auth.errors.tooManyAttempts` | 429 message override |
2035
- | `isFailure` | `(res) => !res.isOk` | What counts as a failed attempt |
2036
- | `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" })`.
2037
2074
 
2038
2075
  ## The 429 response
2039
2076
 
@@ -2063,7 +2100,7 @@ router.post("/auth/forgot-password", forgotController, {
2063
2100
 
2064
2101
  | | `loginThrottleMiddleware` (auth) | `middleware.rateLimit` (core) |
2065
2102
  | ---------------------------- | -------------------------------------------- | ----------------------------- |
2066
- | Counts | only **failed** logins | **every** request |
2103
+ | Counts | every attempt, until a login succeeds | **every** request |
2067
2104
  | Resets on a successful login | yes | no |
2068
2105
  | Locks per account / per IP | yes | per key (default IP) |
2069
2106
  | Storage | `@warlock.js/cache` (shared across replicas) | in-process map |
@@ -2073,8 +2110,8 @@ They compose. For a hard ceiling on request volume _and_ failure-aware account l
2073
2110
  ## Gotchas
2074
2111
 
2075
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.
2076
- - **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.
2077
- - **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.
2078
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).
2079
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.
2080
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.
@@ -2178,6 +2215,8 @@ router.post("/auth/reset-password", resetPasswordController, {
2178
2215
  });
2179
2216
  ```
2180
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
+
2181
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`.
2182
2221
 
2183
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`.
@@ -2210,6 +2249,7 @@ const authConfigurations: AuthConfigurations = {
2210
2249
  setPassword: async (user, plain) => {
2211
2250
  /* optional */
2212
2251
  },
2252
+ awaitDelivery: false, // default: send in the background (anti-enumeration timing)
2213
2253
  },
2214
2254
  oneTimeToken: { model: AppOneTimeToken }, // optional model override
2215
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.52.0",
16
- "@warlock.js/cache": "5.52.0",
17
- "@warlock.js/cascade": "5.52.0",
18
- "@warlock.js/core": "5.52.0",
19
- "@warlock.js/logger": "5.52.0",
20
- "@warlock.js/seal": "5.52.0",
21
- "@warlock.js/notifications": "5.52.0",
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",
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.52.0",
51
+ "version": "5.53.1",
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
 
@@ -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
@@ -67,6 +67,9 @@ A token passes three separate checks, in order — a token can fail any one of t
67
67
  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.
68
68
  2. **The access-token row still exists** — deleting it (logout) invalidates the token immediately, before its JWT expiry.
69
69
  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.
70
+ 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`.
71
+
72
+ Expired or malformed tokens and CSRF Origin mismatches are logged at `debug`, not `error` — any anonymous client can produce them.
70
73
 
71
74
  Missing or invalid credentials return 401; an authenticated disallowed user type returns 403:
72
75
 
@@ -269,6 +272,8 @@ export default {
269
272
 
270
273
  The cookie name `setAuthCookie`/`clearAuthCookie` write **must match** the name a `cookie:<name>` token source reads — they are not linked automatically.
271
274
 
275
+ `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.
276
+
272
277
  ### CSRF: an automatic Origin check on cookie-authenticated writes
273
278
 
274
279
  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`.