@c9up/warden 0.2.3 → 0.2.5

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 (98) hide show
  1. package/README.md +5 -3
  2. package/dist/AttemptStore.d.ts +64 -0
  3. package/dist/AttemptStore.d.ts.map +1 -0
  4. package/dist/AttemptStore.js +117 -0
  5. package/dist/AttemptStore.js.map +1 -0
  6. package/dist/AuthManager.d.ts +5 -3
  7. package/dist/AuthManager.d.ts.map +1 -1
  8. package/dist/AuthManager.js +5 -4
  9. package/dist/AuthManager.js.map +1 -1
  10. package/dist/AuthRateLimiter.d.ts +44 -10
  11. package/dist/AuthRateLimiter.d.ts.map +1 -1
  12. package/dist/AuthRateLimiter.js +58 -73
  13. package/dist/AuthRateLimiter.js.map +1 -1
  14. package/dist/Authenticator.d.ts +8 -11
  15. package/dist/Authenticator.d.ts.map +1 -1
  16. package/dist/Authenticator.js +72 -9
  17. package/dist/Authenticator.js.map +1 -1
  18. package/dist/RememberMeToken.d.ts +15 -4
  19. package/dist/RememberMeToken.d.ts.map +1 -1
  20. package/dist/RememberMeToken.js +20 -7
  21. package/dist/RememberMeToken.js.map +1 -1
  22. package/dist/bouncer/evaluate.d.ts +0 -8
  23. package/dist/bouncer/evaluate.d.ts.map +1 -1
  24. package/dist/bouncer/evaluate.js +1 -1
  25. package/dist/bouncer/evaluate.js.map +1 -1
  26. package/dist/duration.d.ts.map +1 -1
  27. package/dist/duration.js +6 -0
  28. package/dist/duration.js.map +1 -1
  29. package/dist/errors.d.ts +6 -0
  30. package/dist/errors.d.ts.map +1 -1
  31. package/dist/errors.js +6 -0
  32. package/dist/errors.js.map +1 -1
  33. package/dist/index.d.ts +8 -6
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +2 -1
  36. package/dist/index.js.map +1 -1
  37. package/dist/mfa/BackupCodesProvider.d.ts +8 -1
  38. package/dist/mfa/BackupCodesProvider.d.ts.map +1 -1
  39. package/dist/mfa/BackupCodesProvider.js +5 -7
  40. package/dist/mfa/BackupCodesProvider.js.map +1 -1
  41. package/dist/mfa/MfaManager.d.ts +18 -2
  42. package/dist/mfa/MfaManager.d.ts.map +1 -1
  43. package/dist/mfa/MfaManager.js +38 -35
  44. package/dist/mfa/MfaManager.js.map +1 -1
  45. package/dist/mfa/TotpProvider.d.ts +30 -6
  46. package/dist/mfa/TotpProvider.d.ts.map +1 -1
  47. package/dist/mfa/TotpProvider.js +48 -19
  48. package/dist/mfa/TotpProvider.js.map +1 -1
  49. package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
  50. package/dist/mfa/WebauthnProvider.js +4 -1
  51. package/dist/mfa/WebauthnProvider.js.map +1 -1
  52. package/dist/middleware.d.ts +2 -0
  53. package/dist/middleware.d.ts.map +1 -1
  54. package/dist/middleware.js +3 -0
  55. package/dist/middleware.js.map +1 -1
  56. package/dist/native/generated.d.ts +0 -5
  57. package/dist/native/generated.d.ts.map +1 -1
  58. package/dist/native.d.ts +0 -2
  59. package/dist/native.d.ts.map +1 -1
  60. package/dist/native.js +0 -4
  61. package/dist/native.js.map +1 -1
  62. package/dist/strategies/JwtStrategy.d.ts +11 -1
  63. package/dist/strategies/JwtStrategy.d.ts.map +1 -1
  64. package/dist/strategies/JwtStrategy.js +9 -2
  65. package/dist/strategies/JwtStrategy.js.map +1 -1
  66. package/dist/strategies/SessionStrategy.d.ts +70 -1
  67. package/dist/strategies/SessionStrategy.d.ts.map +1 -1
  68. package/dist/strategies/SessionStrategy.js +100 -4
  69. package/dist/strategies/SessionStrategy.js.map +1 -1
  70. package/dist/vendor/nodeEnv.d.ts +5 -0
  71. package/dist/vendor/nodeEnv.d.ts.map +1 -0
  72. package/dist/vendor/nodeEnv.js +38 -0
  73. package/dist/vendor/nodeEnv.js.map +1 -0
  74. package/index.darwin-arm64.node +0 -0
  75. package/index.darwin-x64.node +0 -0
  76. package/index.linux-arm64-gnu.node +0 -0
  77. package/index.linux-x64-gnu.node +0 -0
  78. package/index.win32-x64-msvc.node +0 -0
  79. package/package.json +2 -2
  80. package/src/AttemptStore.ts +158 -0
  81. package/src/AuthManager.ts +9 -7
  82. package/src/AuthRateLimiter.ts +85 -80
  83. package/src/Authenticator.ts +92 -13
  84. package/src/RememberMeToken.ts +36 -8
  85. package/src/bouncer/evaluate.ts +1 -1
  86. package/src/duration.ts +8 -0
  87. package/src/errors.ts +11 -1
  88. package/src/index.ts +24 -3
  89. package/src/mfa/BackupCodesProvider.ts +13 -14
  90. package/src/mfa/MfaManager.ts +58 -43
  91. package/src/mfa/TotpProvider.ts +90 -22
  92. package/src/mfa/WebauthnProvider.ts +4 -1
  93. package/src/middleware.ts +9 -0
  94. package/src/native/generated.ts +0 -14
  95. package/src/native.ts +0 -5
  96. package/src/strategies/JwtStrategy.ts +20 -2
  97. package/src/strategies/SessionStrategy.ts +172 -4
  98. package/src/vendor/nodeEnv.ts +37 -0
