@c9up/warden 0.2.2 → 0.2.4

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 (109) 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/configure.d.ts +6 -0
  27. package/dist/configure.d.ts.map +1 -1
  28. package/dist/configure.js +2 -21
  29. package/dist/configure.js.map +1 -1
  30. package/dist/duration.d.ts.map +1 -1
  31. package/dist/duration.js +6 -0
  32. package/dist/duration.js.map +1 -1
  33. package/dist/errors.d.ts +6 -0
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +6 -0
  36. package/dist/errors.js.map +1 -1
  37. package/dist/index.d.ts +8 -6
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +2 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/mfa/BackupCodesProvider.d.ts +8 -1
  42. package/dist/mfa/BackupCodesProvider.d.ts.map +1 -1
  43. package/dist/mfa/BackupCodesProvider.js +5 -7
  44. package/dist/mfa/BackupCodesProvider.js.map +1 -1
  45. package/dist/mfa/MfaManager.d.ts +18 -2
  46. package/dist/mfa/MfaManager.d.ts.map +1 -1
  47. package/dist/mfa/MfaManager.js +38 -35
  48. package/dist/mfa/MfaManager.js.map +1 -1
  49. package/dist/mfa/TotpProvider.d.ts +30 -6
  50. package/dist/mfa/TotpProvider.d.ts.map +1 -1
  51. package/dist/mfa/TotpProvider.js +48 -19
  52. package/dist/mfa/TotpProvider.js.map +1 -1
  53. package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
  54. package/dist/mfa/WebauthnProvider.js +4 -1
  55. package/dist/mfa/WebauthnProvider.js.map +1 -1
  56. package/dist/middleware.d.ts +2 -0
  57. package/dist/middleware.d.ts.map +1 -1
  58. package/dist/middleware.js +3 -0
  59. package/dist/middleware.js.map +1 -1
  60. package/dist/native/generated.d.ts +0 -5
  61. package/dist/native/generated.d.ts.map +1 -1
  62. package/dist/native.d.ts +0 -2
  63. package/dist/native.d.ts.map +1 -1
  64. package/dist/native.js +0 -4
  65. package/dist/native.js.map +1 -1
  66. package/dist/strategies/JwtStrategy.d.ts +11 -1
  67. package/dist/strategies/JwtStrategy.d.ts.map +1 -1
  68. package/dist/strategies/JwtStrategy.js +9 -2
  69. package/dist/strategies/JwtStrategy.js.map +1 -1
  70. package/dist/strategies/SessionStrategy.d.ts +22 -0
  71. package/dist/strategies/SessionStrategy.d.ts.map +1 -1
  72. package/dist/strategies/SessionStrategy.js +31 -1
  73. package/dist/strategies/SessionStrategy.js.map +1 -1
  74. package/dist/stubs.d.ts +14 -0
  75. package/dist/stubs.d.ts.map +1 -0
  76. package/dist/stubs.js +15 -0
  77. package/dist/stubs.js.map +1 -0
  78. package/dist/vendor/nodeEnv.d.ts +5 -0
  79. package/dist/vendor/nodeEnv.d.ts.map +1 -0
  80. package/dist/vendor/nodeEnv.js +38 -0
  81. package/dist/vendor/nodeEnv.js.map +1 -0
  82. package/index.darwin-arm64.node +0 -0
  83. package/index.darwin-x64.node +0 -0
  84. package/index.linux-arm64-gnu.node +0 -0
  85. package/index.linux-x64-gnu.node +0 -0
  86. package/index.win32-x64-msvc.node +0 -0
  87. package/package.json +4 -3
  88. package/src/AttemptStore.ts +158 -0
  89. package/src/AuthManager.ts +9 -7
  90. package/src/AuthRateLimiter.ts +85 -80
  91. package/src/Authenticator.ts +92 -13
  92. package/src/RememberMeToken.ts +36 -8
  93. package/src/bouncer/evaluate.ts +1 -1
  94. package/src/configure.ts +8 -24
  95. package/src/duration.ts +8 -0
  96. package/src/errors.ts +11 -1
  97. package/src/index.ts +24 -3
  98. package/src/mfa/BackupCodesProvider.ts +13 -14
  99. package/src/mfa/MfaManager.ts +58 -43
  100. package/src/mfa/TotpProvider.ts +90 -22
  101. package/src/mfa/WebauthnProvider.ts +4 -1
  102. package/src/middleware.ts +9 -0
  103. package/src/native/generated.ts +0 -14
  104. package/src/native.ts +0 -5
  105. package/src/strategies/JwtStrategy.ts +20 -2
  106. package/src/strategies/SessionStrategy.ts +52 -1
  107. package/src/stubs.ts +16 -0
  108. package/src/vendor/nodeEnv.ts +37 -0
  109. package/stubs/config/auth.stub +23 -0
