@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.
- package/README.md +5 -3
- package/dist/AttemptStore.d.ts +64 -0
- package/dist/AttemptStore.d.ts.map +1 -0
- package/dist/AttemptStore.js +117 -0
- package/dist/AttemptStore.js.map +1 -0
- package/dist/AuthManager.d.ts +5 -3
- package/dist/AuthManager.d.ts.map +1 -1
- package/dist/AuthManager.js +5 -4
- package/dist/AuthManager.js.map +1 -1
- package/dist/AuthRateLimiter.d.ts +44 -10
- package/dist/AuthRateLimiter.d.ts.map +1 -1
- package/dist/AuthRateLimiter.js +58 -73
- package/dist/AuthRateLimiter.js.map +1 -1
- package/dist/Authenticator.d.ts +8 -11
- package/dist/Authenticator.d.ts.map +1 -1
- package/dist/Authenticator.js +72 -9
- package/dist/Authenticator.js.map +1 -1
- package/dist/RememberMeToken.d.ts +15 -4
- package/dist/RememberMeToken.d.ts.map +1 -1
- package/dist/RememberMeToken.js +20 -7
- package/dist/RememberMeToken.js.map +1 -1
- package/dist/bouncer/evaluate.d.ts +0 -8
- package/dist/bouncer/evaluate.d.ts.map +1 -1
- package/dist/bouncer/evaluate.js +1 -1
- package/dist/bouncer/evaluate.js.map +1 -1
- package/dist/duration.d.ts.map +1 -1
- package/dist/duration.js +6 -0
- package/dist/duration.js.map +1 -1
- package/dist/errors.d.ts +6 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +6 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +8 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/mfa/BackupCodesProvider.d.ts +8 -1
- package/dist/mfa/BackupCodesProvider.d.ts.map +1 -1
- package/dist/mfa/BackupCodesProvider.js +5 -7
- package/dist/mfa/BackupCodesProvider.js.map +1 -1
- package/dist/mfa/MfaManager.d.ts +18 -2
- package/dist/mfa/MfaManager.d.ts.map +1 -1
- package/dist/mfa/MfaManager.js +38 -35
- package/dist/mfa/MfaManager.js.map +1 -1
- package/dist/mfa/TotpProvider.d.ts +30 -6
- package/dist/mfa/TotpProvider.d.ts.map +1 -1
- package/dist/mfa/TotpProvider.js +48 -19
- package/dist/mfa/TotpProvider.js.map +1 -1
- package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
- package/dist/mfa/WebauthnProvider.js +4 -1
- package/dist/mfa/WebauthnProvider.js.map +1 -1
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +3 -0
- package/dist/middleware.js.map +1 -1
- package/dist/native/generated.d.ts +0 -5
- package/dist/native/generated.d.ts.map +1 -1
- package/dist/native.d.ts +0 -2
- package/dist/native.d.ts.map +1 -1
- package/dist/native.js +0 -4
- package/dist/native.js.map +1 -1
- package/dist/strategies/JwtStrategy.d.ts +11 -1
- package/dist/strategies/JwtStrategy.d.ts.map +1 -1
- package/dist/strategies/JwtStrategy.js +9 -2
- package/dist/strategies/JwtStrategy.js.map +1 -1
- package/dist/strategies/SessionStrategy.d.ts +70 -1
- package/dist/strategies/SessionStrategy.d.ts.map +1 -1
- package/dist/strategies/SessionStrategy.js +100 -4
- package/dist/strategies/SessionStrategy.js.map +1 -1
- package/dist/vendor/nodeEnv.d.ts +5 -0
- package/dist/vendor/nodeEnv.d.ts.map +1 -0
- package/dist/vendor/nodeEnv.js +38 -0
- package/dist/vendor/nodeEnv.js.map +1 -0
- package/index.darwin-arm64.node +0 -0
- package/index.darwin-x64.node +0 -0
- package/index.linux-arm64-gnu.node +0 -0
- package/index.linux-x64-gnu.node +0 -0
- package/index.win32-x64-msvc.node +0 -0
- package/package.json +2 -2
- package/src/AttemptStore.ts +158 -0
- package/src/AuthManager.ts +9 -7
- package/src/AuthRateLimiter.ts +85 -80
- package/src/Authenticator.ts +92 -13
- package/src/RememberMeToken.ts +36 -8
- package/src/bouncer/evaluate.ts +1 -1
- package/src/duration.ts +8 -0
- package/src/errors.ts +11 -1
- package/src/index.ts +24 -3
- package/src/mfa/BackupCodesProvider.ts +13 -14
- package/src/mfa/MfaManager.ts +58 -43
- package/src/mfa/TotpProvider.ts +90 -22
- package/src/mfa/WebauthnProvider.ts +4 -1
- package/src/middleware.ts +9 -0
- package/src/native/generated.ts +0 -14
- package/src/native.ts +0 -5
- package/src/strategies/JwtStrategy.ts +20 -2
- package/src/strategies/SessionStrategy.ts +172 -4
- package/src/vendor/nodeEnv.ts +37 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Generated from scripts/vendor/nodeEnv.ts — do not edit.
|
|
2
|
+
//
|
|
3
|
+
// This package is published and built from its own repository, so the file
|
|
4
|
+
// has to exist here rather than be imported. `pnpm vendor:sync` rewrites it,
|
|
5
|
+
// and `pnpm vendor:check` fails if this copy has drifted from the original.
|
|
6
|
+
/**
|
|
7
|
+
* `NODE_ENV`, read the way every runtime actually spells it.
|
|
8
|
+
*
|
|
9
|
+
* `NODE_ENV=prod` is ordinary in a Dockerfile or a platform dashboard, and a
|
|
10
|
+
* bare `=== "production"` answers "not production" for it. What that costs
|
|
11
|
+
* differs per package, so the consequence is stated where the decision is
|
|
12
|
+
* taken, not here.
|
|
13
|
+
*
|
|
14
|
+
* The tables mirror the framework's (`@c9up/ream`, src/env/nodeEnv.ts), which
|
|
15
|
+
* is the origin rather than a peer: it formats to different rules and exposes
|
|
16
|
+
* `currentNodeEnv()` instead of `inProduction()`.
|
|
17
|
+
*/
|
|
18
|
+
const DEV_ENVS = ["dev", "develop", "development"];
|
|
19
|
+
const PROD_ENVS = ["prod", "production"];
|
|
20
|
+
const TEST_ENVS = ["test", "testing"];
|
|
21
|
+
/** The canonical name for whatever `NODE_ENV` holds. */
|
|
22
|
+
export function normalizeNodeEnv(value) {
|
|
23
|
+
if (!value || typeof value !== "string")
|
|
24
|
+
return "unknown";
|
|
25
|
+
const env = value.toLowerCase();
|
|
26
|
+
if (DEV_ENVS.includes(env))
|
|
27
|
+
return "development";
|
|
28
|
+
if (PROD_ENVS.includes(env))
|
|
29
|
+
return "production";
|
|
30
|
+
if (TEST_ENVS.includes(env))
|
|
31
|
+
return "test";
|
|
32
|
+
return env;
|
|
33
|
+
}
|
|
34
|
+
/** Whether this process is running in production, under any spelling. */
|
|
35
|
+
export function inProduction() {
|
|
36
|
+
return normalizeNodeEnv(process.env.NODE_ENV) === "production";
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=nodeEnv.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nodeEnv.js","sourceRoot":"","sources":["../../src/vendor/nodeEnv.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAC1D,EAAE;AACF,2EAA2E;AAC3E,6EAA6E;AAC7E,4EAA4E;AAE5E;;;;;;;;;;;GAWG;AAEH,MAAM,QAAQ,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC;AACnD,MAAM,SAAS,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AACzC,MAAM,SAAS,GAAG,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAEtC,wDAAwD;AACxD,MAAM,UAAU,gBAAgB,CAAC,KAAyB;IACzD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAC1D,MAAM,GAAG,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;IAChC,IAAI,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,aAAa,CAAC;IACjD,IAAI,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,YAAY,CAAC;IACjD,IAAI,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,MAAM,CAAC;IAC3C,OAAO,GAAG,CAAC;AACZ,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,YAAY;IAC3B,OAAO,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,YAAY,CAAC;AAChE,CAAC"}
|
package/index.darwin-arm64.node
CHANGED
|
Binary file
|
package/index.darwin-x64.node
CHANGED
|
Binary file
|
|
Binary file
|
package/index.linux-x64-gnu.node
CHANGED
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@c9up/warden",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"description": "Warden — Authentication & authorization for the Ream framework",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"@c9up/quasar": "^0.1.0 || ^0.2.0",
|
|
54
|
-
"@c9up/ream": "^0.2.
|
|
54
|
+
"@c9up/ream": "^0.2.28"
|
|
55
55
|
},
|
|
56
56
|
"peerDependenciesMeta": {
|
|
57
57
|
"@c9up/ream": {
|
|
@@ -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
|
+
}
|
package/src/AuthManager.ts
CHANGED
|
@@ -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(
|
|
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
|
/**
|
package/src/AuthRateLimiter.ts
CHANGED
|
@@ -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
|
-
*
|
|
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
|
-
|
|
11
|
-
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
#
|
|
22
|
-
#store:
|
|
23
|
-
#maxStoreSize = 100_000;
|
|
49
|
+
readonly #maxAttempts: number;
|
|
50
|
+
readonly #windowSeconds: number;
|
|
51
|
+
readonly #store: AttemptStore;
|
|
24
52
|
|
|
25
|
-
constructor(config
|
|
26
|
-
this.#maxAttempts = config
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
/**
|
|
33
|
-
|
|
34
|
-
|
|
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
|
-
/**
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
/**
|
|
62
|
-
|
|
63
|
-
const
|
|
64
|
-
|
|
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
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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
|
-
|
|
104
|
-
|
|
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
|
}
|
package/src/Authenticator.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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(
|
|
454
|
-
|
|
455
|
-
|
|
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(
|