@c9up/warden 0.2.5 → 0.2.7
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 +74 -5
- package/dist/AccessToken.d.ts +257 -0
- package/dist/AccessToken.d.ts.map +1 -0
- package/dist/AccessToken.js +370 -0
- package/dist/AccessToken.js.map +1 -0
- package/dist/AttemptStore.d.ts +16 -2
- package/dist/AttemptStore.d.ts.map +1 -1
- package/dist/AttemptStore.js +38 -12
- package/dist/AttemptStore.js.map +1 -1
- package/dist/AuthManager.d.ts +44 -8
- package/dist/AuthManager.d.ts.map +1 -1
- package/dist/AuthManager.js +42 -11
- package/dist/AuthManager.js.map +1 -1
- package/dist/AuthRateLimiter.d.ts +16 -3
- package/dist/AuthRateLimiter.d.ts.map +1 -1
- package/dist/AuthRateLimiter.js +25 -6
- package/dist/AuthRateLimiter.js.map +1 -1
- package/dist/Authenticator.d.ts +98 -10
- package/dist/Authenticator.d.ts.map +1 -1
- package/dist/Authenticator.js +223 -19
- package/dist/Authenticator.js.map +1 -1
- package/dist/Guard.d.ts.map +1 -1
- package/dist/Guard.js +17 -5
- package/dist/Guard.js.map +1 -1
- package/dist/RedisBlacklistDriver.d.ts.map +1 -1
- package/dist/RedisBlacklistDriver.js +11 -0
- package/dist/RedisBlacklistDriver.js.map +1 -1
- package/dist/RefreshTokenStore.d.ts +37 -6
- package/dist/RefreshTokenStore.d.ts.map +1 -1
- package/dist/RefreshTokenStore.js +51 -10
- package/dist/RefreshTokenStore.js.map +1 -1
- package/dist/ResilientBlacklistDriver.d.ts +23 -6
- package/dist/ResilientBlacklistDriver.d.ts.map +1 -1
- package/dist/ResilientBlacklistDriver.js +26 -9
- package/dist/ResilientBlacklistDriver.js.map +1 -1
- package/dist/TokenBlacklist.d.ts +3 -1
- package/dist/TokenBlacklist.d.ts.map +1 -1
- package/dist/TokenBlacklist.js +27 -1
- package/dist/TokenBlacklist.js.map +1 -1
- package/dist/WardenProvider.d.ts +2 -0
- package/dist/WardenProvider.d.ts.map +1 -1
- package/dist/WardenProvider.js +4 -58
- package/dist/WardenProvider.js.map +1 -1
- package/dist/authFinder.d.ts +58 -0
- package/dist/authFinder.d.ts.map +1 -0
- package/dist/authFinder.js +77 -0
- package/dist/authFinder.js.map +1 -0
- package/dist/bearer.d.ts +12 -0
- package/dist/bearer.d.ts.map +1 -0
- package/dist/bearer.js +19 -0
- package/dist/bearer.js.map +1 -0
- package/dist/bouncer/Bouncer.d.ts +2 -2
- package/dist/bouncer/Bouncer.d.ts.map +1 -1
- package/dist/bouncer/Bouncer.js +17 -4
- package/dist/bouncer/Bouncer.js.map +1 -1
- package/dist/bouncer/PolicyAuthorizer.d.ts +1 -1
- package/dist/bouncer/PolicyAuthorizer.d.ts.map +1 -1
- package/dist/bouncer/PolicyAuthorizer.js +1 -1
- package/dist/bouncer/PolicyAuthorizer.js.map +1 -1
- package/dist/bouncer/evaluate.d.ts +5 -1
- package/dist/bouncer/evaluate.d.ts.map +1 -1
- package/dist/bouncer/evaluate.js +7 -6
- package/dist/bouncer/evaluate.js.map +1 -1
- package/dist/config.d.ts +8 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +4 -1
- package/dist/config.js.map +1 -1
- package/dist/errors.d.ts +28 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +63 -2
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +10 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/mfa/MfaManager.d.ts +33 -8
- package/dist/mfa/MfaManager.d.ts.map +1 -1
- package/dist/mfa/MfaManager.js +69 -20
- package/dist/mfa/MfaManager.js.map +1 -1
- package/dist/mfa/TotpProvider.d.ts.map +1 -1
- package/dist/mfa/TotpProvider.js +8 -0
- package/dist/mfa/TotpProvider.js.map +1 -1
- package/dist/mfa/WebauthnProvider.d.ts +22 -0
- package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
- package/dist/mfa/WebauthnProvider.js +57 -12
- package/dist/mfa/WebauthnProvider.js.map +1 -1
- package/dist/middleware.d.ts +13 -3
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +28 -6
- package/dist/middleware.js.map +1 -1
- package/dist/native.d.ts +6 -2
- package/dist/native.d.ts.map +1 -1
- package/dist/native.js +19 -2
- package/dist/native.js.map +1 -1
- package/dist/quasar.d.ts.map +1 -1
- package/dist/quasar.js +8 -1
- package/dist/quasar.js.map +1 -1
- package/dist/rights/RightsResolver.d.ts +10 -0
- package/dist/rights/RightsResolver.d.ts.map +1 -1
- package/dist/rights/RightsResolver.js +23 -0
- package/dist/rights/RightsResolver.js.map +1 -1
- package/dist/sanitize.d.ts.map +1 -1
- package/dist/sanitize.js +3 -1
- package/dist/sanitize.js.map +1 -1
- package/dist/services/main.d.ts.map +1 -1
- package/dist/services/main.js +12 -2
- package/dist/services/main.js.map +1 -1
- package/dist/standalone.d.ts +24 -3
- package/dist/standalone.d.ts.map +1 -1
- package/dist/standalone.js +22 -32
- package/dist/standalone.js.map +1 -1
- package/dist/strategies/ApiKeyStrategy.d.ts +46 -12
- package/dist/strategies/ApiKeyStrategy.d.ts.map +1 -1
- package/dist/strategies/ApiKeyStrategy.js +76 -37
- package/dist/strategies/ApiKeyStrategy.js.map +1 -1
- package/dist/strategies/BasicAuthStrategy.d.ts.map +1 -1
- package/dist/strategies/BasicAuthStrategy.js +5 -2
- package/dist/strategies/BasicAuthStrategy.js.map +1 -1
- package/dist/strategies/JwtStrategy.d.ts +6 -2
- package/dist/strategies/JwtStrategy.d.ts.map +1 -1
- package/dist/strategies/JwtStrategy.js +58 -11
- package/dist/strategies/JwtStrategy.js.map +1 -1
- package/dist/strategies/SessionStrategy.d.ts.map +1 -1
- package/dist/strategies/SessionStrategy.js +4 -1
- package/dist/strategies/SessionStrategy.js.map +1 -1
- package/dist/templateTags.d.ts +42 -0
- package/dist/templateTags.d.ts.map +1 -0
- package/dist/templateTags.js +82 -0
- package/dist/templateTags.js.map +1 -0
- package/dist/vendor/nativeBinary.d.ts +26 -2
- package/dist/vendor/nativeBinary.d.ts.map +1 -1
- package/dist/vendor/nativeBinary.js +63 -6
- package/dist/vendor/nativeBinary.js.map +1 -1
- package/dist/vendor/quasarConnection.d.ts +44 -3
- package/dist/vendor/quasarConnection.d.ts.map +1 -1
- package/dist/vendor/quasarConnection.js +64 -23
- package/dist/vendor/quasarConnection.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 +9 -5
- package/src/AccessToken.ts +550 -0
- package/src/AttemptStore.ts +42 -13
- package/src/AuthManager.ts +75 -18
- package/src/AuthRateLimiter.ts +24 -8
- package/src/Authenticator.ts +282 -22
- package/src/Guard.ts +18 -5
- package/src/RedisBlacklistDriver.ts +11 -0
- package/src/RefreshTokenStore.ts +79 -13
- package/src/ResilientBlacklistDriver.ts +30 -9
- package/src/TokenBlacklist.ts +28 -1
- package/src/WardenProvider.ts +6 -83
- package/src/authFinder.ts +118 -0
- package/src/bearer.ts +16 -0
- package/src/bouncer/Bouncer.ts +21 -6
- package/src/bouncer/PolicyAuthorizer.ts +1 -1
- package/src/bouncer/evaluate.ts +7 -10
- package/src/config.ts +8 -4
- package/src/errors.ts +80 -2
- package/src/index.ts +29 -0
- package/src/mfa/MfaManager.ts +98 -22
- package/src/mfa/TotpProvider.ts +15 -2
- package/src/mfa/WebauthnProvider.ts +77 -13
- package/src/middleware.ts +52 -8
- package/src/native.ts +20 -4
- package/src/quasar.ts +13 -2
- package/src/rights/RightsResolver.ts +27 -0
- package/src/sanitize.ts +4 -2
- package/src/services/main.ts +14 -2
- package/src/standalone.ts +75 -37
- package/src/strategies/ApiKeyStrategy.ts +117 -42
- package/src/strategies/BasicAuthStrategy.ts +7 -2
- package/src/strategies/JwtStrategy.ts +61 -10
- package/src/strategies/SessionStrategy.ts +4 -1
- package/src/templateTags.ts +117 -0
- package/src/vendor/nativeBinary.ts +82 -6
- package/src/vendor/quasarConnection.ts +105 -22
- package/stubs/config/auth.stub +3 -0
- package/scripts/build-napi-types.mjs +0 -69
- package/scripts/copy-napi.mjs +0 -75
- package/scripts/generate-napi-types.mjs +0 -156
package/src/AuthManager.ts
CHANGED
|
@@ -8,7 +8,10 @@ import { Authenticator } from "./Authenticator.js";
|
|
|
8
8
|
import { WardenError } from "./errors.js";
|
|
9
9
|
import type { WardenContext } from "./middleware.js";
|
|
10
10
|
import { MemoryRightsStore } from "./rights/MemoryRightsStore.js";
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
narrowToAccessToken,
|
|
13
|
+
RightsResolver,
|
|
14
|
+
} from "./rights/RightsResolver.js";
|
|
12
15
|
import type { EffectivePermissions, Scope } from "./rights/types.js";
|
|
13
16
|
import { sanitizePayload } from "./sanitize.js";
|
|
14
17
|
import type {
|
|
@@ -16,10 +19,43 @@ import type {
|
|
|
16
19
|
SessionStore,
|
|
17
20
|
} from "./strategies/SessionStrategy.js";
|
|
18
21
|
|
|
22
|
+
/**
|
|
23
|
+
* The token a request authenticated with, when it authenticated with one: an
|
|
24
|
+
* access token, or an OAuth token from a guard such as visa's. Its abilities
|
|
25
|
+
* are what the TOKEN may do, a separate axis from `UserPayload.permissions`
|
|
26
|
+
* (what the USER may do): a request may act only where both agree.
|
|
27
|
+
*/
|
|
28
|
+
export interface CurrentAccessToken {
|
|
29
|
+
readonly abilities: readonly string[];
|
|
30
|
+
/** Whether the token may do `ability` (`*` grants every ability). */
|
|
31
|
+
allows(ability: string): boolean;
|
|
32
|
+
denies(ability: string): boolean;
|
|
33
|
+
/** Throw unless the token may do `ability`. */
|
|
34
|
+
authorize(ability: string): void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Whether the token the user authenticated with, if any, allows `permission`.
|
|
39
|
+
*
|
|
40
|
+
* A permission check on a request made with a token is an INTERSECTION: the
|
|
41
|
+
* user must hold the permission AND the token must allow it. The token never
|
|
42
|
+
* widens what the user may do (a same-named ability grants nothing the user
|
|
43
|
+
* lacks), and it narrows it: a token limited to a few abilities does not carry
|
|
44
|
+
* every permission of its user. A user with no `currentAccessToken` (a session,
|
|
45
|
+
* a JWT) is not restricted here.
|
|
46
|
+
*/
|
|
47
|
+
export function tokenAllows(user: UserPayload, permission: string): boolean {
|
|
48
|
+
const token = user.currentAccessToken;
|
|
49
|
+
return token === undefined || token.allows(permission);
|
|
50
|
+
}
|
|
51
|
+
|
|
19
52
|
export interface UserPayload {
|
|
20
53
|
id: string;
|
|
21
54
|
roles?: string[];
|
|
55
|
+
/** The user's own permissions. Never widened by a token's abilities. */
|
|
22
56
|
permissions?: string[];
|
|
57
|
+
/** Set by a token guard: the token this request authenticated with. */
|
|
58
|
+
currentAccessToken?: CurrentAccessToken;
|
|
23
59
|
[key: string]: unknown;
|
|
24
60
|
}
|
|
25
61
|
|
|
@@ -28,11 +64,13 @@ export interface AuthResult {
|
|
|
28
64
|
user?: UserPayload;
|
|
29
65
|
error?: string;
|
|
30
66
|
/**
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* rejection
|
|
34
|
-
*
|
|
35
|
-
*
|
|
67
|
+
* Set when the strategy's `verify()` / `authenticate()` THREW a generic
|
|
68
|
+
* error, as opposed to returning a deliberate `{ authenticated: false }`
|
|
69
|
+
* rejection: a server incident (the user store is down), not bad
|
|
70
|
+
* credentials. A caller answers it as unavailable (500), does not count it
|
|
71
|
+
* against the user's failed attempts, and does not tell the user their
|
|
72
|
+
* password is wrong. `authenticate()` carries no `error` text with it; the
|
|
73
|
+
* cause is in the server log.
|
|
36
74
|
*/
|
|
37
75
|
strategyCrash?: true;
|
|
38
76
|
}
|
|
@@ -238,13 +276,18 @@ export class AuthManager {
|
|
|
238
276
|
} catch (err) {
|
|
239
277
|
// Re-throw structured WardenError sentinels (e.g. SessionStrategy's
|
|
240
278
|
// USE_LOGIN throw) so callers see the design-boundary signal instead
|
|
241
|
-
// of a soft `{ authenticated: false }`.
|
|
279
|
+
// of a soft `{ authenticated: false }`.
|
|
242
280
|
if (err instanceof WardenError) throw err;
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
281
|
+
// Anything else is an outage (a database down, a driver bug), not a
|
|
282
|
+
// wrong password: flag it so the caller does not answer "invalid
|
|
283
|
+
// credentials" or count it as a failed attempt. The thrown text names
|
|
284
|
+
// hosts, ports and queries, so it goes to the server log and never
|
|
285
|
+
// into the result a caller may render.
|
|
286
|
+
console.error(
|
|
287
|
+
`[warden] strategy '${strategyName ?? this.#default}' threw during authenticate():`,
|
|
288
|
+
err,
|
|
289
|
+
);
|
|
290
|
+
return { authenticated: false, strategyCrash: true };
|
|
248
291
|
}
|
|
249
292
|
}
|
|
250
293
|
|
|
@@ -311,12 +354,15 @@ export class AuthManager {
|
|
|
311
354
|
* Bouncer policy path (`this.permissions`, 56.3) consults the SAME resolver,
|
|
312
355
|
* so a coarse question and a policy question return the same answer for the
|
|
313
356
|
* same `(user, scope)` (the single unification point — AC-E3).
|
|
357
|
+
*
|
|
358
|
+
* Narrowed by the access token the user came in with, if any
|
|
359
|
+
* ({@link narrowToAccessToken}): the set is what THIS request may do.
|
|
314
360
|
*/
|
|
315
|
-
resolvePermissions(
|
|
361
|
+
async resolvePermissions(
|
|
316
362
|
user: UserPayload,
|
|
317
363
|
scope: Scope = "global",
|
|
318
364
|
): Promise<EffectivePermissions> {
|
|
319
|
-
return this.#rights.resolve(user, scope);
|
|
365
|
+
return narrowToAccessToken(await this.#rights.resolve(user, scope), user);
|
|
320
366
|
}
|
|
321
367
|
|
|
322
368
|
/**
|
|
@@ -335,25 +381,30 @@ export class AuthManager {
|
|
|
335
381
|
/**
|
|
336
382
|
* Check if a user has a specific permission within a scope (default
|
|
337
383
|
* `"global"`). Derived from roles + store grants ONLY — token
|
|
338
|
-
* `user.permissions` is NOT read (D1, cerebrum 459).
|
|
384
|
+
* `user.permissions` is NOT read (D1, cerebrum 459). When the user came in
|
|
385
|
+
* with a token (`currentAccessToken`), the token must allow it too: see
|
|
386
|
+
* {@link tokenAllows}.
|
|
339
387
|
*/
|
|
340
388
|
async hasPermission(
|
|
341
389
|
user: UserPayload,
|
|
342
390
|
permission: string,
|
|
343
391
|
scope: Scope = "global",
|
|
344
392
|
): Promise<boolean> {
|
|
393
|
+
if (!tokenAllows(user, permission)) return false;
|
|
345
394
|
return (await this.resolvePermissions(user, scope)).has(permission);
|
|
346
395
|
}
|
|
347
396
|
|
|
348
397
|
/**
|
|
349
398
|
* Check if a user has ALL required permissions within a scope (default
|
|
350
|
-
* `"global"`). Empty list ⇒ vacuously true.
|
|
399
|
+
* `"global"`). Empty list ⇒ vacuously true. Intersected with the token's
|
|
400
|
+
* abilities like {@link hasPermission}.
|
|
351
401
|
*/
|
|
352
402
|
async hasAllPermissions(
|
|
353
403
|
user: UserPayload,
|
|
354
|
-
permissions: string[],
|
|
404
|
+
permissions: readonly string[],
|
|
355
405
|
scope: Scope = "global",
|
|
356
406
|
): Promise<boolean> {
|
|
407
|
+
if (!permissions.every((p) => tokenAllows(user, p))) return false;
|
|
357
408
|
return (await this.resolvePermissions(user, scope)).hasAll(permissions);
|
|
358
409
|
}
|
|
359
410
|
|
|
@@ -510,7 +561,13 @@ export class AuthManager {
|
|
|
510
561
|
},
|
|
511
562
|
);
|
|
512
563
|
}
|
|
513
|
-
|
|
564
|
+
const revived = await strategy.authenticateViaRememberMeToken(
|
|
565
|
+
cookieValue,
|
|
566
|
+
state,
|
|
567
|
+
);
|
|
568
|
+
// The same prototype-pollution guard `verify` and `authenticate` apply.
|
|
569
|
+
if (revived) sanitizePayload(revived.user);
|
|
570
|
+
return revived;
|
|
514
571
|
}
|
|
515
572
|
|
|
516
573
|
/**
|
package/src/AuthRateLimiter.ts
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
* @implements MISS-26
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
+
import { createHash } from "node:crypto";
|
|
22
23
|
import { type AttemptStore, MemoryAttemptStore } from "./AttemptStore.js";
|
|
23
24
|
import { WardenError } from "./errors.js";
|
|
24
25
|
|
|
@@ -59,22 +60,37 @@ export class AuthRateLimiter {
|
|
|
59
60
|
this.#store = config.store ?? new MemoryAttemptStore();
|
|
60
61
|
}
|
|
61
62
|
|
|
62
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* The keys a login attempt is counted under: its IP first, then its
|
|
65
|
+
* identifier. The identifier is keyed by the SHA-256 of its normalized form
|
|
66
|
+
* (trimmed, lowercased): it is whatever the client posted, and kept
|
|
67
|
+
* verbatim a 1 MB body pinned 1 MB in the store for the whole window.
|
|
68
|
+
*/
|
|
63
69
|
static loginKeys(ip: string, identifier: string): string[] {
|
|
64
|
-
|
|
70
|
+
const digest = createHash("sha256")
|
|
71
|
+
.update(identifier.trim().toLowerCase())
|
|
72
|
+
.digest("base64url");
|
|
73
|
+
return [`ip:${ip.trim()}`, `id:${digest}`];
|
|
65
74
|
}
|
|
66
75
|
|
|
67
76
|
/**
|
|
68
|
-
* Count an attempt under
|
|
69
|
-
* BEFORE checking the credential; a refused attempt must not reach
|
|
77
|
+
* Count an attempt under its keys, in order, and say whether it may go on.
|
|
78
|
+
* Call it BEFORE checking the credential; a refused attempt must not reach
|
|
79
|
+
* it.
|
|
80
|
+
*
|
|
81
|
+
* The first key over the limit refuses the attempt and the keys after it
|
|
82
|
+
* are not counted. Counting them all let an IP already throttled create
|
|
83
|
+
* one `id:` window per request: a client cycling identifiers filled the
|
|
84
|
+
* memory store, whose bound then refused every other client's new keys.
|
|
85
|
+
* Stopped at the spent `ip:` key, one address touches at most
|
|
86
|
+
* `maxAttempts` identifiers per window.
|
|
70
87
|
*/
|
|
71
88
|
async attempt(...keys: string[]): Promise<AttemptDecision> {
|
|
72
|
-
const counts = await Promise.all(
|
|
73
|
-
keys.map((key) => this.#store.increment(key, this.#windowSeconds)),
|
|
74
|
-
);
|
|
75
89
|
let highest = { count: 0, resetSeconds: 0 };
|
|
76
|
-
for (const
|
|
90
|
+
for (const key of keys) {
|
|
91
|
+
const counted = await this.#store.increment(key, this.#windowSeconds);
|
|
77
92
|
if (counted.count > highest.count) highest = counted;
|
|
93
|
+
if (counted.count > this.#maxAttempts) break;
|
|
78
94
|
}
|
|
79
95
|
return {
|
|
80
96
|
allowed: highest.count <= this.#maxAttempts,
|
package/src/Authenticator.ts
CHANGED
|
@@ -15,13 +15,21 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import type {
|
|
18
|
+
AccessToken,
|
|
19
|
+
CreateAccessTokenOptions,
|
|
20
|
+
TokenOwner,
|
|
21
|
+
} from "./AccessToken.js";
|
|
22
|
+
import type {
|
|
23
|
+
AuthClientResponse,
|
|
18
24
|
AuthManager,
|
|
19
25
|
AuthResult,
|
|
20
26
|
AuthStrategy,
|
|
21
27
|
UserPayload,
|
|
22
28
|
} from "./AuthManager.js";
|
|
29
|
+
import { readBearerToken } from "./bearer.js";
|
|
23
30
|
import { E_UNAUTHORIZED_ACCESS, WardenError } from "./errors.js";
|
|
24
31
|
import type { WardenContext } from "./middleware.js";
|
|
32
|
+
import type { Scope } from "./rights/types.js";
|
|
25
33
|
import { sanitizePayload } from "./sanitize.js";
|
|
26
34
|
import {
|
|
27
35
|
createSessionGuardState,
|
|
@@ -129,11 +137,54 @@ function isSessionGuard(auth: AuthManager, name: string): boolean {
|
|
|
129
137
|
function hasVerifyWithContext(
|
|
130
138
|
strategy: AuthStrategy,
|
|
131
139
|
): strategy is StrategyWithContext {
|
|
140
|
+
return typeof Reflect.get(strategy, "verifyWithContext") === "function";
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* A guard that mints and revokes access tokens (`ApiKeyStrategy`, or one an
|
|
145
|
+
* application wrote with the same two members).
|
|
146
|
+
*/
|
|
147
|
+
interface AccessTokenIssuer {
|
|
148
|
+
createToken(
|
|
149
|
+
user: TokenOwner,
|
|
150
|
+
abilities?: string[],
|
|
151
|
+
options?: CreateAccessTokenOptions,
|
|
152
|
+
): Promise<AccessToken>;
|
|
153
|
+
invalidateToken(value: string): Promise<boolean>;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function isAccessTokenIssuer(
|
|
157
|
+
strategy: AuthStrategy,
|
|
158
|
+
): strategy is AuthStrategy & AccessTokenIssuer {
|
|
132
159
|
return (
|
|
133
|
-
typeof (strategy
|
|
160
|
+
typeof Reflect.get(strategy, "createToken") === "function" &&
|
|
161
|
+
typeof Reflect.get(strategy, "invalidateToken") === "function"
|
|
134
162
|
);
|
|
135
163
|
}
|
|
136
164
|
|
|
165
|
+
/**
|
|
166
|
+
* What a test seam hands back is the strategy's own business; this only checks
|
|
167
|
+
* it is the object the harness reads fields from.
|
|
168
|
+
*/
|
|
169
|
+
function isAuthClientResponse(value: unknown): value is AuthClientResponse {
|
|
170
|
+
return typeof value === "object" && value !== null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The credential a token guard reads from a request: the API-key header first
|
|
175
|
+
* for an API-key guard name, the Bearer token first for any other — the same
|
|
176
|
+
* pick {@link tryAuthenticate} makes, so the token revoked is the one that
|
|
177
|
+
* authenticated.
|
|
178
|
+
*/
|
|
179
|
+
function tokenCredentialFor(
|
|
180
|
+
strategyName: string,
|
|
181
|
+
creds: ExtractedCredentials,
|
|
182
|
+
): string {
|
|
183
|
+
return API_KEY_GUARD_NAMES.includes(strategyName)
|
|
184
|
+
? creds.apiKey || creds.bearerToken
|
|
185
|
+
: creds.bearerToken || creds.apiKey;
|
|
186
|
+
}
|
|
187
|
+
|
|
137
188
|
/** The credentials Warden extracts from a request, independent of guard list. */
|
|
138
189
|
export interface ExtractedCredentials {
|
|
139
190
|
bearerToken: string;
|
|
@@ -186,9 +237,7 @@ export function extractCredentials(
|
|
|
186
237
|
): ExtractedCredentials {
|
|
187
238
|
const headers = ctx.request.headers();
|
|
188
239
|
const authHeader = headers.authorization ?? "";
|
|
189
|
-
const bearerToken = authHeader
|
|
190
|
-
? authHeader.slice(7)
|
|
191
|
-
: "";
|
|
240
|
+
const bearerToken = readBearerToken(authHeader);
|
|
192
241
|
// The scheme is case-insensitive (RFC 7235); the strategy decodes the rest.
|
|
193
242
|
const basicAuth = /^basic\s/i.test(authHeader) ? authHeader : "";
|
|
194
243
|
// HTTP header names are case-insensitive; runtimes lowercase incoming keys,
|
|
@@ -217,7 +266,7 @@ async function tryAuthenticate(
|
|
|
217
266
|
strategies: string[],
|
|
218
267
|
creds: ExtractedCredentials,
|
|
219
268
|
): Promise<AuthAttempt> {
|
|
220
|
-
const {
|
|
269
|
+
const { basicAuth, session } = creds;
|
|
221
270
|
let result: AuthResult | null = null;
|
|
222
271
|
let viaGuard: string | undefined;
|
|
223
272
|
let attemptCount = 0;
|
|
@@ -251,9 +300,7 @@ async function tryAuthenticate(
|
|
|
251
300
|
// Native-first credential, other transport as fallback so a
|
|
252
301
|
// single-credential client still authenticates (and an invalid
|
|
253
302
|
// Bearer no longer masks a valid API key for the api-key guard).
|
|
254
|
-
const credential =
|
|
255
|
-
? apiKey || bearerToken
|
|
256
|
-
: bearerToken || apiKey;
|
|
303
|
+
const credential = tokenCredentialFor(strategyName, creds);
|
|
257
304
|
if (!credential) continue;
|
|
258
305
|
attemptCount++;
|
|
259
306
|
r = await auth.verify(credential, strategyName);
|
|
@@ -321,6 +368,114 @@ export class GuardAccessor {
|
|
|
321
368
|
return this.user !== undefined;
|
|
322
369
|
}
|
|
323
370
|
|
|
371
|
+
/** Whether this guard was tried during the request (AdonisJS guard parity). */
|
|
372
|
+
get authenticationAttempted(): boolean {
|
|
373
|
+
return this.#parent.attemptedVia(this.#name);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* The user, or `E_UNAUTHORIZED_ACCESS` when this guard did not authenticate
|
|
378
|
+
* the request (AdonisJS `guard.getUserOrFail()`).
|
|
379
|
+
*/
|
|
380
|
+
getUserOrFail(): UserPayload {
|
|
381
|
+
const user = this.user;
|
|
382
|
+
if (user === undefined) {
|
|
383
|
+
throw new E_UNAUTHORIZED_ACCESS("Unauthorized access", {
|
|
384
|
+
guardDriverName: this.#name,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
return user;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Authenticate through this guard and say whether it worked, without
|
|
392
|
+
* throwing on a credential rejection (AdonisJS `guard.check()`). A crashed
|
|
393
|
+
* strategy still throws: an outage is not a guest.
|
|
394
|
+
*/
|
|
395
|
+
async check(): Promise<boolean> {
|
|
396
|
+
try {
|
|
397
|
+
await this.authenticate();
|
|
398
|
+
return true;
|
|
399
|
+
} catch (err) {
|
|
400
|
+
if (err instanceof E_UNAUTHORIZED_ACCESS) return false;
|
|
401
|
+
throw err;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* What a test client sends to be a user through this guard (AdonisJS
|
|
407
|
+
* `guard.authenticateAsClient`). The arguments are the strategy's own: a
|
|
408
|
+
* user for a session guard, a user plus abilities for a token guard.
|
|
409
|
+
*/
|
|
410
|
+
async authenticateAsClient(...args: unknown[]): Promise<AuthClientResponse> {
|
|
411
|
+
const strategy = this.#auth.getStrategy(this.#name);
|
|
412
|
+
const seam: unknown = Reflect.get(strategy, "authenticateAsClient");
|
|
413
|
+
if (typeof seam !== "function") {
|
|
414
|
+
throw new WardenError(
|
|
415
|
+
"STRATEGY_HAS_NO_CLIENT",
|
|
416
|
+
`Auth strategy '${this.#name}' has no authenticateAsClient() — it cannot forge a client request.`,
|
|
417
|
+
{
|
|
418
|
+
hint: "Implement authenticateAsClient() on the strategy, or authenticate through a real login in the test.",
|
|
419
|
+
},
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
const response: unknown = await Reflect.apply(seam, strategy, args);
|
|
423
|
+
if (!isAuthClientResponse(response)) {
|
|
424
|
+
throw new WardenError(
|
|
425
|
+
"STRATEGY_HAS_NO_CLIENT",
|
|
426
|
+
`Auth strategy '${this.#name}' answered authenticateAsClient() with no client response.`,
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
return response;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Mint an access token for `user` through this guard (AdonisJS
|
|
434
|
+
* `auth.use('api').createToken(user, abilities, options)`). The returned
|
|
435
|
+
* token carries its `value` this once: hand it to the client now.
|
|
436
|
+
*/
|
|
437
|
+
async createToken(
|
|
438
|
+
user: TokenOwner,
|
|
439
|
+
abilities?: string[],
|
|
440
|
+
options?: CreateAccessTokenOptions,
|
|
441
|
+
): Promise<AccessToken> {
|
|
442
|
+
return this.#tokenIssuer().createToken(user, abilities, options);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Revoke the access token this request came in with (AdonisJS
|
|
447
|
+
* `auth.use('api').invalidateToken()`) — the sign-out of a token client.
|
|
448
|
+
* Answers whether it existed; `E_UNAUTHORIZED_ACCESS` when the request
|
|
449
|
+
* carries no token, as upstream.
|
|
450
|
+
*/
|
|
451
|
+
async invalidateToken(): Promise<boolean> {
|
|
452
|
+
const issuer = this.#tokenIssuer();
|
|
453
|
+
const value = tokenCredentialFor(
|
|
454
|
+
this.#name,
|
|
455
|
+
extractCredentials(this.#ctx, this.#auth),
|
|
456
|
+
);
|
|
457
|
+
if (!value) {
|
|
458
|
+
throw new E_UNAUTHORIZED_ACCESS("Unauthorized access", {
|
|
459
|
+
guardDriverName: this.#name,
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
return issuer.invalidateToken(value);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
#tokenIssuer(): AccessTokenIssuer {
|
|
466
|
+
const strategy = this.#auth.getStrategy(this.#name);
|
|
467
|
+
if (!isAccessTokenIssuer(strategy)) {
|
|
468
|
+
throw new WardenError(
|
|
469
|
+
"STRATEGY_CANNOT_ISSUE",
|
|
470
|
+
`Guard '${this.#name}' does not issue access tokens.`,
|
|
471
|
+
{
|
|
472
|
+
hint: "createToken()/invalidateToken() belong to an access-tokens guard (apiKeyGuard). A JWT guard signs with auth.issueFor(user, guard).",
|
|
473
|
+
},
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
return strategy;
|
|
477
|
+
}
|
|
478
|
+
|
|
324
479
|
/**
|
|
325
480
|
* Whether the user was revived from a remember-me cookie rather than
|
|
326
481
|
* signing in.
|
|
@@ -365,8 +520,11 @@ export class GuardAccessor {
|
|
|
365
520
|
);
|
|
366
521
|
}
|
|
367
522
|
|
|
368
|
-
/**
|
|
369
|
-
|
|
523
|
+
/**
|
|
524
|
+
* Authenticate the request using only this guard, resolving to the user
|
|
525
|
+
* (throws `E_UNAUTHORIZED_ACCESS` on failure).
|
|
526
|
+
*/
|
|
527
|
+
authenticate(): Promise<UserPayload> {
|
|
370
528
|
return this.#parent.authenticateUsing([this.#name]);
|
|
371
529
|
}
|
|
372
530
|
|
|
@@ -394,6 +552,14 @@ export class GuardAccessor {
|
|
|
394
552
|
this.#state,
|
|
395
553
|
);
|
|
396
554
|
if (!revived) return undefined;
|
|
555
|
+
// A revival is never a step-up, whichever guard performed it: a guard
|
|
556
|
+
// the application wrote itself may hand back its row untouched, and an
|
|
557
|
+
// "MFA enabled" column on it must not satisfy `@RequireMfa()`.
|
|
558
|
+
const user: UserPayload = { ...revived.user, mfa: false };
|
|
559
|
+
// Same guard as every other path into `ctx.auth.user`, and BEFORE the
|
|
560
|
+
// session is seated with it: `findUser` may hand back a JSON-decoded
|
|
561
|
+
// row carrying an own `__proto__` / `constructor` key.
|
|
562
|
+
sanitizePayload(user);
|
|
397
563
|
|
|
398
564
|
write.call(
|
|
399
565
|
this.#ctx.response,
|
|
@@ -405,8 +571,8 @@ export class GuardAccessor {
|
|
|
405
571
|
// typed, and it clears `viaRemember` — the one thing this path exists to
|
|
406
572
|
// report, and what an app checks before letting someone change an email
|
|
407
573
|
// or spend money.
|
|
408
|
-
strategy.seatSession(
|
|
409
|
-
return
|
|
574
|
+
strategy.seatSession(user, session);
|
|
575
|
+
return user;
|
|
410
576
|
}
|
|
411
577
|
|
|
412
578
|
/**
|
|
@@ -545,9 +711,45 @@ export class GuardAccessor {
|
|
|
545
711
|
if (user) user.mfa = true;
|
|
546
712
|
}
|
|
547
713
|
|
|
548
|
-
/**
|
|
549
|
-
|
|
550
|
-
|
|
714
|
+
/**
|
|
715
|
+
* Log the current user out of this guard (session guards).
|
|
716
|
+
*
|
|
717
|
+
* Ends the remember-me credential too, as upstream's session guard does: the
|
|
718
|
+
* cookie is cleared and the stored token behind it deleted. Leaving either
|
|
719
|
+
* meant the next request, with an empty session, was signed straight back
|
|
720
|
+
* in from the cookie.
|
|
721
|
+
*
|
|
722
|
+
* The cookie is cleared first and whatever happens next: a store that fails
|
|
723
|
+
* to delete the row must not leave the browser holding the credential. The
|
|
724
|
+
* store's error is still thrown, after the session is ended, because a token
|
|
725
|
+
* row that survived a logout is something the application has to know about.
|
|
726
|
+
*
|
|
727
|
+
* NAMED DEVIATION — upstream deletes the row only once the presented secret
|
|
728
|
+
* matches it and only for the signed-in user. Here the row is deleted from
|
|
729
|
+
* the identifier the (encrypted) cookie names whatever the secret: a cookie
|
|
730
|
+
* whose secret no longer matches is one a stolen copy already recycled, and
|
|
731
|
+
* a logout from the real browser is exactly when that copy must die.
|
|
732
|
+
*/
|
|
733
|
+
async logout(): Promise<void> {
|
|
734
|
+
const session = this.#requireSession();
|
|
735
|
+
const strategy = strategyOrUndefined(this.#auth, this.#name);
|
|
736
|
+
const issuer =
|
|
737
|
+
strategy && isRememberMeIssuer(strategy) ? strategy : undefined;
|
|
738
|
+
const read = this.#ctx.request.encryptedCookie;
|
|
739
|
+
const cookie =
|
|
740
|
+
issuer && read
|
|
741
|
+
? read.call(this.#ctx.request, issuer.rememberMeCookieName)
|
|
742
|
+
: null;
|
|
743
|
+
this.#clearRememberMe();
|
|
744
|
+
let revocation: Promise<void> = Promise.resolve();
|
|
745
|
+
if (issuer && cookie) {
|
|
746
|
+
revocation = issuer.revokeRememberMeToken(cookie);
|
|
747
|
+
// Observed here so a failing store is not an unhandled rejection
|
|
748
|
+
// while the session is being ended; it is rethrown below.
|
|
749
|
+
revocation.catch(() => undefined);
|
|
750
|
+
}
|
|
751
|
+
await this.#auth.logout(session, this.#name, this.#state);
|
|
752
|
+
await revocation;
|
|
551
753
|
}
|
|
552
754
|
|
|
553
755
|
#requireSession(): SessionStore {
|
|
@@ -573,6 +775,8 @@ export class Authenticator {
|
|
|
573
775
|
#user?: UserPayload;
|
|
574
776
|
#viaGuard?: string;
|
|
575
777
|
#attempted = false;
|
|
778
|
+
/** Every guard tried during this request, for `use(name).authenticationAttempted`. */
|
|
779
|
+
readonly #attemptedGuards = new Set<string>();
|
|
576
780
|
readonly #guardCache = new Map<string, GuardAccessor>();
|
|
577
781
|
|
|
578
782
|
constructor(ctx: WardenContext, auth: AuthManager) {
|
|
@@ -600,6 +804,16 @@ export class Authenticator {
|
|
|
600
804
|
return this.#viaGuard;
|
|
601
805
|
}
|
|
602
806
|
|
|
807
|
+
/** The guard used when none is named (AdonisJS `auth.defaultGuard`). */
|
|
808
|
+
get defaultGuard(): string {
|
|
809
|
+
return this.#auth.defaultStrategyName;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/** @internal Whether `name` was tried during this request. */
|
|
813
|
+
attemptedVia(name: string): boolean {
|
|
814
|
+
return this.#attemptedGuards.has(name);
|
|
815
|
+
}
|
|
816
|
+
|
|
603
817
|
/**
|
|
604
818
|
* Roles of the authenticated user (Ream reads `ctx.auth.roles ??
|
|
605
819
|
* ctx.auth.user.roles`). Warden nests them under `user`; this getter mirrors
|
|
@@ -609,13 +823,50 @@ export class Authenticator {
|
|
|
609
823
|
return this.#user?.roles;
|
|
610
824
|
}
|
|
611
825
|
|
|
612
|
-
/**
|
|
826
|
+
/**
|
|
827
|
+
* Permissions the authenticated user's PAYLOAD carries (see
|
|
828
|
+
* {@link Authenticator.roles}). Informational only: a decision goes through
|
|
829
|
+
* {@link Authenticator.hasPermission}, which consults the rights resolver.
|
|
830
|
+
*/
|
|
613
831
|
get permissions(): string[] | undefined {
|
|
614
832
|
return this.#user?.permissions;
|
|
615
833
|
}
|
|
616
834
|
|
|
617
|
-
/**
|
|
618
|
-
|
|
835
|
+
/**
|
|
836
|
+
* Whether the authenticated user may do `permission` within `scope`.
|
|
837
|
+
*
|
|
838
|
+
* Delegates to {@link AuthManager.hasPermission}: the rights resolver decides
|
|
839
|
+
* (roles and grants from the store, never the payload's `permissions`), and
|
|
840
|
+
* the access token the request came with narrows it. A guest holds nothing.
|
|
841
|
+
*
|
|
842
|
+
* No upstream shape to mirror: the upstream authenticator has no notion of
|
|
843
|
+
* permissions. This is how a host's gates reach warden's rights layer
|
|
844
|
+
* through `ctx.auth` without importing warden.
|
|
845
|
+
*/
|
|
846
|
+
async hasPermission(permission: string, scope?: Scope): Promise<boolean> {
|
|
847
|
+
if (this.#user === undefined) return false;
|
|
848
|
+
return this.#auth.hasPermission(this.#user, permission, scope);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Whether the authenticated user may do every one of `permissions` within
|
|
853
|
+
* `scope` — {@link Authenticator.hasPermission} for a list. A guest holds
|
|
854
|
+
* nothing, not even the empty list.
|
|
855
|
+
*/
|
|
856
|
+
async hasAllPermissions(
|
|
857
|
+
permissions: readonly string[],
|
|
858
|
+
scope?: Scope,
|
|
859
|
+
): Promise<boolean> {
|
|
860
|
+
if (this.#user === undefined) return false;
|
|
861
|
+
return this.#auth.hasAllPermissions(this.#user, permissions, scope);
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
/**
|
|
865
|
+
* Authenticate via the default guard and resolve to the user (AdonisJS
|
|
866
|
+
* `const user = await auth.authenticate()`). Throws `E_UNAUTHORIZED_ACCESS`
|
|
867
|
+
* on failure.
|
|
868
|
+
*/
|
|
869
|
+
authenticate(): Promise<UserPayload> {
|
|
619
870
|
return this.authenticateUsing([this.#auth.defaultStrategyName]);
|
|
620
871
|
}
|
|
621
872
|
|
|
@@ -668,7 +919,7 @@ export class Authenticator {
|
|
|
668
919
|
async authenticateUsing(
|
|
669
920
|
guards?: string[],
|
|
670
921
|
options?: { loginRoute?: string },
|
|
671
|
-
): Promise<
|
|
922
|
+
): Promise<UserPayload> {
|
|
672
923
|
this.#attempted = true;
|
|
673
924
|
const names =
|
|
674
925
|
guards && guards.length > 0 ? guards : [this.#auth.defaultStrategyName];
|
|
@@ -691,6 +942,11 @@ export class Authenticator {
|
|
|
691
942
|
const { attemptCount, crashCount } = attempt;
|
|
692
943
|
let result = attempt.result;
|
|
693
944
|
let viaGuard = attempt.viaGuard;
|
|
945
|
+
// The guards tried, in order, up to the one that answered.
|
|
946
|
+
for (const name of names) {
|
|
947
|
+
this.#attemptedGuards.add(name);
|
|
948
|
+
if (name === viaGuard) break;
|
|
949
|
+
}
|
|
694
950
|
|
|
695
951
|
// No credential answered, but the browser may still hold a remember-me
|
|
696
952
|
// cookie — that is what "keep me signed in" means, and nothing read it.
|
|
@@ -715,7 +971,7 @@ export class Authenticator {
|
|
|
715
971
|
`${this.#auth.eventPrefixFor(winner)}:authentication_succeeded`,
|
|
716
972
|
{ guardName: winner, user: result.user, sessionId: undefined },
|
|
717
973
|
);
|
|
718
|
-
return;
|
|
974
|
+
return result.user;
|
|
719
975
|
}
|
|
720
976
|
// Every attempted guard crashed → a server-side incident, not a
|
|
721
977
|
// credential rejection. Surface distinctly (mapped to 500 by the caller).
|
|
@@ -758,8 +1014,11 @@ export class Authenticator {
|
|
|
758
1014
|
return this.#user;
|
|
759
1015
|
}
|
|
760
1016
|
|
|
761
|
-
/**
|
|
762
|
-
|
|
1017
|
+
/**
|
|
1018
|
+
* Access a named guard (AdonisJS `auth.use('web')`); the default guard when
|
|
1019
|
+
* no name is given. Instances are cached per request.
|
|
1020
|
+
*/
|
|
1021
|
+
use(name: string = this.#auth.defaultStrategyName): GuardAccessor {
|
|
763
1022
|
let accessor = this.#guardCache.get(name);
|
|
764
1023
|
if (!accessor) {
|
|
765
1024
|
accessor = new GuardAccessor(this.#ctx, this.#auth, name, this);
|
|
@@ -775,6 +1034,7 @@ export class Authenticator {
|
|
|
775
1034
|
*/
|
|
776
1035
|
adopt(result: AuthResult | null, viaGuard: string | undefined): void {
|
|
777
1036
|
this.#attempted = true;
|
|
1037
|
+
if (viaGuard !== undefined) this.#attemptedGuards.add(viaGuard);
|
|
778
1038
|
if (result?.authenticated && result.user) {
|
|
779
1039
|
this.#user = result.user;
|
|
780
1040
|
this.#viaGuard = viaGuard;
|