@c9up/warden 0.1.17 → 0.1.19
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/dist/AuthManager.d.ts +86 -1
- package/dist/AuthManager.d.ts.map +1 -1
- package/dist/AuthManager.js +113 -10
- package/dist/AuthManager.js.map +1 -1
- package/dist/Authenticator.d.ts +13 -1
- package/dist/Authenticator.d.ts.map +1 -1
- package/dist/Authenticator.js +37 -3
- package/dist/Authenticator.js.map +1 -1
- package/dist/RememberMeToken.d.ts +169 -0
- package/dist/RememberMeToken.d.ts.map +1 -0
- package/dist/RememberMeToken.js +269 -0
- package/dist/RememberMeToken.js.map +1 -0
- package/dist/ResilientBlacklistDriver.d.ts +15 -9
- package/dist/ResilientBlacklistDriver.d.ts.map +1 -1
- package/dist/ResilientBlacklistDriver.js +53 -15
- package/dist/ResilientBlacklistDriver.js.map +1 -1
- package/dist/Secret.d.ts +11 -0
- package/dist/Secret.d.ts.map +1 -0
- package/dist/Secret.js +36 -0
- package/dist/Secret.js.map +1 -0
- package/dist/WardenProvider.d.ts +1 -0
- package/dist/WardenProvider.d.ts.map +1 -1
- package/dist/WardenProvider.js +64 -0
- package/dist/WardenProvider.js.map +1 -1
- package/dist/bouncer/Bouncer.d.ts +46 -1
- package/dist/bouncer/Bouncer.d.ts.map +1 -1
- package/dist/bouncer/Bouncer.js +77 -4
- package/dist/bouncer/Bouncer.js.map +1 -1
- package/dist/bouncer/PolicyAuthorizer.d.ts +9 -1
- package/dist/bouncer/PolicyAuthorizer.d.ts.map +1 -1
- package/dist/bouncer/PolicyAuthorizer.js +17 -1
- package/dist/bouncer/PolicyAuthorizer.js.map +1 -1
- package/dist/bouncer/evaluate.d.ts +14 -2
- package/dist/bouncer/evaluate.d.ts.map +1 -1
- package/dist/bouncer/evaluate.js +16 -5
- package/dist/bouncer/evaluate.js.map +1 -1
- package/dist/bouncer/types.d.ts +4 -2
- package/dist/bouncer/types.d.ts.map +1 -1
- package/dist/config.d.ts +3 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +5 -0
- package/dist/config.js.map +1 -1
- package/dist/firstcontact/drivers/GitHubDriver.d.ts.map +1 -1
- package/dist/firstcontact/drivers/GitHubDriver.js +2 -3
- package/dist/firstcontact/drivers/GitHubDriver.js.map +1 -1
- package/dist/firstcontact/drivers/GoogleDriver.d.ts.map +1 -1
- package/dist/firstcontact/drivers/GoogleDriver.js +2 -3
- package/dist/firstcontact/drivers/GoogleDriver.js.map +1 -1
- package/dist/firstcontact/types.d.ts +10 -0
- package/dist/firstcontact/types.d.ts.map +1 -1
- package/dist/firstcontact/types.js +18 -1
- package/dist/firstcontact/types.js.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/dist/mfa/MfaManager.d.ts.map +1 -1
- package/dist/mfa/MfaManager.js +14 -5
- package/dist/mfa/MfaManager.js.map +1 -1
- package/dist/mfa/TotpProvider.d.ts +34 -1
- package/dist/mfa/TotpProvider.d.ts.map +1 -1
- package/dist/mfa/TotpProvider.js +60 -4
- package/dist/mfa/TotpProvider.js.map +1 -1
- package/dist/mfa/webauthn-codec.d.ts +6 -1
- package/dist/mfa/webauthn-codec.d.ts.map +1 -1
- package/dist/mfa/webauthn-codec.js +50 -6
- package/dist/mfa/webauthn-codec.js.map +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +46 -1
- package/dist/middleware.js.map +1 -1
- package/dist/quasar.d.ts.map +1 -1
- package/dist/quasar.js +6 -14
- package/dist/quasar.js.map +1 -1
- package/dist/sanitize.d.ts +10 -0
- package/dist/sanitize.d.ts.map +1 -0
- package/dist/sanitize.js +15 -0
- package/dist/sanitize.js.map +1 -0
- package/dist/strategies/ApiKeyStrategy.d.ts +10 -1
- package/dist/strategies/ApiKeyStrategy.d.ts.map +1 -1
- package/dist/strategies/ApiKeyStrategy.js +16 -0
- package/dist/strategies/ApiKeyStrategy.js.map +1 -1
- package/dist/strategies/BasicAuthStrategy.d.ts +59 -0
- package/dist/strategies/BasicAuthStrategy.d.ts.map +1 -0
- package/dist/strategies/BasicAuthStrategy.js +97 -0
- package/dist/strategies/BasicAuthStrategy.js.map +1 -0
- package/dist/strategies/JwtStrategy.d.ts +10 -1
- package/dist/strategies/JwtStrategy.d.ts.map +1 -1
- package/dist/strategies/JwtStrategy.js +11 -0
- package/dist/strategies/JwtStrategy.js.map +1 -1
- package/dist/strategies/SessionStrategy.d.ts +84 -2
- package/dist/strategies/SessionStrategy.d.ts.map +1 -1
- package/dist/strategies/SessionStrategy.js +124 -1
- package/dist/strategies/SessionStrategy.js.map +1 -1
- 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 +4 -2
- package/src/AuthManager.ts +163 -7
- package/src/Authenticator.ts +58 -10
- package/src/RememberMeToken.ts +357 -0
- package/src/ResilientBlacklistDriver.ts +58 -18
- package/src/Secret.ts +41 -0
- package/src/WardenProvider.ts +90 -0
- package/src/bouncer/Bouncer.ts +93 -4
- package/src/bouncer/PolicyAuthorizer.ts +20 -1
- package/src/bouncer/evaluate.ts +26 -6
- package/src/bouncer/types.ts +4 -2
- package/src/config.ts +9 -0
- package/src/firstcontact/drivers/GitHubDriver.ts +2 -3
- package/src/firstcontact/drivers/GoogleDriver.ts +2 -3
- package/src/firstcontact/types.ts +24 -0
- package/src/index.ts +30 -2
- package/src/mfa/MfaManager.ts +15 -8
- package/src/mfa/TotpProvider.ts +90 -6
- package/src/mfa/webauthn-codec.ts +48 -6
- package/src/middleware.ts +55 -2
- package/src/quasar.ts +6 -14
- package/src/sanitize.ts +17 -0
- package/src/strategies/ApiKeyStrategy.ts +23 -1
- package/src/strategies/BasicAuthStrategy.ts +127 -0
- package/src/strategies/JwtStrategy.ts +18 -1
- package/src/strategies/SessionStrategy.ts +167 -2
package/src/Authenticator.ts
CHANGED
|
@@ -14,15 +14,15 @@
|
|
|
14
14
|
* `@c9up/ream`.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
type UserPayload,
|
|
17
|
+
import type {
|
|
18
|
+
AuthManager,
|
|
19
|
+
AuthResult,
|
|
20
|
+
AuthStrategy,
|
|
21
|
+
UserPayload,
|
|
23
22
|
} from "./AuthManager.js";
|
|
24
23
|
import { E_UNAUTHORIZED_ACCESS, WardenError } from "./errors.js";
|
|
25
24
|
import type { WardenContext } from "./middleware.js";
|
|
25
|
+
import { sanitizePayload } from "./sanitize.js";
|
|
26
26
|
import type { SessionStore } from "./strategies/SessionStrategy.js";
|
|
27
27
|
|
|
28
28
|
/**
|
|
@@ -308,6 +308,31 @@ export class Authenticator {
|
|
|
308
308
|
}
|
|
309
309
|
}
|
|
310
310
|
|
|
311
|
+
/**
|
|
312
|
+
* Try the given guards in order and report whether one succeeded, without
|
|
313
|
+
* throwing (AdonisJS `checkUsing`).
|
|
314
|
+
*
|
|
315
|
+
* The non-throwing sibling of {@link authenticateUsing}: `check()` is to
|
|
316
|
+
* `authenticate()` what this is to it. A handler that wants to branch on
|
|
317
|
+
* "is anyone signed in through either of these" had to wrap the throwing
|
|
318
|
+
* form in a try/catch itself.
|
|
319
|
+
*/
|
|
320
|
+
async checkUsing(
|
|
321
|
+
guards?: string[],
|
|
322
|
+
options?: { loginRoute?: string },
|
|
323
|
+
): Promise<boolean> {
|
|
324
|
+
try {
|
|
325
|
+
await this.authenticateUsing(guards, options);
|
|
326
|
+
return this.isAuthenticated;
|
|
327
|
+
} catch (err) {
|
|
328
|
+
// A credential rejection is an answer, not a failure. Anything else
|
|
329
|
+
// — a crashed strategy, a config error — is still a real problem and
|
|
330
|
+
// must not be reported as "not signed in".
|
|
331
|
+
if (err instanceof E_UNAUTHORIZED_ACCESS) return false;
|
|
332
|
+
throw err;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
311
336
|
/**
|
|
312
337
|
* Authenticate by trying the given guards in order (default: the default
|
|
313
338
|
* guard). Sets the user on the first success; throws `E_UNAUTHORIZED_ACCESS`
|
|
@@ -321,6 +346,14 @@ export class Authenticator {
|
|
|
321
346
|
this.#attempted = true;
|
|
322
347
|
const names =
|
|
323
348
|
guards && guards.length > 0 ? guards : [this.#auth.defaultStrategyName];
|
|
349
|
+
const guardName = names[0] ?? this.#auth.defaultStrategyName;
|
|
350
|
+
// Namespaced by the guard's driver, as AdonisJS does: `session_auth:*`,
|
|
351
|
+
// `access_tokens_auth:*`, `basic_auth:*`. An app auditing session logins
|
|
352
|
+
// must not be told about bearer-token traffic under the same name.
|
|
353
|
+
this.#auth.emitAuthEvent(
|
|
354
|
+
`${this.#auth.eventPrefixFor(guardName)}:authentication_attempted`,
|
|
355
|
+
{ guardName },
|
|
356
|
+
);
|
|
324
357
|
const creds = extractCredentials(this.#ctx, this.#auth);
|
|
325
358
|
const hasSessionStrategy = names.includes("session");
|
|
326
359
|
const { result, viaGuard, attemptCount, crashCount } =
|
|
@@ -332,6 +365,13 @@ export class Authenticator {
|
|
|
332
365
|
if (result?.authenticated && result.user) {
|
|
333
366
|
this.#user = result.user;
|
|
334
367
|
this.#viaGuard = viaGuard;
|
|
368
|
+
// The guard that actually answered names the event, not the one asked
|
|
369
|
+
// for first.
|
|
370
|
+
const winner = viaGuard ?? guardName;
|
|
371
|
+
this.#auth.emitAuthEvent(
|
|
372
|
+
`${this.#auth.eventPrefixFor(winner)}:authentication_succeeded`,
|
|
373
|
+
{ guardName: winner, user: result.user, sessionId: undefined },
|
|
374
|
+
);
|
|
335
375
|
return;
|
|
336
376
|
}
|
|
337
377
|
// Every attempted guard crashed → a server-side incident, not a
|
|
@@ -343,10 +383,18 @@ export class Authenticator {
|
|
|
343
383
|
{ status: 500 },
|
|
344
384
|
);
|
|
345
385
|
}
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
386
|
+
const failure = new E_UNAUTHORIZED_ACCESS(
|
|
387
|
+
result?.error ?? "Unauthorized access",
|
|
388
|
+
{
|
|
389
|
+
guardDriverName: guardName,
|
|
390
|
+
redirectTo: hasSessionStrategy ? options?.loginRoute : undefined,
|
|
391
|
+
},
|
|
392
|
+
);
|
|
393
|
+
this.#auth.emitAuthEvent(
|
|
394
|
+
`${this.#auth.eventPrefixFor(guardName)}:authentication_failed`,
|
|
395
|
+
{ guardName, error: failure },
|
|
396
|
+
);
|
|
397
|
+
throw failure;
|
|
350
398
|
}
|
|
351
399
|
|
|
352
400
|
/** Return the authenticated user or throw `E_UNAUTHORIZED_ACCESS`. */
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remember-me tokens — "keep me signed in" that survives the session cookie.
|
|
3
|
+
*
|
|
4
|
+
* Modelled on `@adonisjs/auth`'s `RememberMeToken`
|
|
5
|
+
* (modules/session_guard/remember_me_token.ts), because an app moving over
|
|
6
|
+
* carries the same table and the same cookie:
|
|
7
|
+
*
|
|
8
|
+
* value = base64url(identifier) + "." + base64url(secret)
|
|
9
|
+
* stored = sha256(secret), never the secret itself
|
|
10
|
+
*
|
|
11
|
+
* The three properties that make this safe, all taken from upstream:
|
|
12
|
+
*
|
|
13
|
+
* 1. **Only a hash is stored.** A dump of the tokens table does not let anyone
|
|
14
|
+
* log in — the secret exists solely in the user's cookie.
|
|
15
|
+
* 2. **The comparison is constant-time.** Comparing hashes with `===` leaks
|
|
16
|
+
* how many leading bytes matched, which is enough to forge one byte at a
|
|
17
|
+
* time.
|
|
18
|
+
* 3. **A used token is recycled.** Authenticating rotates the secret and
|
|
19
|
+
* invalidates the old one, so a stolen cookie stops working the moment the
|
|
20
|
+
* legitimate user comes back.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
24
|
+
import { Secret } from "./Secret.js";
|
|
25
|
+
|
|
26
|
+
/** Bytes of entropy in a token secret. Adonis defaults to 40. */
|
|
27
|
+
export const DEFAULT_SECRET_LENGTH = 40;
|
|
28
|
+
|
|
29
|
+
/** A token as persisted. The secret is NOT here — only its hash. */
|
|
30
|
+
export interface StoredRememberMeToken {
|
|
31
|
+
/** Unique id of the row; the public half of the token value. */
|
|
32
|
+
identifier: string;
|
|
33
|
+
/** Whose token this is. */
|
|
34
|
+
tokenableId: string | number;
|
|
35
|
+
/** `sha256(secret)`, hex. */
|
|
36
|
+
hash: string;
|
|
37
|
+
createdAt: number;
|
|
38
|
+
updatedAt: number;
|
|
39
|
+
expiresAt: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** What a store must implement. Structural: warden owns no database. */
|
|
43
|
+
export interface RememberMeTokenDriver {
|
|
44
|
+
create(token: StoredRememberMeToken): Promise<void>;
|
|
45
|
+
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>;
|
|
48
|
+
delete(identifier: string): Promise<void>;
|
|
49
|
+
deleteAllForUser(userId: string | number): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Base64url without padding — the encoding Adonis uses for the token halves. */
|
|
53
|
+
function base64UrlEncode(value: string): string {
|
|
54
|
+
return Buffer.from(value, "utf8").toString("base64url");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function base64UrlDecode(value: string): string | null {
|
|
58
|
+
try {
|
|
59
|
+
const decoded = Buffer.from(value, "base64url").toString("utf8");
|
|
60
|
+
// A non-base64url character decodes to something that does not round-trip;
|
|
61
|
+
// reject rather than authenticate against a mangled identifier.
|
|
62
|
+
return Buffer.from(decoded, "utf8").toString("base64url") === value
|
|
63
|
+
? decoded
|
|
64
|
+
: null;
|
|
65
|
+
} catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** `sha256(secret)` as hex — what gets stored. */
|
|
71
|
+
export function hashSecret(secret: string): string {
|
|
72
|
+
return createHash("sha256").update(secret).digest("hex");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Compare two hex hashes without leaking where they diverge. Length is checked
|
|
77
|
+
* first because `timingSafeEqual` throws on a mismatch — and the length of a
|
|
78
|
+
* sha256 hex digest is public anyway.
|
|
79
|
+
*/
|
|
80
|
+
export function safeCompareHashes(a: string, b: string): boolean {
|
|
81
|
+
const left = Buffer.from(a, "utf8");
|
|
82
|
+
const right = Buffer.from(b, "utf8");
|
|
83
|
+
if (left.length !== right.length) return false;
|
|
84
|
+
return timingSafeEqual(left, right);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Split a cookie value into its identifier and secret, or `null` if malformed. */
|
|
88
|
+
export function decodeTokenValue(
|
|
89
|
+
value: unknown,
|
|
90
|
+
): { identifier: string; secret: string } | null {
|
|
91
|
+
if (typeof value !== "string" || value.length === 0) return null;
|
|
92
|
+
const [encodedIdentifier, ...rest] = value.split(".");
|
|
93
|
+
if (!encodedIdentifier || rest.length === 0) return null;
|
|
94
|
+
const identifier = base64UrlDecode(encodedIdentifier);
|
|
95
|
+
const secret = base64UrlDecode(rest.join("."));
|
|
96
|
+
if (identifier === null || secret === null) return null;
|
|
97
|
+
if (identifier === "" || secret === "") return null;
|
|
98
|
+
return { identifier, secret };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Build the cookie value from its two halves. */
|
|
102
|
+
export function encodeTokenValue(identifier: string, secret: string): string {
|
|
103
|
+
return `${base64UrlEncode(identifier)}.${base64UrlEncode(secret)}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A freshly minted token: what to store, and what to hand the browser. */
|
|
107
|
+
export interface MintedRememberMeToken {
|
|
108
|
+
stored: StoredRememberMeToken;
|
|
109
|
+
/** Goes in the cookie. Never persisted. */
|
|
110
|
+
value: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Mint a token for `userId`, valid for `ageSeconds`.
|
|
115
|
+
*
|
|
116
|
+
* `identifier` is random too, not a counter: a guessable identifier would let
|
|
117
|
+
* an attacker enumerate rows and target a specific user's token.
|
|
118
|
+
*/
|
|
119
|
+
export function mintRememberMeToken(
|
|
120
|
+
userId: string | number,
|
|
121
|
+
ageSeconds: number,
|
|
122
|
+
secretLength = DEFAULT_SECRET_LENGTH,
|
|
123
|
+
): MintedRememberMeToken {
|
|
124
|
+
const identifier = randomBytes(16).toString("hex");
|
|
125
|
+
const secret = randomBytes(secretLength).toString("base64url");
|
|
126
|
+
const now = Date.now();
|
|
127
|
+
return {
|
|
128
|
+
stored: {
|
|
129
|
+
identifier,
|
|
130
|
+
tokenableId: userId,
|
|
131
|
+
hash: hashSecret(secret),
|
|
132
|
+
createdAt: now,
|
|
133
|
+
updatedAt: now,
|
|
134
|
+
expiresAt: now + ageSeconds * 1000,
|
|
135
|
+
},
|
|
136
|
+
value: encodeTokenValue(identifier, secret),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Verify a cookie value against the store, and RECYCLE the token on success:
|
|
142
|
+
* the row keeps its identifier but gets a fresh secret and expiry, and the
|
|
143
|
+
* caller must send the returned value back as the new cookie.
|
|
144
|
+
*
|
|
145
|
+
* Recycling is what limits the damage of a stolen cookie — the thief's copy
|
|
146
|
+
* dies as soon as the real user authenticates again.
|
|
147
|
+
*
|
|
148
|
+
* Returns `null` for anything wrong: malformed value, unknown identifier,
|
|
149
|
+
* expired row, or a secret that does not match. The caller cannot tell these
|
|
150
|
+
* apart, which is deliberate — a distinguishable "unknown identifier" tells an
|
|
151
|
+
* attacker which identifiers exist.
|
|
152
|
+
*/
|
|
153
|
+
export async function verifyAndRecycleRememberMeToken(
|
|
154
|
+
driver: RememberMeTokenDriver,
|
|
155
|
+
cookieValue: unknown,
|
|
156
|
+
ageSeconds: number,
|
|
157
|
+
secretLength = DEFAULT_SECRET_LENGTH,
|
|
158
|
+
): Promise<{ userId: string | number; value: string } | null> {
|
|
159
|
+
const decoded = decodeTokenValue(cookieValue);
|
|
160
|
+
if (!decoded) return null;
|
|
161
|
+
|
|
162
|
+
const stored = await driver.find(decoded.identifier);
|
|
163
|
+
if (!stored) return null;
|
|
164
|
+
|
|
165
|
+
if (stored.expiresAt <= Date.now()) {
|
|
166
|
+
// Expired rows are removed on sight rather than left to a cleanup job.
|
|
167
|
+
await driver.delete(stored.identifier);
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (!safeCompareHashes(stored.hash, hashSecret(decoded.secret))) {
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const secret = randomBytes(secretLength).toString("base64url");
|
|
176
|
+
const expiresAt = Date.now() + ageSeconds * 1000;
|
|
177
|
+
await driver.update(stored.identifier, hashSecret(secret), expiresAt);
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
userId: stored.tokenableId,
|
|
181
|
+
value: encodeTokenValue(stored.identifier, secret),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** In-memory store — for tests and single-process apps. Not for a cluster. */
|
|
186
|
+
export class MemoryRememberMeTokenDriver implements RememberMeTokenDriver {
|
|
187
|
+
readonly #rows = new Map<string, StoredRememberMeToken>();
|
|
188
|
+
|
|
189
|
+
async create(token: StoredRememberMeToken): Promise<void> {
|
|
190
|
+
this.#rows.set(token.identifier, { ...token });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async find(identifier: string): Promise<StoredRememberMeToken | null> {
|
|
194
|
+
const row = this.#rows.get(identifier);
|
|
195
|
+
return row ? { ...row } : null;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async update(
|
|
199
|
+
identifier: string,
|
|
200
|
+
hash: string,
|
|
201
|
+
expiresAt: number,
|
|
202
|
+
): Promise<void> {
|
|
203
|
+
const row = this.#rows.get(identifier);
|
|
204
|
+
if (!row) return;
|
|
205
|
+
this.#rows.set(identifier, {
|
|
206
|
+
...row,
|
|
207
|
+
hash,
|
|
208
|
+
expiresAt,
|
|
209
|
+
updatedAt: Date.now(),
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async delete(identifier: string): Promise<void> {
|
|
214
|
+
this.#rows.delete(identifier);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async deleteAllForUser(userId: string | number): Promise<void> {
|
|
218
|
+
for (const [identifier, row] of this.#rows) {
|
|
219
|
+
if (String(row.tokenableId) === String(userId)) {
|
|
220
|
+
this.#rows.delete(identifier);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* A remember-me token as an object, matching `@adonisjs/auth`'s
|
|
228
|
+
* `RememberMeToken` (modules/session_guard/remember_me_token.ts).
|
|
229
|
+
*
|
|
230
|
+
* The functions above are what warden's own guard uses and stay the primary
|
|
231
|
+
* API. This class exists because an app moving over calls
|
|
232
|
+
* `RememberMeToken.decode(...)` / `token.verify(secret)` directly — upstream
|
|
233
|
+
* exports it — and finding nothing under that name is a migration stopping at
|
|
234
|
+
* an import line. Both sit on the same encoding and the same hashing, so they
|
|
235
|
+
* cannot disagree about what a token is.
|
|
236
|
+
*
|
|
237
|
+
* Secrets come back wrapped in {@link Secret} so one cannot end up in a log by
|
|
238
|
+
* being interpolated into a string, which is what upstream does too.
|
|
239
|
+
*/
|
|
240
|
+
export class RememberMeToken {
|
|
241
|
+
/**
|
|
242
|
+
* Split a public token value into its identifier and secret. Returns `null`
|
|
243
|
+
* for anything malformed rather than throwing — a bad cookie is an ordinary
|
|
244
|
+
* event, not an exception.
|
|
245
|
+
*/
|
|
246
|
+
static decode(
|
|
247
|
+
value: string,
|
|
248
|
+
): { identifier: string; secret: Secret<string> } | null {
|
|
249
|
+
const decoded = decodeTokenValue(value);
|
|
250
|
+
if (!decoded) return null;
|
|
251
|
+
return {
|
|
252
|
+
identifier: decoded.identifier,
|
|
253
|
+
secret: new Secret(decoded.secret),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** A fresh secret and the hash to store for it. */
|
|
258
|
+
static seed(size: number = DEFAULT_SECRET_LENGTH): {
|
|
259
|
+
secret: Secret<string>;
|
|
260
|
+
hash: string;
|
|
261
|
+
} {
|
|
262
|
+
const secret = randomBytes(size).toString("base64url");
|
|
263
|
+
return { secret: new Secret(secret), hash: hashSecret(secret) };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Everything the persistence layer needs for a new token, without deciding
|
|
268
|
+
* how it is stored (upstream `createTransientToken`).
|
|
269
|
+
*
|
|
270
|
+
* `expiresIn` is in SECONDS, as everywhere else in this module. AdonisJS
|
|
271
|
+
* also accepts a duration string there; warden takes the number, so the
|
|
272
|
+
* unit is never ambiguous at a call site.
|
|
273
|
+
*/
|
|
274
|
+
static createTransientToken(
|
|
275
|
+
userId: string | number,
|
|
276
|
+
size: number,
|
|
277
|
+
expiresIn: number,
|
|
278
|
+
): {
|
|
279
|
+
secret: Secret<string>;
|
|
280
|
+
hash: string;
|
|
281
|
+
userId: string | number;
|
|
282
|
+
expiresAt: Date;
|
|
283
|
+
} {
|
|
284
|
+
const { secret, hash } = RememberMeToken.seed(size);
|
|
285
|
+
return {
|
|
286
|
+
secret,
|
|
287
|
+
hash,
|
|
288
|
+
userId,
|
|
289
|
+
expiresAt: new Date(Date.now() + expiresIn * 1000),
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
identifier: string;
|
|
294
|
+
tokenableId: string | number;
|
|
295
|
+
hash: string;
|
|
296
|
+
createdAt: Date;
|
|
297
|
+
updatedAt: Date;
|
|
298
|
+
expiresAt: Date;
|
|
299
|
+
/** The public `identifier.secret` value — only on a token just minted. */
|
|
300
|
+
value?: Secret<string>;
|
|
301
|
+
|
|
302
|
+
constructor(attributes: {
|
|
303
|
+
identifier: string;
|
|
304
|
+
tokenableId: string | number;
|
|
305
|
+
hash: string;
|
|
306
|
+
createdAt: Date;
|
|
307
|
+
updatedAt: Date;
|
|
308
|
+
expiresAt: Date;
|
|
309
|
+
secret?: Secret<string>;
|
|
310
|
+
}) {
|
|
311
|
+
this.identifier = attributes.identifier;
|
|
312
|
+
this.tokenableId = attributes.tokenableId;
|
|
313
|
+
this.hash = attributes.hash;
|
|
314
|
+
this.createdAt = attributes.createdAt;
|
|
315
|
+
this.updatedAt = attributes.updatedAt;
|
|
316
|
+
this.expiresAt = attributes.expiresAt;
|
|
317
|
+
if (attributes.secret) {
|
|
318
|
+
this.value = new Secret(
|
|
319
|
+
encodeTokenValue(attributes.identifier, attributes.secret.release()),
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Build one from a stored row, whose timestamps are epoch milliseconds. */
|
|
325
|
+
static fromStored(stored: StoredRememberMeToken): RememberMeToken {
|
|
326
|
+
return new RememberMeToken({
|
|
327
|
+
identifier: stored.identifier,
|
|
328
|
+
tokenableId: stored.tokenableId,
|
|
329
|
+
hash: stored.hash,
|
|
330
|
+
createdAt: new Date(stored.createdAt),
|
|
331
|
+
updatedAt: new Date(stored.updatedAt),
|
|
332
|
+
expiresAt: new Date(stored.expiresAt),
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The row to persist, in the shape {@link RememberMeTokenDriver} takes. */
|
|
337
|
+
toStored(): StoredRememberMeToken {
|
|
338
|
+
return {
|
|
339
|
+
identifier: this.identifier,
|
|
340
|
+
tokenableId: this.tokenableId,
|
|
341
|
+
hash: this.hash,
|
|
342
|
+
createdAt: this.createdAt.getTime(),
|
|
343
|
+
updatedAt: this.updatedAt.getTime(),
|
|
344
|
+
expiresAt: this.expiresAt.getTime(),
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Whether the token is past its expiry. */
|
|
349
|
+
isExpired(): boolean {
|
|
350
|
+
return this.expiresAt.getTime() <= Date.now();
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** Constant-time check of a presented secret against the stored hash. */
|
|
354
|
+
verify(secret: Secret<string>): boolean {
|
|
355
|
+
return safeCompareHashes(this.hash, hashSecret(secret.release()));
|
|
356
|
+
}
|
|
357
|
+
}
|
|
@@ -4,17 +4,23 @@
|
|
|
4
4
|
* takes the whole app down.
|
|
5
5
|
*
|
|
6
6
|
* Policy (fail-open on reads):
|
|
7
|
-
* - `add()` —
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
7
|
+
* - `add()` — records the revocation in BOTH, always. The fallback is this
|
|
8
|
+
* instance's own record of what it has revoked, not a log of its
|
|
9
|
+
* outages: writing only on failure meant a token revoked while
|
|
10
|
+
* the primary was HEALTHY was absent from the fallback, so the
|
|
11
|
+
* first check during a later outage let that logged-out token
|
|
12
|
+
* through. A primary failure still does not fail the logout.
|
|
13
|
+
* - `has()` — asks the fallback FIRST: what this instance revoked is known
|
|
14
|
+
* locally and needs no round trip. Otherwise it asks the
|
|
15
|
+
* primary, and if that throws, allows the token through
|
|
16
|
+
* (fail-open). Access tokens are short-lived, so the window a
|
|
17
|
+
* revocation missed by BOTH survives is bounded by the token TTL
|
|
18
|
+
* — the blacklist is defense-in-depth above expiry, not the
|
|
14
19
|
* primary boundary.
|
|
15
20
|
*
|
|
16
|
-
* Every degradation invokes `onDegrade
|
|
17
|
-
* outage
|
|
21
|
+
* Every degradation invokes `onDegrade`. The default reports the first failure
|
|
22
|
+
* per operation and then a periodic count: an outage that logs on every request
|
|
23
|
+
* buries itself, and the reader stops seeing what the flood is about.
|
|
18
24
|
*/
|
|
19
25
|
|
|
20
26
|
import {
|
|
@@ -32,11 +38,36 @@ export interface ResilientBlacklistConfig {
|
|
|
32
38
|
onDegrade?: (event: BlacklistDegradeEvent) => void;
|
|
33
39
|
}
|
|
34
40
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
41
|
+
/** How long a repeat of the same failing operation stays folded into a count. */
|
|
42
|
+
const DEGRADE_LOG_WINDOW_MS = 60_000;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Report the first failure of each operation, then one line per window with
|
|
46
|
+
* how many were suppressed.
|
|
47
|
+
*
|
|
48
|
+
* Keyed by operation — a fixed, three-value set — never by the error text,
|
|
49
|
+
* which an attacker could influence and which would make the key set unbounded.
|
|
50
|
+
*/
|
|
51
|
+
function makeDefaultOnDegrade(): (event: BlacklistDegradeEvent) => void {
|
|
52
|
+
const windows = new Map<string, { until: number; suppressed: number }>();
|
|
53
|
+
return ({ op, error }: BlacklistDegradeEvent): void => {
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
const open = windows.get(op);
|
|
56
|
+
if (open === undefined || open.until <= now) {
|
|
57
|
+
if (open !== undefined && open.suppressed > 0) {
|
|
58
|
+
console.warn(
|
|
59
|
+
`[warden] blacklist primary failed on ${op} ${open.suppressed} more time(s) in the last minute.`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
windows.set(op, { until: now + DEGRADE_LOG_WINDOW_MS, suppressed: 0 });
|
|
63
|
+
console.warn(
|
|
64
|
+
`[warden] blacklist primary failed on ${op}; using in-memory fallback:`,
|
|
65
|
+
error,
|
|
66
|
+
);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
open.suppressed++;
|
|
70
|
+
};
|
|
40
71
|
}
|
|
41
72
|
|
|
42
73
|
export class ResilientBlacklistDriver implements BlacklistDriver {
|
|
@@ -51,25 +82,34 @@ export class ResilientBlacklistDriver implements BlacklistDriver {
|
|
|
51
82
|
) {
|
|
52
83
|
this.#primary = primary;
|
|
53
84
|
this.#fallback = fallback;
|
|
54
|
-
this.#onDegrade = config.onDegrade ??
|
|
85
|
+
this.#onDegrade = config.onDegrade ?? makeDefaultOnDegrade();
|
|
55
86
|
}
|
|
56
87
|
|
|
57
88
|
async add(jti: string, expiresAt: number): Promise<void> {
|
|
89
|
+
// The fallback first, and unconditionally: it is what this instance
|
|
90
|
+
// knows it revoked. Recording only on failure left every revocation made
|
|
91
|
+
// while the primary was healthy invisible to the fallback — and those are
|
|
92
|
+
// most of them.
|
|
93
|
+
await this.#fallback.add(jti, expiresAt);
|
|
58
94
|
try {
|
|
59
95
|
await this.#primary.add(jti, expiresAt);
|
|
60
96
|
} catch (error) {
|
|
97
|
+
// The revocation is already durable enough for this instance, so a
|
|
98
|
+
// primary failure must not fail the logout.
|
|
61
99
|
this.#onDegrade({ op: "add", error });
|
|
62
|
-
await this.#fallback.add(jti, expiresAt);
|
|
63
100
|
}
|
|
64
101
|
}
|
|
65
102
|
|
|
66
103
|
async has(jti: string): Promise<boolean> {
|
|
104
|
+
// What this instance revoked is known locally — no round trip needed, and
|
|
105
|
+
// it stays correct through an outage that starts a moment later.
|
|
106
|
+
if (await this.#fallback.has(jti)) return true;
|
|
67
107
|
try {
|
|
68
108
|
return await this.#primary.has(jti);
|
|
69
109
|
} catch (error) {
|
|
70
110
|
this.#onDegrade({ op: "has", error });
|
|
71
|
-
// Fail-open
|
|
72
|
-
return
|
|
111
|
+
// Fail-open on what neither knows: access tokens are short-lived.
|
|
112
|
+
return false;
|
|
73
113
|
}
|
|
74
114
|
}
|
|
75
115
|
|
package/src/Secret.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wraps a sensitive value so it never leaks through a log, `JSON.stringify`, or
|
|
3
|
+
* `util.inspect`. Read it back deliberately with {@link Secret.release}.
|
|
4
|
+
*
|
|
5
|
+
* AdonisJS takes this from `@adonisjs/core/helpers`, and its `RememberMeToken`
|
|
6
|
+
* hands secrets out wrapped in one. Warden carries its own copy rather than
|
|
7
|
+
* importing `@c9up/ream`: it has no runtime dependencies and ships a standalone
|
|
8
|
+
* entry point, so reaching for a peer here would break the framework-free mode.
|
|
9
|
+
* Same reason every native package carries its own platform map.
|
|
10
|
+
*/
|
|
11
|
+
const REDACTED = "[redacted]";
|
|
12
|
+
|
|
13
|
+
export class Secret<T> {
|
|
14
|
+
readonly #value: T;
|
|
15
|
+
readonly #keyword: string;
|
|
16
|
+
|
|
17
|
+
constructor(value: T, redactedKeyword: string = REDACTED) {
|
|
18
|
+
this.#value = value;
|
|
19
|
+
this.#keyword = redactedKeyword;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Redacted placeholder, so `JSON.stringify` never emits the secret. */
|
|
23
|
+
toJSON(): string {
|
|
24
|
+
return this.#keyword;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Redacted placeholder for string coercion and template literals. */
|
|
28
|
+
toString(): string {
|
|
29
|
+
return this.#keyword;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Redacted placeholder for `console.log` / `util.inspect`. */
|
|
33
|
+
[Symbol.for("nodejs.util.inspect.custom")](): string {
|
|
34
|
+
return this.#keyword;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Release the underlying value — the one deliberate way to read it. */
|
|
38
|
+
release(): T {
|
|
39
|
+
return this.#value;
|
|
40
|
+
}
|
|
41
|
+
}
|