@@ -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/configure.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import { stubsRoot } from "./stubs.js";
2
3
 
3
4
  interface Codemods {
4
5
  addProvider(importPath: string): Promise<void>;
@@ -8,6 +9,12 @@ interface Codemods {
8
9
  content: string,
9
10
  options?: { force?: boolean },
10
11
  ): Promise<void>;
12
+ makeUsingStub(
13
+ stubsRoot: string,
14
+ stubPath: string,
15
+ state?: Record<string, string | number | boolean>,
16
+ options?: { force?: boolean },
17
+ ): Promise<{ path: string; contents: string }>;
11
18
  }
12
19
 
13
20
  export async function configure(codemods: Codemods): Promise<void> {
@@ -17,30 +24,7 @@ export async function configure(codemods: Codemods): Promise<void> {
17
24
  JWT_SECRET: jwtSecret,
18
25
  JWT_EXPIRY: "3600",
19
26
  });
20
- await codemods.writeFile(
21
- "config/auth.ts",
22
- `import { defineConfig, jwtGuard } from '@c9up/warden'
23
-
24
- export default defineConfig({
25
- default: 'jwt',
26
- guards: {
27
- jwt: jwtGuard({
28
- secret: process.env.JWT_SECRET ?? '',
29
- // Seconds, or a duration string — JWT_EXPIRY=1h works as written.
30
- expiresIn: process.env.JWT_EXPIRY ?? 3600,
31
- // TODO: wire these to your user model (e.g. via your ORM).
32
- // The JWT guard needs both to issue and verify tokens.
33
- findUser: async (_id) => {
34
- throw new Error('TODO: implement findUser(id) for the JWT guard in config/auth.ts')
35
- },
36
- verifyCredentials: async (_email, _password) => {
37
- throw new Error('TODO: implement verifyCredentials(email, password) in config/auth.ts')
38
- },
39
- }),
40
- },
41
- })
42
- `,
43
- );
27
+ await codemods.makeUsingStub(stubsRoot, "config/auth.stub");
44
28
  // Announce the TODOs on stderr so `ream add @c9up/warden` doesn't end
45
29
  // with a quiet success that the user reads as "auth is wired". The
46
30
  // generated config/auth.ts ships with `throw new Error('TODO ...')`
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;
@@ -31,6 +31,17 @@ export interface JwtClaims {
31
31
  [key: string]: unknown;
32
32
  }
33
33
 
34
+ /** What a token asserts beyond who its user is. */
35
+ export interface SignTokenOptions {
36
+ /**
37
+ * The user completed an MFA step-up for this session (`MfaManager.verify()`
38
+ * succeeded). Sets the `mfa` claim `@RequireMfa()` reads. It says the step
39
+ * was DONE, not that the account has MFA enabled — so it comes from the
40
+ * step-up flow and never from `findUser`.
41
+ */
42
+ mfa?: boolean;
43
+ }
44
+
34
45
  function sign(payload: JwtClaims, secret: string): string {
35
46
  const rust = nativeWarden();
36
47
  if (!rust) {
@@ -204,10 +215,16 @@ export class JwtStrategy implements AuthStrategy {
204
215
  return { authenticated: false, error: "User not found" };
205
216
  }
206
217
 
207
- return { authenticated: true, user };
218
+ // `mfa` is the TOKEN's step-up claim, whatever `findUser` said: an app
219
+ // that returns the account's "MFA enabled" flag there would otherwise
220
+ // unlock @RequireMfa routes for a token that never stepped up.
221
+ return {
222
+ authenticated: true,
223
+ user: { ...user, mfa: payload.mfa === true },
224
+ };
208
225
  }
209
226
 
210
- signToken(user: UserPayload): string {
227
+ signToken(user: UserPayload, options: SignTokenOptions = {}): string {
211
228
  const now = Math.floor(Date.now() / 1000);
212
229
  return sign(
213
230
  {
@@ -217,6 +234,7 @@ export class JwtStrategy implements AuthStrategy {
217
234
  iat: now,
218
235
  exp: now + this.#expiresIn,
219
236
  jti: randomUUID(),
237
+ ...(options.mfa === true ? { mfa: true } : {}),
220
238
  },
221
239
  this.#secret,
222
240
  );