@@ -18,6 +18,12 @@
18
18
  * 3. **A used token is recycled.** Authenticating rotates the secret and
19
19
  * invalidates the old one, so a stolen cookie stops working the moment the
20
20
  * legitimate user comes back.
21
+ *
22
+ * One property goes further than upstream: the rotation is a compare-and-set.
23
+ * Upstream reads, compares, then replaces, so two requests carrying the same
24
+ * cookie both pass the comparison and both get a fresh secret — a stolen
25
+ * cookie replayed alongside the real one survives. Here the store replaces the
26
+ * hash only if it is still the one presented; the second request loses.
21
27
  */
22
28
 
23
29
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
@@ -43,8 +49,18 @@ export interface StoredRememberMeToken {
43
49
  export interface RememberMeTokenDriver {
44
50
  create(token: StoredRememberMeToken): Promise<void>;
45
51
  find(identifier: string): Promise<StoredRememberMeToken | null>;
46
- /** Replace the hash + expiry of an existing row (recycling). */
47
- update(identifier: string, hash: string, expiresAt: number): Promise<void>;
52
+ /**
53
+ * Replace the hash + expiry of a row, ONLY if its hash is still
54
+ * `previousHash` — atomically (`UPDATE … WHERE identifier = ? AND hash = ?`
55
+ * and the affected row count, in SQL). Returns whether it replaced it: a
56
+ * `false` means another request consumed the token first.
57
+ */
58
+ update(
59
+ identifier: string,
60
+ previousHash: string,
61
+ hash: string,
62
+ expiresAt: number,
63
+ ): Promise<boolean>;
48
64
  delete(identifier: string): Promise<void>;
49
65
  deleteAllForUser(userId: string | number): Promise<void>;
50
66
  }
@@ -162,7 +178,9 @@ export async function verifyAndRecycleRememberMeToken(
162
178
  const stored = await driver.find(decoded.identifier);
163
179
  if (!stored) return null;
164
180
 
165
- if (stored.expiresAt <= Date.now()) {
181
+ // Written as "not in the future" so an expiry that is not a number — a
182
+ // NaN from a bad age — counts as expired instead of as never.
183
+ if (!(stored.expiresAt > Date.now())) {
166
184
  // Expired rows are removed on sight rather than left to a cleanup job.
167
185
  await driver.delete(stored.identifier);
168
186
  return null;
@@ -174,7 +192,15 @@ export async function verifyAndRecycleRememberMeToken(
174
192
 
175
193
  const secret = randomBytes(secretLength).toString("base64url");
176
194
  const expiresAt = Date.now() + ageSeconds * 1000;
177
- await driver.update(stored.identifier, hashSecret(secret), expiresAt);
195
+ const recycled = await driver.update(
196
+ stored.identifier,
197
+ stored.hash,
198
+ hashSecret(secret),
199
+ expiresAt,
200
+ );
201
+ // Another request holding the same cookie rotated it first: this one is
202
+ // the replay, whichever of the two it is.
203
+ if (!recycled) return null;
178
204
 
179
205
  return {
180
206
  userId: stored.tokenableId,
@@ -197,17 +223,19 @@ export class MemoryRememberMeTokenDriver implements RememberMeTokenDriver {
197
223
 
198
224
  async update(
199
225
  identifier: string,
226
+ previousHash: string,
200
227
  hash: string,
201
228
  expiresAt: number,
202
- ): Promise<void> {
229
+ ): Promise<boolean> {
203
230
  const row = this.#rows.get(identifier);
204
- if (!row) return;
231
+ if (!row || row.hash !== previousHash) return false;
205
232
  this.#rows.set(identifier, {
206
233
  ...row,
207
234
  hash,
208
235
  expiresAt,
209
236
  updatedAt: Date.now(),
210
237
  });
238
+ return true;
211
239
  }
212
240
 
213
241
  async delete(identifier: string): Promise<void> {
@@ -345,9 +373,9 @@ export class RememberMeToken {
345
373
  };
346
374
  }
347
375
 
348
- /** Whether the token is past its expiry. */
376
+ /** Whether the token is past its expiry (an invalid date counts as past). */
349
377
  isExpired(): boolean {
350
- return this.expiresAt.getTime() <= Date.now();
378
+ return !(this.expiresAt.getTime() > Date.now());
351
379
  }
352
380
 
353
381
  /** Constant-time check of a presented secret against the stored hash. */
@@ -39,7 +39,7 @@ export const defaultResponseBuilder: ResponseBuilder = (value) => {
39
39
  * bare `return false` a house message and status instead of a naked 403
40
40
  * (AdonisJS `Bouncer.responseBuilder`).
41
41
  */
42
- export function normalizeResponse(
42
+ function normalizeResponse(
43
43
  value: boolean | AuthorizationResponse,
44
44
  builder: ResponseBuilder = defaultResponseBuilder,
45
45
  ): AuthorizationResponse {
package/src/duration.ts CHANGED
@@ -97,5 +97,13 @@ export function resolveExpiresInSeconds(
97
97
  `Warden: token lifetime must be a positive duration, got ${JSON.stringify(chosen)}`,
98
98
  );
99
99
  }
100
+ // A token's `exp` is whole seconds: "500ms" made it fractional, and the
101
+ // engine reads a fractional `exp` as a missing one — the token was dead on
102
+ // issue.
103
+ if (!Number.isInteger(seconds)) {
104
+ throw new TypeError(
105
+ `Warden: token lifetime must be a whole number of seconds, got ${JSON.stringify(chosen)}`,
106
+ );
107
+ }
100
108
  return seconds;
101
109
  }
package/src/errors.ts CHANGED
@@ -48,14 +48,24 @@ export class WardenError extends Error {
48
48
  export class E_UNAUTHORIZED_ACCESS extends WardenError {
49
49
  readonly redirectTo?: string;
50
50
  readonly guardDriverName: string;
51
+ /**
52
+ * The `WWW-Authenticate` value the 401 carries — a Basic guard's challenge,
53
+ * without which a browser never prompts for credentials.
54
+ */
55
+ readonly challenge?: string;
51
56
 
52
57
  constructor(
53
58
  message: string,
54
- options: { guardDriverName: string; redirectTo?: string },
59
+ options: {
60
+ guardDriverName: string;
61
+ redirectTo?: string;
62
+ challenge?: string;
63
+ },
55
64
  ) {
56
65
  super("E_UNAUTHORIZED_ACCESS", message, { status: 401 });
57
66
  this.guardDriverName = options.guardDriverName;
58
67
  this.redirectTo = options.redirectTo;
68
+ this.challenge = options.challenge;
59
69
  }
60
70
  }
61
71
 
package/src/index.ts CHANGED
@@ -6,6 +6,13 @@
6
6
 
7
7
  import "./augmentations.js";
8
8
 
9
+ export type {
10
+ AttemptCount,
11
+ AttemptRedisClient,
12
+ AttemptRedisSource,
13
+ AttemptStore,
14
+ } from "./AttemptStore.js";
15
+ export { MemoryAttemptStore, RedisAttemptStore } from "./AttemptStore.js";
9
16
  export type { AuthAttempt, ExtractedCredentials } from "./Authenticator.js";
10
17
  export {
11
18
  API_KEY_GUARD_NAMES,
@@ -24,7 +31,10 @@ export {
24
31
  authEventPrefix,
25
32
  type WardenEmitter,
26
33
  } from "./AuthManager.js";
27
- export type { AuthRateLimiterConfig } from "./AuthRateLimiter.js";
34
+ export type {
35
+ AttemptDecision,
36
+ AuthRateLimiterConfig,
37
+ } from "./AuthRateLimiter.js";
28
38
  export { AuthRateLimiter } from "./AuthRateLimiter.js";
29
39
  export { AbilitiesBuilder } from "./bouncer/AbilitiesBuilder.js";
30
40
  export { AuthorizationResponse } from "./bouncer/AuthorizationResponse.js";
@@ -85,6 +95,7 @@ export type {
85
95
  MfaFactorStore,
86
96
  MfaFactorSummary,
87
97
  MfaManagerConfig,
98
+ MfaRateLimitConfig,
88
99
  } from "./mfa/MfaManager.js";
89
100
  export { MemoryMfaFactorStore, MfaManager } from "./mfa/MfaManager.js";
90
101
  export type {
@@ -98,12 +109,17 @@ export type {
98
109
  } from "./mfa/OtpProvider.js";
99
110
  export { MemoryOtpChallengeStore, OtpProvider } from "./mfa/OtpProvider.js";
100
111
  export type {
112
+ ReplayRedisClient,
101
113
  TotpAlgorithm,
102
114
  TotpConfig,
103
115
  TotpEnrollment,
104
116
  TotpReplayGuard,
105
117
  } from "./mfa/TotpProvider.js";
106
- export { MemoryTotpReplayGuard, TotpProvider } from "./mfa/TotpProvider.js";
118
+ export {
119
+ MemoryTotpReplayGuard,
120
+ RedisTotpReplayGuard,
121
+ TotpProvider,
122
+ } from "./mfa/TotpProvider.js";
107
123
  export type {
108
124
  AuthenticationOptionsJSON,
109
125
  AuthenticationResponseJSON,
@@ -171,9 +187,14 @@ export {
171
187
  decodeBasicAuth,
172
188
  safeCompare,
173
189
  } from "./strategies/BasicAuthStrategy.js";
174
- export type { JwtClaims, JwtStrategyConfig } from "./strategies/JwtStrategy.js";
190
+ export type {
191
+ JwtClaims,
192
+ JwtStrategyConfig,
193
+ SignTokenOptions,
194
+ } from "./strategies/JwtStrategy.js";
175
195
  export { generateJwtSecret, JwtStrategy } from "./strategies/JwtStrategy.js";
176
196
  export type {
197
+ RememberMeCookieAttributes,
177
198
  SessionGuardState,
178
199
  SessionStore,
179
200
  SessionStrategyConfig,
@@ -8,8 +8,8 @@
8
8
  */
9
9
 
10
10
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
11
- import { WardenError } from "../errors.js";
12
11
  import { base32Encode } from "./base32.js";
12
+ import { assertIntegerIn } from "./TotpProvider.js";
13
13
 
14
14
  export interface BackupCodesConfig {
15
15
  /** How many codes to generate. Default `10`. */
@@ -27,8 +27,15 @@ export interface BackupCodesResult {
27
27
 
28
28
  export interface BackupCodeVerification {
29
29
  ok: boolean;
30
- /** The hash list with the consumed code removed (persist this on success). */
30
+ /** The hash list with the consumed code removed. */
31
31
  remaining: string[];
32
+ /**
33
+ * The stored hash the code matched. Consume THIS one atomically
34
+ * (`MfaFactorStore.consumeBackupHash`) rather than saving `remaining`: two
35
+ * requests with the same code both computed the same `remaining`, and both
36
+ * were accepted.
37
+ */
38
+ matched?: string;
32
39
  }
33
40
 
34
41
  const DEFAULTS = { count: 10, length: 10 };
@@ -39,18 +46,9 @@ export class BackupCodesProvider {
39
46
 
40
47
  constructor(config: BackupCodesConfig = {}) {
41
48
  this.#cfg = { ...DEFAULTS, ...config };
42
- if (this.#cfg.count < 1) {
43
- throw new WardenError(
44
- "INVALID_CONFIG",
45
- `backup code count must be >= 1, got ${this.#cfg.count}`,
46
- );
47
- }
48
- if (this.#cfg.length < 8) {
49
- throw new WardenError(
50
- "INVALID_CONFIG",
51
- `backup code length must be >= 8 for adequate entropy, got ${this.#cfg.length}`,
52
- );
53
- }
49
+ assertIntegerIn("backup code count", this.#cfg.count, 1, 100);
50
+ // At least 8 characters for adequate entropy.
51
+ assertIntegerIn("backup code length", this.#cfg.length, 8, 64);
54
52
  }
55
53
 
56
54
  /** Generate a fresh batch of codes plus the hashes to persist. */
@@ -90,6 +88,7 @@ export class BackupCodesProvider {
90
88
  return {
91
89
  ok: true,
92
90
  remaining: hashes.filter((_, i) => i !== matchedIndex),
91
+ matched: hashes[matchedIndex],
93
92
  };
94
93
  }
95
94
  }
@@ -10,6 +10,8 @@
10
10
  */
11
11
 
12
12
  import { randomBytes } from "node:crypto";
13
+ import type { AttemptStore } from "../AttemptStore.js";
14
+ import { AuthRateLimiter } from "../AuthRateLimiter.js";
13
15
  import { WardenError } from "../errors.js";
14
16
  import type { BackupCodesProvider } from "./BackupCodesProvider.js";
15
17
  import type { TotpProvider } from "./TotpProvider.js";
@@ -43,6 +45,13 @@ export interface MfaFactorStore {
43
45
  findById(id: string): Promise<MfaFactor | null>;
44
46
  findByUser(userId: string): Promise<MfaFactor[]>;
45
47
  delete(id: string): Promise<void>;
48
+ /**
49
+ * Remove `hash` from the factor's backup hashes — ATOMICALLY, and only if
50
+ * it is still there (an `UPDATE … WHERE` on the hash, or a Redis `SREM`).
51
+ * True when this call removed it: the code is accepted, once. A read, a
52
+ * filter and a save let two requests with the same code both succeed.
53
+ */
54
+ consumeBackupHash(factorId: string, hash: string): Promise<boolean>;
46
55
  }
47
56
 
48
57
  export class MemoryMfaFactorStore implements MfaFactorStore {
@@ -59,13 +68,36 @@ export class MemoryMfaFactorStore implements MfaFactorStore {
59
68
  async delete(id: string): Promise<void> {
60
69
  this.#store.delete(id);
61
70
  }
71
+ /** Synchronous between read and write: nothing interleaves. */
72
+ async consumeBackupHash(factorId: string, hash: string): Promise<boolean> {
73
+ const factor = this.#store.get(factorId);
74
+ const hashes = factor?.backupHashes;
75
+ if (
76
+ factor === undefined ||
77
+ hashes === undefined ||
78
+ !hashes.includes(hash)
79
+ ) {
80
+ return false;
81
+ }
82
+ this.#store.set(factorId, {
83
+ ...factor,
84
+ backupHashes: hashes.filter((stored) => stored !== hash),
85
+ });
86
+ return true;
87
+ }
62
88
  }
63
89
 
64
90
  export interface MfaRateLimitConfig {
65
- /** Failed verifications allowed per user before lockout. Default `5`. */
91
+ /** Verifications allowed per user before lockout. Default `5`. */
66
92
  maxAttempts?: number;
67
93
  /** Lockout / counter window in seconds. Default `900` (15 min). */
68
94
  windowSeconds?: number;
95
+ /**
96
+ * Where the counts live. Default: this process's memory. A cluster passes a
97
+ * shared one (`RedisAttemptStore`), or a lockout holds only on the instance
98
+ * that counted it.
99
+ */
100
+ store?: AttemptStore;
69
101
  }
70
102
 
71
103
  export interface MfaManagerConfig {
@@ -78,19 +110,12 @@ export interface MfaManagerConfig {
78
110
  rateLimit?: MfaRateLimitConfig;
79
111
  }
80
112
 
81
- interface AttemptEntry {
82
- count: number;
83
- resetAt: number;
84
- }
85
-
86
113
  export class MfaManager {
87
114
  readonly #issuer: string;
88
115
  readonly #totp?: TotpProvider;
89
116
  readonly #backupCodes?: BackupCodesProvider;
90
117
  readonly #store: MfaFactorStore;
91
- readonly #maxAttempts: number;
92
- readonly #windowMs: number;
93
- readonly #attempts = new Map<string, AttemptEntry>();
118
+ readonly #limiter: AuthRateLimiter;
94
119
 
95
120
  constructor(config: MfaManagerConfig) {
96
121
  if (!config?.issuer) {
@@ -100,8 +125,11 @@ export class MfaManager {
100
125
  this.#totp = config.totp;
101
126
  this.#backupCodes = config.backupCodes;
102
127
  this.#store = config.store ?? new MemoryMfaFactorStore();
103
- this.#maxAttempts = config.rateLimit?.maxAttempts ?? 5;
104
- this.#windowMs = (config.rateLimit?.windowSeconds ?? 900) * 1000;
128
+ this.#limiter = new AuthRateLimiter({
129
+ maxAttempts: config.rateLimit?.maxAttempts ?? 5,
130
+ windowSeconds: config.rateLimit?.windowSeconds ?? 900,
131
+ store: config.rateLimit?.store,
132
+ });
105
133
  }
106
134
 
107
135
  // ── TOTP enrollment ──────────────────────────────────────────────
@@ -201,8 +229,12 @@ export class MfaManager {
201
229
  continue;
202
230
  }
203
231
  const result = provider.verify(factor.backupHashes, code);
204
- if (result.ok) {
205
- await this.#store.save({ ...factor, backupHashes: result.remaining });
232
+ // Only the request that removes the hash wins; one that verified the
233
+ // same code a moment later finds it gone.
234
+ if (
235
+ result.matched !== undefined &&
236
+ (await this.#store.consumeBackupHash(factor.id, result.matched))
237
+ ) {
206
238
  return true;
207
239
  }
208
240
  }
@@ -216,7 +248,11 @@ export class MfaManager {
216
248
  * factors first, then falls back to consuming a backup code.
217
249
  */
218
250
  async verify(userId: string, code: string): Promise<boolean> {
219
- if (this.#isLocked(userId)) {
251
+ // Counted BEFORE the code is checked, by one atomic increment: reading
252
+ // "not locked" first and counting the failure after let a burst of
253
+ // concurrent attempts all reach the providers.
254
+ const key = lockoutKey(userId);
255
+ if (!(await this.#limiter.attempt(key)).allowed) {
220
256
  return false;
221
257
  }
222
258
  let ok = false;
@@ -228,11 +264,7 @@ export class MfaManager {
228
264
  ) {
229
265
  ok = true;
230
266
  }
231
- if (ok) {
232
- this.#attempts.delete(userId);
233
- } else {
234
- this.#recordFailure(userId);
235
- }
267
+ if (ok) await this.#limiter.clear(key);
236
268
  return ok;
237
269
  }
238
270
 
@@ -240,8 +272,8 @@ export class MfaManager {
240
272
  * Whether the user is currently locked out of `verify()` after too many
241
273
  * failed attempts. Use it to surface a "try again later" message.
242
274
  */
243
- isLocked(userId: string): boolean {
244
- return this.#isLocked(userId);
275
+ isLocked(userId: string): Promise<boolean> {
276
+ return this.#limiter.isBlocked(lockoutKey(userId));
245
277
  }
246
278
 
247
279
  /** List the user's factors without exposing any secret material. */
@@ -266,28 +298,6 @@ export class MfaManager {
266
298
  await this.#store.delete(factorId);
267
299
  }
268
300
 
269
- #isLocked(userId: string): boolean {
270
- const entry = this.#attempts.get(userId);
271
- if (!entry) {
272
- return false;
273
- }
274
- if (entry.resetAt < Date.now()) {
275
- this.#attempts.delete(userId);
276
- return false;
277
- }
278
- return entry.count >= this.#maxAttempts;
279
- }
280
-
281
- #recordFailure(userId: string): void {
282
- const now = Date.now();
283
- let entry = this.#attempts.get(userId);
284
- if (!entry || entry.resetAt < now) {
285
- entry = { count: 0, resetAt: now + this.#windowMs };
286
- this.#attempts.set(userId, entry);
287
- }
288
- entry.count++;
289
- }
290
-
291
301
  #requireTotp(): TotpProvider {
292
302
  if (!this.#totp) {
293
303
  throw new WardenError(
@@ -309,6 +319,11 @@ export class MfaManager {
309
319
  }
310
320
  }
311
321
 
322
+ /** The limiter key of a user's MFA attempts. */
323
+ function lockoutKey(userId: string): string {
324
+ return `mfa:${userId}`;
325
+ }
326
+
312
327
  function newId(): string {
313
328
  return randomBytes(16).toString("hex");
314
329
  }
@@ -13,6 +13,23 @@ import { base32Decode, base32Encode } from "./base32.js";
13
13
 
14
14
  export type TotpAlgorithm = "SHA1" | "SHA256" | "SHA512";
15
15
 
16
+ const TOTP_ALGORITHMS: readonly string[] = ["SHA1", "SHA256", "SHA512"];
17
+
18
+ /** Throw INVALID_CONFIG unless `value` is an integer in `[min, max]`. */
19
+ export function assertIntegerIn(
20
+ what: string,
21
+ value: number,
22
+ min: number,
23
+ max: number,
24
+ ): void {
25
+ if (!Number.isInteger(value) || value < min || value > max) {
26
+ throw new WardenError(
27
+ "INVALID_CONFIG",
28
+ `${what} must be a whole number from ${min} to ${max}, got ${String(value)}`,
29
+ );
30
+ }
31
+ }
32
+
16
33
  export interface TotpConfig {
17
34
  /** HMAC algorithm. Default `SHA1` (authenticator-app compatible). */
18
35
  algorithm?: TotpAlgorithm;
@@ -43,12 +60,18 @@ export interface TotpConfig {
43
60
  *
44
61
  * Keys are opaque digests, never the secret itself: a store may be shared, and
45
62
  * a guard that leaks the seed is worse than the replay it prevents.
63
+ *
64
+ * One operation, not a "was it used?" read followed by a "remember it" write:
65
+ * between the two, a second request with the same code read "unused" too, and
66
+ * both were accepted.
46
67
  */
47
68
  export interface TotpReplayGuard {
48
- /** True when this exact code has already been accepted. */
49
- used(key: string): boolean | Promise<boolean>;
50
- /** Record it as used; `ttlMs` is how long it could still be replayed. */
51
- remember(key: string, ttlMs: number): void | Promise<void>;
69
+ /**
70
+ * Record `key` as used for `ttlMs` — ATOMICALLY, only if it is not already
71
+ * recorded (Redis `SET key 1 PX ttl NX`). True when this call recorded it:
72
+ * the code is accepted. False when it was already used.
73
+ */
74
+ claim(key: string, ttlMs: number): boolean | Promise<boolean>;
52
75
  }
53
76
 
54
77
  /**
@@ -59,22 +82,63 @@ export interface TotpReplayGuard {
59
82
  export class MemoryTotpReplayGuard implements TotpReplayGuard {
60
83
  readonly #seen = new Map<string, number>();
61
84
 
62
- used(key: string): boolean {
63
- const expiresAt = this.#seen.get(key);
64
- if (expiresAt === undefined) return false;
65
- if (expiresAt <= Date.now()) {
66
- this.#seen.delete(key);
67
- return false;
68
- }
69
- return true;
70
- }
71
-
72
- remember(key: string, ttlMs: number): void {
85
+ /** Synchronous: nothing can run between the check and the write. */
86
+ claim(key: string, ttlMs: number): boolean {
73
87
  const now = Date.now();
74
88
  for (const [seenKey, expiresAt] of this.#seen) {
75
89
  if (expiresAt <= now) this.#seen.delete(seenKey);
76
90
  }
91
+ if (this.#seen.has(key)) return false;
77
92
  this.#seen.set(key, now + ttlMs);
93
+ return true;
94
+ }
95
+ }
96
+
97
+ /** What {@link RedisTotpReplayGuard} needs of a Redis client. */
98
+ export interface ReplayRedisClient {
99
+ set(
100
+ key: string,
101
+ value: string,
102
+ expiry: "PX",
103
+ ttlMs: number,
104
+ mode: "NX",
105
+ ): Promise<unknown>;
106
+ }
107
+
108
+ /**
109
+ * A replay guard shared across instances: `SET key 1 PX ttl NX` records a code
110
+ * only if no instance did first. Needed as soon as the app runs on more than
111
+ * one, or the same code works once per instance.
112
+ */
113
+ export class RedisTotpReplayGuard implements TotpReplayGuard {
114
+ readonly #source: ReplayRedisClient | (() => Promise<ReplayRedisClient>);
115
+ #resolved: ReplayRedisClient | undefined;
116
+ readonly #prefix: string;
117
+
118
+ constructor(
119
+ source: ReplayRedisClient | (() => Promise<ReplayRedisClient>),
120
+ options: { prefix?: string } = {},
121
+ ) {
122
+ this.#source = source;
123
+ this.#prefix = options.prefix ?? "warden:totp";
124
+ }
125
+
126
+ async claim(key: string, ttlMs: number): Promise<boolean> {
127
+ if (this.#resolved === undefined) {
128
+ this.#resolved =
129
+ typeof this.#source === "function"
130
+ ? await this.#source()
131
+ : this.#source;
132
+ }
133
+ // Redis refuses PX 0; a code with no replay time left still gets 1 ms.
134
+ const result = await this.#resolved.set(
135
+ `${this.#prefix}:${key}`,
136
+ "1",
137
+ "PX",
138
+ Math.max(1, Math.ceil(ttlMs)),
139
+ "NX",
140
+ );
141
+ return result === "OK";
78
142
  }
79
143
  }
80
144
 
@@ -106,10 +170,16 @@ export class TotpProvider {
106
170
  replayGuard === null
107
171
  ? null
108
172
  : (replayGuard ?? new MemoryTotpReplayGuard());
109
- if (this.#cfg.digits < 6 || this.#cfg.digits > 8) {
173
+ // Every number bounds a loop or a buffer: a period of 0 crashed code
174
+ // generation, a window of Infinity never ended the verification loop,
175
+ // and NaN slips past a `<` comparison.
176
+ assertIntegerIn("TOTP digits", this.#cfg.digits, 6, 8);
177
+ assertIntegerIn("TOTP period", this.#cfg.period, 1, 3600);
178
+ assertIntegerIn("TOTP window", this.#cfg.window, 0, 10);
179
+ if (!TOTP_ALGORITHMS.includes(this.#cfg.algorithm)) {
110
180
  throw new WardenError(
111
181
  "INVALID_CONFIG",
112
- `TOTP digits must be 6-8, got ${this.#cfg.digits}`,
182
+ `TOTP algorithm must be one of ${TOTP_ALGORITHMS.join(", ")}, got ${String(this.#cfg.algorithm)}`,
113
183
  );
114
184
  }
115
185
  }
@@ -169,13 +239,11 @@ export class TotpProvider {
169
239
  // for the whole window — with the default settings, ~90 seconds in
170
240
  // which a shoulder-surfed or intercepted code still works.
171
241
  const seenKey = this.#replayKey(secret, counter);
172
- if (await this.#replayGuard.used(seenKey)) return false;
173
- // Remember it for as long as it could still be replayed: until the
174
- // last step that would accept it has passed.
242
+ // Claimed for as long as it could still be replayed: until the last
243
+ // step that would accept it has passed.
175
244
  const ttlMs =
176
245
  (counter + this.#cfg.window + 1) * this.#cfg.period * 1000 - atMs;
177
- await this.#replayGuard.remember(seenKey, Math.max(ttlMs, 0));
178
- return true;
246
+ return this.#replayGuard.claim(seenKey, Math.max(ttlMs, 0));
179
247
  }
180
248
  return false;
181
249
  }
@@ -488,7 +488,10 @@ export class WebauthnProvider {
488
488
  alg: coseToKeyObject(authData.cosePublicKey).alg,
489
489
  };
490
490
  });
491
- if (parsed === null) {
491
+ // The algorithms offered to the browser are a requirement, not a hint:
492
+ // an authenticator is free to answer with any key it has, and one this
493
+ // server did not accept must not be stored.
494
+ if (parsed === null || !this.#algorithms.includes(parsed.alg)) {
492
495
  return { verified: false };
493
496
  }
494
497
  await this.#credentials.save({
package/src/middleware.ts CHANGED
@@ -113,6 +113,8 @@ export interface WardenContext {
113
113
  response: {
114
114
  status: (code: number) => unknown;
115
115
  json: (data: unknown) => void;
116
+ /** Set a response header — the `WWW-Authenticate` challenge of a 401. */
117
+ header?: (name: string, value: string) => unknown;
116
118
  /**
117
119
  * Write an ENCRYPTED cookie, for the remember-me token. Optional: a
118
120
  * host without it simply cannot offer "keep me signed in", and
@@ -424,6 +426,13 @@ export function renderAuthError(
424
426
  ctx.response.redirect(error.redirectTo);
425
427
  return;
426
428
  }
429
+ if (error.challenge !== undefined) {
430
+ ctx.response.header?.call(
431
+ ctx.response,
432
+ "WWW-Authenticate",
433
+ error.challenge,
434
+ );
435
+ }
427
436
  ctx.response.status(error.status ?? 401);
428
437
  ctx.response.json({
429
438
  error: { code: error.code, message: error.message },
@@ -7,17 +7,3 @@
7
7
  export declare function jwtSign(payload: string, secret: string): string;
8
8
 
9
9
  export declare function jwtVerify(token: string, secret: string): string;
10
-
11
- export declare function constantTimeEq(a: string, b: string): boolean;
12
-
13
- export declare function hmacSign(data: string, secret: string): string;
14
-
15
- export declare function hmacVerify(
16
- data: string,
17
- signature: string,
18
- secret: string,
19
- ): boolean;
20
-
21
- export declare function randomBytes(len: number): string;
22
-
23
- export declare function randomHex(len: number): string;
package/src/native.ts CHANGED
@@ -23,11 +23,6 @@ export type NativeWarden = typeof import("./native/generated.js");
23
23
  const attempt = loadNativeBinary<NativeWarden>();
24
24
  const native = attempt.loaded ? attempt.binary : undefined;
25
25
 
26
- /** Whether the Rust NAPI engine loaded. */
27
- export function isNativeAvailable(): boolean {
28
- return native !== undefined;
29
- }
30
-
31
26
  /** Get the native engine. Returns undefined if not loaded — caller must throw. */
32
27
  export function nativeWarden(): NativeWarden | undefined {
33
28
  return native;