@c9up/warden 0.2.3 → 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 (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 +22 -0
  67. package/dist/strategies/SessionStrategy.d.ts.map +1 -1
  68. package/dist/strategies/SessionStrategy.js +31 -1
  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 +1 -1
  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 +52 -1
  98. package/src/vendor/nodeEnv.ts +37 -0
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Where failed-attempt counters live — for the login throttle
3
+ * ({@link AuthRateLimiter}) and the MFA lockout (`MfaManager`).
4
+ *
5
+ * The count is taken BEFORE the credential is checked, by one atomic
6
+ * increment. Checking "is it locked?" first and recording the failure after
7
+ * let a burst of concurrent attempts all read "not locked" and all reach the
8
+ * verifier; an increment that returns the new count cannot be raced that way.
9
+ *
10
+ * The memory store is one process's; a cluster shares {@link RedisAttemptStore}
11
+ * so a lockout holds whichever instance the next attempt lands on.
12
+ */
13
+
14
+ /** A window of attempts counted under one key. */
15
+ export interface AttemptCount {
16
+ /** Attempts in the current window, this one included. */
17
+ count: number;
18
+ /** Seconds until the window ends and the count starts over. */
19
+ resetSeconds: number;
20
+ }
21
+
22
+ export interface AttemptStore {
23
+ /**
24
+ * Count one attempt under `key`, atomically, and return the count so far.
25
+ * The window starts at the first attempt and lasts `windowSeconds`.
26
+ */
27
+ increment(key: string, windowSeconds: number): Promise<AttemptCount>;
28
+ /** The attempts counted under `key` in its current window (0 if none). */
29
+ count(key: string): Promise<number>;
30
+ /** Forget `key`'s attempts — after a success. */
31
+ reset(key: string): Promise<void>;
32
+ }
33
+
34
+ /** Most keys the memory store holds before it makes room. */
35
+ const DEFAULT_MAX_KEYS = 100_000;
36
+
37
+ /** In this process's memory, bounded. Not shared across instances. */
38
+ export class MemoryAttemptStore implements AttemptStore {
39
+ readonly #entries = new Map<string, { count: number; resetAt: number }>();
40
+ readonly #maxKeys: number;
41
+
42
+ constructor(options: { maxKeys?: number } = {}) {
43
+ this.#maxKeys = options.maxKeys ?? DEFAULT_MAX_KEYS;
44
+ }
45
+
46
+ async increment(key: string, windowSeconds: number): Promise<AttemptCount> {
47
+ const now = Date.now();
48
+ let entry = this.#entries.get(key);
49
+ if (entry === undefined || entry.resetAt <= now) {
50
+ this.#entries.delete(key);
51
+ this.#makeRoom(now);
52
+ entry = { count: 0, resetAt: now + windowSeconds * 1000 };
53
+ this.#entries.set(key, entry);
54
+ }
55
+ entry.count++;
56
+ return {
57
+ count: entry.count,
58
+ resetSeconds: Math.ceil((entry.resetAt - now) / 1000),
59
+ };
60
+ }
61
+
62
+ async count(key: string): Promise<number> {
63
+ const entry = this.#entries.get(key);
64
+ if (entry === undefined) return 0;
65
+ if (entry.resetAt <= Date.now()) {
66
+ this.#entries.delete(key);
67
+ return 0;
68
+ }
69
+ return entry.count;
70
+ }
71
+
72
+ async reset(key: string): Promise<void> {
73
+ this.#entries.delete(key);
74
+ }
75
+
76
+ /**
77
+ * Keep the map under its bound: drop the expired windows, and if every
78
+ * window is still live, the oldest ones — a Map iterates in insertion
79
+ * order. Evicting a live window forgives its attempts; growing without
80
+ * bound would take the process down instead.
81
+ */
82
+ #makeRoom(now: number): void {
83
+ if (this.#entries.size < this.#maxKeys) return;
84
+ for (const [key, entry] of this.#entries) {
85
+ if (entry.resetAt <= now) this.#entries.delete(key);
86
+ }
87
+ for (const key of this.#entries.keys()) {
88
+ if (this.#entries.size < this.#maxKeys) break;
89
+ this.#entries.delete(key);
90
+ }
91
+ }
92
+ }
93
+
94
+ /** What {@link RedisAttemptStore} needs of a Redis client (ioredis, node-redis). */
95
+ export interface AttemptRedisClient {
96
+ incr(key: string): Promise<number>;
97
+ expire(key: string, seconds: number): Promise<unknown>;
98
+ ttl(key: string): Promise<number>;
99
+ get(key: string): Promise<string | null>;
100
+ del(key: string): Promise<unknown>;
101
+ }
102
+
103
+ /** A client, or a resolver for one — resolved on the first attempt. */
104
+ export type AttemptRedisSource =
105
+ | AttemptRedisClient
106
+ | (() => Promise<AttemptRedisClient>);
107
+
108
+ /**
109
+ * Shared across instances through Redis: `INCR`, then `EXPIRE` on the first
110
+ * hit of a window.
111
+ */
112
+ export class RedisAttemptStore implements AttemptStore {
113
+ readonly #source: AttemptRedisSource;
114
+ #resolved: AttemptRedisClient | undefined;
115
+ readonly #prefix: string;
116
+
117
+ constructor(source: AttemptRedisSource, options: { prefix?: string } = {}) {
118
+ this.#source = source;
119
+ this.#prefix = options.prefix ?? "warden:attempts";
120
+ }
121
+
122
+ async #client(): Promise<AttemptRedisClient> {
123
+ if (this.#resolved) return this.#resolved;
124
+ this.#resolved =
125
+ typeof this.#source === "function" ? await this.#source() : this.#source;
126
+ return this.#resolved;
127
+ }
128
+
129
+ async increment(key: string, windowSeconds: number): Promise<AttemptCount> {
130
+ const client = await this.#client();
131
+ const namespaced = `${this.#prefix}:${key}`;
132
+ const count = await client.incr(namespaced);
133
+ if (count === 1) {
134
+ await client.expire(namespaced, windowSeconds);
135
+ return { count, resetSeconds: windowSeconds };
136
+ }
137
+ const ttl = await client.ttl(namespaced);
138
+ // A key with no expiry — the process died between its INCR and its
139
+ // EXPIRE — would count forever: give it the window it should have had.
140
+ if (ttl < 0) {
141
+ await client.expire(namespaced, windowSeconds);
142
+ return { count, resetSeconds: windowSeconds };
143
+ }
144
+ return { count, resetSeconds: ttl };
145
+ }
146
+
147
+ async count(key: string): Promise<number> {
148
+ const client = await this.#client();
149
+ const value = await client.get(`${this.#prefix}:${key}`);
150
+ const count = Number(value ?? 0);
151
+ return Number.isSafeInteger(count) ? count : 0;
152
+ }
153
+
154
+ async reset(key: string): Promise<void> {
155
+ const client = await this.#client();
156
+ await client.del(`${this.#prefix}:${key}`);
157
+ }
158
+ }
@@ -7,13 +7,10 @@
7
7
  import { Authenticator } from "./Authenticator.js";
8
8
  import { WardenError } from "./errors.js";
9
9
  import type { WardenContext } from "./middleware.js";
10
- import { sanitizePayload } from "./sanitize.js";
11
-
12
- export { sanitizePayload };
13
-
14
10
  import { MemoryRightsStore } from "./rights/MemoryRightsStore.js";
15
11
  import { RightsResolver } from "./rights/RightsResolver.js";
16
12
  import type { EffectivePermissions, Scope } from "./rights/types.js";
13
+ import { sanitizePayload } from "./sanitize.js";
17
14
  import type {
18
15
  SessionGuardState,
19
16
  SessionStore,
@@ -121,7 +118,7 @@ export interface AuthConfig {
121
118
 
122
119
  /** A strategy that can mint a token for a resolved user (e.g. JwtStrategy). */
123
120
  interface TokenIssuer {
124
- signToken(user: UserPayload): string;
121
+ signToken(user: UserPayload, options?: { mfa?: boolean }): string;
125
122
  }
126
123
 
127
124
  /**
@@ -288,7 +285,12 @@ export class AuthManager {
288
285
  * / permissions / iat / exp / jti — are identical. Throws if the resolved
289
286
  * strategy can't issue tokens (e.g. session / API-key strategies).
290
287
  */
291
- issueFor(user: UserPayload, strategyName?: string): string {
288
+ issueFor(
289
+ user: UserPayload,
290
+ strategyName?: string,
291
+ /** `{ mfa: true }` once the user completed an MFA step-up. */
292
+ options?: { mfa?: boolean },
293
+ ): string {
292
294
  const strategy = this.getStrategy(strategyName);
293
295
  if (!isTokenIssuer(strategy)) {
294
296
  throw new WardenError(
@@ -299,7 +301,7 @@ export class AuthManager {
299
301
  },
300
302
  );
301
303
  }
302
- return strategy.signToken(user);
304
+ return strategy.signToken(user, options);
303
305
  }
304
306
 
305
307
  /**
@@ -1,105 +1,110 @@
1
1
  /**
2
- * AuthRateLimiter — brute force protection for login endpoints.
2
+ * AuthRateLimiter — brute force protection for login endpoints, and the
3
+ * lockout behind `MfaManager.verify()`.
3
4
  *
4
- * Dual-key rate limiting: IP + email to prevent distributed attacks.
5
+ * An attempt is counted BEFORE the credential is checked, by one atomic
6
+ * increment per key ({@link AttemptStore}): checking first and recording the
7
+ * failure afterwards let a burst of concurrent attempts all pass the check.
8
+ * A success clears the keys.
9
+ *
10
+ * A login is counted under two keys, its IP and its identifier
11
+ * ({@link AuthRateLimiter.loginKeys}), so neither spraying one password across
12
+ * accounts from one address nor one account from many addresses gets through.
13
+ *
14
+ * const keys = AuthRateLimiter.loginKeys(ctx.request.ip(), email)
15
+ * if (!(await limiter.attempt(...keys)).allowed) return tooManyAttempts()
16
+ * const user = await verify(email, password)
17
+ * if (user) await limiter.clear(...keys)
5
18
  *
6
19
  * @implements MISS-26
7
20
  */
8
21
 
22
+ import { type AttemptStore, MemoryAttemptStore } from "./AttemptStore.js";
23
+ import { WardenError } from "./errors.js";
24
+
9
25
  export interface AuthRateLimiterConfig {
10
- maxAttempts?: number; // default 5
11
- windowSeconds?: number; // default 900 (15 min)
26
+ /** Attempts allowed per window, per key. Default 5. */
27
+ maxAttempts?: number;
28
+ /** How long a window lasts, in seconds. Default 900 (15 min). */
29
+ windowSeconds?: number;
30
+ /**
31
+ * Where the counts live. Default: this process's memory. A cluster passes a
32
+ * shared one ({@link RedisAttemptStore}), or a lockout holds only on the
33
+ * instance that counted it.
34
+ */
35
+ store?: AttemptStore;
12
36
  }
13
37
 
14
- interface AttemptEntry {
15
- count: number;
16
- resetAt: number;
38
+ /** What {@link AuthRateLimiter.attempt} decided. */
39
+ export interface AttemptDecision {
40
+ /** Whether this attempt may go on to the credential check. */
41
+ allowed: boolean;
42
+ /** Attempts left on the most-used key. */
43
+ remaining: number;
44
+ /** Seconds until the most-used key's window ends. */
45
+ retryAfterSeconds: number;
17
46
  }
18
47
 
19
48
  export class AuthRateLimiter {
20
- #maxAttempts: number;
21
- #window: number;
22
- #store: Map<string, AttemptEntry> = new Map();
23
- #maxStoreSize = 100_000;
49
+ readonly #maxAttempts: number;
50
+ readonly #windowSeconds: number;
51
+ readonly #store: AttemptStore;
24
52
 
25
- constructor(config?: AuthRateLimiterConfig) {
26
- this.#maxAttempts = config?.maxAttempts ?? 5;
27
- if (this.#maxAttempts <= 0) this.#maxAttempts = 1;
28
- this.#window = (config?.windowSeconds ?? 900) * 1000;
29
- if (this.#window <= 0) this.#window = 900_000; // prevent bypass via 0/negative
53
+ constructor(config: AuthRateLimiterConfig = {}) {
54
+ this.#maxAttempts = positiveInteger("maxAttempts", config.maxAttempts ?? 5);
55
+ this.#windowSeconds = positiveInteger(
56
+ "windowSeconds",
57
+ config.windowSeconds ?? 900,
58
+ );
59
+ this.#store = config.store ?? new MemoryAttemptStore();
30
60
  }
31
61
 
32
- /** Check if an attempt is allowed. Returns false if rate limited. */
33
- check(ip: string, identifier: string): boolean {
34
- const now = Date.now();
35
- const ipNorm = normalizeIp(ip);
36
- const identifierNorm = normalizeIdentifier(identifier);
37
- // Dual key: limit both by IP and by identifier (email)
38
- const ipKey = `ip:${ipNorm}`;
39
- const idKey = `id:${identifierNorm}`;
40
-
41
- return this.#checkKey(ipKey, now) && this.#checkKey(idKey, now);
62
+ /** The keys a login attempt is counted under: its IP and its identifier. */
63
+ static loginKeys(ip: string, identifier: string): string[] {
64
+ return [`ip:${ip.trim()}`, `id:${identifier.trim().toLowerCase()}`];
42
65
  }
43
66
 
44
- /** Record a failed attempt. */
45
- recordFailure(ip: string, identifier: string): void {
46
- const now = Date.now();
47
- const ipNorm = normalizeIp(ip);
48
- const identifierNorm = normalizeIdentifier(identifier);
49
- this.#increment(`ip:${ipNorm}`, now);
50
- this.#increment(`id:${identifierNorm}`, now);
51
- }
52
-
53
- /** Reset counters on successful login. */
54
- recordSuccess(ip: string, identifier: string): void {
55
- const ipNorm = normalizeIp(ip);
56
- const identifierNorm = normalizeIdentifier(identifier);
57
- this.#store.delete(`ip:${ipNorm}`);
58
- this.#store.delete(`id:${identifierNorm}`);
67
+ /**
68
+ * Count an attempt under every key, and say whether it may go on. Call it
69
+ * BEFORE checking the credential; a refused attempt must not reach it.
70
+ */
71
+ async attempt(...keys: string[]): Promise<AttemptDecision> {
72
+ const counts = await Promise.all(
73
+ keys.map((key) => this.#store.increment(key, this.#windowSeconds)),
74
+ );
75
+ let highest = { count: 0, resetSeconds: 0 };
76
+ for (const counted of counts) {
77
+ if (counted.count > highest.count) highest = counted;
78
+ }
79
+ return {
80
+ allowed: highest.count <= this.#maxAttempts,
81
+ remaining: Math.max(0, this.#maxAttempts - highest.count),
82
+ retryAfterSeconds: highest.resetSeconds,
83
+ };
59
84
  }
60
85
 
61
- /** Get remaining attempts for an identifier. */
62
- remaining(ip: string, identifier: string): number {
63
- const ipNorm = normalizeIp(ip);
64
- const identifierNorm = normalizeIdentifier(identifier);
65
- const ipEntry = this.#store.get(`ip:${ipNorm}`);
66
- const idEntry = this.#store.get(`id:${identifierNorm}`);
67
- const ipRemaining = ipEntry
68
- ? Math.max(0, this.#maxAttempts - ipEntry.count)
69
- : this.#maxAttempts;
70
- const idRemaining = idEntry
71
- ? Math.max(0, this.#maxAttempts - idEntry.count)
72
- : this.#maxAttempts;
73
- return Math.min(ipRemaining, idRemaining);
86
+ /** Whether any key has used up its attempts, without counting one. */
87
+ async isBlocked(...keys: string[]): Promise<boolean> {
88
+ const counts = await Promise.all(keys.map((key) => this.#store.count(key)));
89
+ return counts.some((count) => count >= this.#maxAttempts);
74
90
  }
75
91
 
76
- #checkKey(key: string, now: number): boolean {
77
- const entry = this.#store.get(key);
78
- if (!entry || entry.resetAt < now) return true;
79
- return entry.count < this.#maxAttempts;
92
+ /** Forget the keys' attempts — after a success. */
93
+ async clear(...keys: string[]): Promise<void> {
94
+ await Promise.all(keys.map((key) => this.#store.reset(key)));
80
95
  }
81
-
82
- #increment(key: string, now: number): void {
83
- // Evict expired entries when store grows too large (prevent OOM)
84
- if (this.#store.size > this.#maxStoreSize) {
85
- for (const [k, v] of this.#store) {
86
- if (v.resetAt < now) this.#store.delete(k);
87
- }
88
- }
89
-
90
- let entry = this.#store.get(key);
91
- if (!entry || entry.resetAt < now) {
92
- entry = { count: 0, resetAt: now + this.#window };
93
- this.#store.set(key, entry);
94
- }
95
- entry.count++;
96
- }
97
- }
98
-
99
- function normalizeIdentifier(identifier: string): string {
100
- return identifier.trim().toLowerCase();
101
96
  }
102
97
 
103
- function normalizeIp(ip: string): string {
104
- return ip.trim();
98
+ /**
99
+ * A limit that would not limit is refused: `Infinity` attempts or a window of
100
+ * 0 turned the protection off, silently.
101
+ */
102
+ function positiveInteger(field: string, value: number): number {
103
+ if (!Number.isSafeInteger(value) || value <= 0) {
104
+ throw new WardenError(
105
+ "INVALID_CONFIG",
106
+ `AuthRateLimiter ${field} must be a positive whole number, got ${String(value)}`,
107
+ );
108
+ }
109
+ return value;
105
110
  }
@@ -25,9 +25,11 @@ import type { WardenContext } from "./middleware.js";
25
25
  import { sanitizePayload } from "./sanitize.js";
26
26
  import {
27
27
  createSessionGuardState,
28
+ type RememberMeCookieAttributes,
28
29
  type SessionGuardState,
29
30
  type SessionStore,
30
31
  } from "./strategies/SessionStrategy.js";
32
+ import { inProduction } from "./vendor/nodeEnv.js";
31
33
 
32
34
  /**
33
35
  * Guard names Warden accepts for the API-key / access-tokens driver. AdonisJS
@@ -76,6 +78,27 @@ interface RememberMeIssuer {
76
78
  revokeRememberMeToken(cookieValue: unknown): Promise<void>;
77
79
  readonly rememberMeCookieName: string;
78
80
  readonly rememberMeAgeSeconds: number;
81
+ /** Overrides of the cookie attributes; the defaults below otherwise. */
82
+ readonly rememberMeCookie?: RememberMeCookieAttributes;
83
+ }
84
+
85
+ /**
86
+ * The remember-me cookie's attributes. Ream has no application-wide cookie
87
+ * defaults to inherit (AdonisJS takes them from `config/app.ts`), so they are
88
+ * set here: a credential that lives for years is `Secure` in production,
89
+ * `SameSite=Lax`, and scoped to the whole site.
90
+ */
91
+ function rememberMeCookieOptions(
92
+ strategy: RememberMeIssuer,
93
+ ): Record<string, unknown> {
94
+ return {
95
+ path: "/",
96
+ sameSite: "lax",
97
+ secure: inProduction(),
98
+ ...strategy.rememberMeCookie,
99
+ maxAge: strategy.rememberMeAgeSeconds,
100
+ httpOnly: true,
101
+ };
79
102
  }
80
103
 
81
104
  /**
@@ -115,9 +138,24 @@ function hasVerifyWithContext(
115
138
  export interface ExtractedCredentials {
116
139
  bearerToken: string;
117
140
  apiKey: string;
141
+ /** The whole `Authorization` header when its scheme is Basic, else `""`. */
142
+ basicAuth: string;
118
143
  session: SessionStore | undefined;
119
144
  }
120
145
 
146
+ /**
147
+ * The challenge of a Basic guard (`BasicAuthStrategy.challenge`), or undefined
148
+ * for any other guard. Structural, like the other capability probes: a Basic
149
+ * guard is one that has a challenge to send.
150
+ */
151
+ function basicChallengeOf(
152
+ strategy: AuthStrategy | undefined,
153
+ ): string | undefined {
154
+ const challenge: unknown =
155
+ strategy === undefined ? undefined : Reflect.get(strategy, "challenge");
156
+ return typeof challenge === "string" ? challenge : undefined;
157
+ }
158
+
121
159
  /**
122
160
  * Resolve the header the API-key guard reads its key from. Prefers the
123
161
  * registered guard's `headerName` (under either accepted guard name), else the
@@ -151,10 +189,12 @@ export function extractCredentials(
151
189
  const bearerToken = authHeader.startsWith("Bearer ")
152
190
  ? authHeader.slice(7)
153
191
  : "";
192
+ // The scheme is case-insensitive (RFC 7235); the strategy decodes the rest.
193
+ const basicAuth = /^basic\s/i.test(authHeader) ? authHeader : "";
154
194
  // HTTP header names are case-insensitive; runtimes lowercase incoming keys,
155
195
  // so normalise the configured header name before the lookup.
156
196
  const apiKey = headers[resolveApiKeyHeader(auth).toLowerCase()] ?? "";
157
- return { bearerToken, apiKey, session: ctx.session };
197
+ return { bearerToken, apiKey, basicAuth, session: ctx.session };
158
198
  }
159
199
 
160
200
  /** Outcome of {@link tryAuthenticate}. */
@@ -172,16 +212,12 @@ export interface AuthAttempt {
172
212
  * Distinguishes crashes (strategy threw / `strategyCrash`) from credential
173
213
  * rejections so the caller can return 500 vs 401.
174
214
  */
175
- export async function tryAuthenticate(
215
+ async function tryAuthenticate(
176
216
  auth: AuthManager,
177
217
  strategies: string[],
178
- creds: {
179
- bearerToken: string;
180
- apiKey: string;
181
- session: SessionStore | undefined;
182
- },
218
+ creds: ExtractedCredentials,
183
219
  ): Promise<AuthAttempt> {
184
- const { bearerToken, apiKey, session } = creds;
220
+ const { bearerToken, apiKey, basicAuth, session } = creds;
185
221
  let result: AuthResult | null = null;
186
222
  let viaGuard: string | undefined;
187
223
  let attemptCount = 0;
@@ -205,6 +241,12 @@ export async function tryAuthenticate(
205
241
  // The session path bypasses AuthManager.verify(), so apply the
206
242
  // same prototype-pollution guard JWT / api-key users get there.
207
243
  if (r.user) sanitizePayload(r.user);
244
+ } else if (basicChallengeOf(strategy) !== undefined) {
245
+ // A Basic guard reads the Authorization header itself, and only
246
+ // that: a Bearer token or an API key is not a password.
247
+ if (!basicAuth) continue;
248
+ attemptCount++;
249
+ r = await auth.verify(basicAuth, strategyName);
208
250
  } else {
209
251
  // Native-first credential, other transport as fallback so a
210
252
  // single-credential client still authenticates (and an invalid
@@ -357,7 +399,7 @@ export class GuardAccessor {
357
399
  this.#ctx.response,
358
400
  strategy.rememberMeCookieName,
359
401
  revived.cookieValue,
360
- { maxAge: strategy.rememberMeAgeSeconds, httpOnly: true },
402
+ rememberMeCookieOptions(strategy),
361
403
  );
362
404
  // Seat the session WITHOUT `login()`: that method means a password was
363
405
  // typed, and it clears `viaRemember` — the one thing this path exists to
@@ -450,10 +492,12 @@ export class GuardAccessor {
450
492
  );
451
493
  }
452
494
  try {
453
- write.call(this.#ctx.response, strategy.rememberMeCookieName, value, {
454
- maxAge: strategy.rememberMeAgeSeconds,
455
- httpOnly: true,
456
- });
495
+ write.call(
496
+ this.#ctx.response,
497
+ strategy.rememberMeCookieName,
498
+ value,
499
+ rememberMeCookieOptions(strategy),
500
+ );
457
501
  } catch (err) {
458
502
  // The row exists and the browser will never hold it: a credential
459
503
  // nobody can reach is still one, so it does not survive the failure.
@@ -467,12 +511,40 @@ export class GuardAccessor {
467
511
  #clearRememberMe(): void {
468
512
  const strategy = strategyOrUndefined(this.#auth, this.#name);
469
513
  if (!strategy || !isRememberMeIssuer(strategy)) return;
514
+ // Cleared on the path and domain it was set on: a browser keys cookies
515
+ // by both, and a clear elsewhere leaves the credential in place.
516
+ const { path, domain } = rememberMeCookieOptions(strategy);
470
517
  this.#ctx.response.clearCookie?.call(
471
518
  this.#ctx.response,
472
519
  strategy.rememberMeCookieName,
520
+ { path, domain },
473
521
  );
474
522
  }
475
523
 
524
+ /**
525
+ * Record that this session completed an MFA step-up, once
526
+ * `MfaManager.verify()` succeeded — what `@RequireMfa()` requires (session
527
+ * guards; a JWT carries it as `issueFor(user, guard, { mfa: true })`).
528
+ */
529
+ markMfaVerified(): void {
530
+ const strategy = strategyOrUndefined(this.#auth, this.#name);
531
+ const mark = strategy
532
+ ? Reflect.get(strategy, "markMfaVerified")
533
+ : undefined;
534
+ if (typeof mark !== "function") {
535
+ throw new WardenError(
536
+ "INVALID_CONFIG",
537
+ `Guard '${this.#name}' keeps no session to record an MFA step-up in.`,
538
+ {
539
+ hint: "Sign a token with the step-up instead: auth.issueFor(user, guard, { mfa: true }).",
540
+ },
541
+ );
542
+ }
543
+ mark.call(strategy, this.#requireSession());
544
+ const user = this.user;
545
+ if (user) user.mfa = true;
546
+ }
547
+
476
548
  /** Log the current user out of this guard (session guards). */
477
549
  logout(): Promise<void> {
478
550
  return this.#auth.logout(this.#requireSession(), this.#name, this.#state);
@@ -654,11 +726,18 @@ export class Authenticator {
654
726
  { status: 500 },
655
727
  );
656
728
  }
729
+ // A Basic guard among those tried: the 401 must carry its challenge,
730
+ // or the browser never asks for credentials (AdonisJS basic_auth does
731
+ // the same).
732
+ const challenge = names
733
+ .map((name) => basicChallengeOf(strategyOrUndefined(this.#auth, name)))
734
+ .find((value) => value !== undefined);
657
735
  const failure = new E_UNAUTHORIZED_ACCESS(
658
736
  result?.error ?? "Unauthorized access",
659
737
  {
660
738
  guardDriverName: guardName,
661
739
  redirectTo: hasSessionStrategy ? options?.loginRoute : undefined,
740
+ challenge,
662
741
  },
663
742
  );
664
743
  this.#auth.emitAuthEvent(
@@ -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. */