@c9up/warden 0.2.6 → 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 +4 -2
- package/dist/AttemptStore.d.ts.map +1 -1
- package/dist/AttemptStore.js +12 -0
- package/dist/AttemptStore.js.map +1 -1
- package/dist/AuthManager.d.ts +11 -6
- package/dist/AuthManager.d.ts.map +1 -1
- package/dist/AuthManager.js +19 -9
- 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 +79 -9
- package/dist/Authenticator.d.ts.map +1 -1
- package/dist/Authenticator.js +186 -16
- package/dist/Authenticator.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.map +1 -1
- package/dist/ResilientBlacklistDriver.js +2 -1
- 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/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/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 +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/mfa/MfaManager.d.ts +17 -4
- package/dist/mfa/MfaManager.d.ts.map +1 -1
- package/dist/mfa/MfaManager.js +37 -14
- 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 +1 -1
- package/dist/middleware.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.map +1 -1
- package/dist/standalone.js +2 -4
- package/dist/standalone.js.map +1 -1
- package/dist/strategies/ApiKeyStrategy.d.ts +5 -4
- package/dist/strategies/ApiKeyStrategy.d.ts.map +1 -1
- package/dist/strategies/ApiKeyStrategy.js +10 -5
- 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 +55 -8
- 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/vendor/quasarConnection.d.ts +18 -0
- package/dist/vendor/quasarConnection.d.ts.map +1 -1
- package/dist/vendor/quasarConnection.js +20 -0
- 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 +3 -4
- package/src/AttemptStore.ts +13 -0
- package/src/AuthManager.ts +35 -16
- package/src/AuthRateLimiter.ts +24 -8
- package/src/Authenticator.ts +243 -19
- package/src/RedisBlacklistDriver.ts +11 -0
- package/src/RefreshTokenStore.ts +79 -13
- package/src/ResilientBlacklistDriver.ts +2 -1
- package/src/TokenBlacklist.ts +28 -1
- 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/errors.ts +80 -2
- package/src/index.ts +11 -0
- package/src/mfa/MfaManager.ts +59 -16
- package/src/mfa/TotpProvider.ts +15 -2
- package/src/mfa/WebauthnProvider.ts +77 -13
- package/src/middleware.ts +16 -3
- package/src/rights/RightsResolver.ts +27 -0
- package/src/sanitize.ts +4 -2
- package/src/services/main.ts +14 -2
- package/src/standalone.ts +2 -5
- package/src/strategies/ApiKeyStrategy.ts +10 -5
- package/src/strategies/BasicAuthStrategy.ts +7 -2
- package/src/strategies/JwtStrategy.ts +58 -9
- package/src/strategies/SessionStrategy.ts +4 -1
- package/src/vendor/quasarConnection.ts +21 -0
- 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/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
|
/**
|
|
@@ -609,6 +775,8 @@ export class Authenticator {
|
|
|
609
775
|
#user?: UserPayload;
|
|
610
776
|
#viaGuard?: string;
|
|
611
777
|
#attempted = false;
|
|
778
|
+
/** Every guard tried during this request, for `use(name).authenticationAttempted`. */
|
|
779
|
+
readonly #attemptedGuards = new Set<string>();
|
|
612
780
|
readonly #guardCache = new Map<string, GuardAccessor>();
|
|
613
781
|
|
|
614
782
|
constructor(ctx: WardenContext, auth: AuthManager) {
|
|
@@ -636,6 +804,16 @@ export class Authenticator {
|
|
|
636
804
|
return this.#viaGuard;
|
|
637
805
|
}
|
|
638
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
|
+
|
|
639
817
|
/**
|
|
640
818
|
* Roles of the authenticated user (Ream reads `ctx.auth.roles ??
|
|
641
819
|
* ctx.auth.user.roles`). Warden nests them under `user`; this getter mirrors
|
|
@@ -645,13 +823,50 @@ export class Authenticator {
|
|
|
645
823
|
return this.#user?.roles;
|
|
646
824
|
}
|
|
647
825
|
|
|
648
|
-
/**
|
|
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
|
+
*/
|
|
649
831
|
get permissions(): string[] | undefined {
|
|
650
832
|
return this.#user?.permissions;
|
|
651
833
|
}
|
|
652
834
|
|
|
653
|
-
/**
|
|
654
|
-
|
|
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> {
|
|
655
870
|
return this.authenticateUsing([this.#auth.defaultStrategyName]);
|
|
656
871
|
}
|
|
657
872
|
|
|
@@ -704,7 +919,7 @@ export class Authenticator {
|
|
|
704
919
|
async authenticateUsing(
|
|
705
920
|
guards?: string[],
|
|
706
921
|
options?: { loginRoute?: string },
|
|
707
|
-
): Promise<
|
|
922
|
+
): Promise<UserPayload> {
|
|
708
923
|
this.#attempted = true;
|
|
709
924
|
const names =
|
|
710
925
|
guards && guards.length > 0 ? guards : [this.#auth.defaultStrategyName];
|
|
@@ -727,6 +942,11 @@ export class Authenticator {
|
|
|
727
942
|
const { attemptCount, crashCount } = attempt;
|
|
728
943
|
let result = attempt.result;
|
|
729
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
|
+
}
|
|
730
950
|
|
|
731
951
|
// No credential answered, but the browser may still hold a remember-me
|
|
732
952
|
// cookie — that is what "keep me signed in" means, and nothing read it.
|
|
@@ -751,7 +971,7 @@ export class Authenticator {
|
|
|
751
971
|
`${this.#auth.eventPrefixFor(winner)}:authentication_succeeded`,
|
|
752
972
|
{ guardName: winner, user: result.user, sessionId: undefined },
|
|
753
973
|
);
|
|
754
|
-
return;
|
|
974
|
+
return result.user;
|
|
755
975
|
}
|
|
756
976
|
// Every attempted guard crashed → a server-side incident, not a
|
|
757
977
|
// credential rejection. Surface distinctly (mapped to 500 by the caller).
|
|
@@ -794,8 +1014,11 @@ export class Authenticator {
|
|
|
794
1014
|
return this.#user;
|
|
795
1015
|
}
|
|
796
1016
|
|
|
797
|
-
/**
|
|
798
|
-
|
|
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 {
|
|
799
1022
|
let accessor = this.#guardCache.get(name);
|
|
800
1023
|
if (!accessor) {
|
|
801
1024
|
accessor = new GuardAccessor(this.#ctx, this.#auth, name, this);
|
|
@@ -811,6 +1034,7 @@ export class Authenticator {
|
|
|
811
1034
|
*/
|
|
812
1035
|
adopt(result: AuthResult | null, viaGuard: string | undefined): void {
|
|
813
1036
|
this.#attempted = true;
|
|
1037
|
+
if (viaGuard !== undefined) this.#attemptedGuards.add(viaGuard);
|
|
814
1038
|
if (result?.authenticated && result.user) {
|
|
815
1039
|
this.#user = result.user;
|
|
816
1040
|
this.#viaGuard = viaGuard;
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import type { BlacklistDriver } from "./TokenBlacklist.js";
|
|
12
|
+
import { hasEnded } from "./vendor/quasarConnection.js";
|
|
12
13
|
|
|
13
14
|
/** The minimal ioredis-shaped surface this driver needs. */
|
|
14
15
|
export interface RedisLikeClient {
|
|
@@ -49,8 +50,18 @@ export class RedisBlacklistDriver implements BlacklistDriver {
|
|
|
49
50
|
/**
|
|
50
51
|
* The client, resolved once. Two requests racing on a cold start must not
|
|
51
52
|
* each open their own connection, so the in-flight promise is shared.
|
|
53
|
+
*
|
|
54
|
+
* Resolved AGAIN once the client it holds has ended for good: quasar
|
|
55
|
+
* retires a connection whose retry strategy gave up and hands out a fresh
|
|
56
|
+
* one, and keeping the dead client failed every revocation check with
|
|
57
|
+
* "Connection is closed." until restart. NAMED DEVIATION, better than
|
|
58
|
+
* upstream, whose Redis stores capture `ioConnection` once. A client handed
|
|
59
|
+
* in directly is kept whatever its state.
|
|
52
60
|
*/
|
|
53
61
|
async #client(): Promise<RedisLikeClient> {
|
|
62
|
+
if (typeof this.#source === "function" && hasEnded(this.#resolved)) {
|
|
63
|
+
this.#resolved = undefined;
|
|
64
|
+
}
|
|
54
65
|
if (this.#resolved) return this.#resolved;
|
|
55
66
|
if (typeof this.#source !== "function") {
|
|
56
67
|
this.#resolved = this.#source;
|
package/src/RefreshTokenStore.ts
CHANGED
|
@@ -1,26 +1,49 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* RefreshTokenStore — server-side opaque refresh token management.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Opaque token pattern:
|
|
5
5
|
* { accessToken, refreshToken, expiresIn }
|
|
6
6
|
* POST /auth/refresh → new pair, old token invalidated
|
|
7
7
|
*
|
|
8
|
+
* A refresh token is a bearer credential, so only `sha256(value)` is
|
|
9
|
+
* persisted, like access tokens, remember-me tokens, OTPs and backup codes: a
|
|
10
|
+
* dump of the table is not a set of working tokens. The driver is keyed by
|
|
11
|
+
* that hash and never sees the value; the application hashes what the client
|
|
12
|
+
* presents with {@link hashRefreshToken} before asking the driver.
|
|
13
|
+
*
|
|
14
|
+
* Cutover from a store that held the value itself: fail closed. Rows written
|
|
15
|
+
* before hashing are keyed by the clear value and no presented token hashes
|
|
16
|
+
* to it, so they simply stop refreshing and those clients sign in again.
|
|
17
|
+
* Nothing re-reads a clear value to upgrade it: that would keep the clear
|
|
18
|
+
* column, the very thing this removes, readable as a credential.
|
|
19
|
+
*
|
|
8
20
|
* @implements MISS-5
|
|
9
21
|
*/
|
|
10
22
|
|
|
11
23
|
import { randomBytes } from "node:crypto";
|
|
24
|
+
import { WardenError } from "./errors.js";
|
|
25
|
+
import { hashSecret } from "./RememberMeToken.js";
|
|
12
26
|
|
|
13
27
|
export interface StoredRefreshToken {
|
|
14
|
-
token
|
|
28
|
+
/** `sha256(value)`, hex. The token itself is never stored. */
|
|
29
|
+
hash: string;
|
|
15
30
|
userId: string | number;
|
|
16
31
|
expiresAt: number;
|
|
17
32
|
createdAt: number;
|
|
18
33
|
}
|
|
19
34
|
|
|
35
|
+
/**
|
|
36
|
+
* What a store implements. Every token argument is the HASH from
|
|
37
|
+
* {@link hashRefreshToken}, never the value the client holds.
|
|
38
|
+
*/
|
|
20
39
|
export interface RefreshTokenDriver {
|
|
21
40
|
store(token: StoredRefreshToken): Promise<void>;
|
|
22
|
-
find(
|
|
23
|
-
revoke(
|
|
41
|
+
find(hash: string): Promise<StoredRefreshToken | null>;
|
|
42
|
+
revoke(hash: string): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Remove every token of `userId`. Ids are compared as strings: a row
|
|
45
|
+
* stored with `"1"` belongs to user `1`.
|
|
46
|
+
*/
|
|
24
47
|
revokeAllForUser(userId: string | number): Promise<void>;
|
|
25
48
|
cleanup(): Promise<void>;
|
|
26
49
|
}
|
|
@@ -30,33 +53,36 @@ export class MemoryRefreshTokenDriver implements RefreshTokenDriver {
|
|
|
30
53
|
#tokens: Map<string, StoredRefreshToken> = new Map();
|
|
31
54
|
|
|
32
55
|
async store(token: StoredRefreshToken): Promise<void> {
|
|
33
|
-
this.#tokens.set(token.
|
|
56
|
+
this.#tokens.set(token.hash, token);
|
|
34
57
|
}
|
|
35
58
|
|
|
36
|
-
async find(
|
|
37
|
-
const stored = this.#tokens.get(
|
|
59
|
+
async find(hash: string): Promise<StoredRefreshToken | null> {
|
|
60
|
+
const stored = this.#tokens.get(hash);
|
|
38
61
|
if (!stored) return null;
|
|
39
|
-
|
|
40
|
-
|
|
62
|
+
// "Not in the future" rather than "in the past": an expiry that is not
|
|
63
|
+
// a number counts as expired instead of as never.
|
|
64
|
+
if (!(stored.expiresAt > Date.now())) {
|
|
65
|
+
this.#tokens.delete(hash);
|
|
41
66
|
return null;
|
|
42
67
|
}
|
|
43
68
|
return stored;
|
|
44
69
|
}
|
|
45
70
|
|
|
46
|
-
async revoke(
|
|
47
|
-
this.#tokens.delete(
|
|
71
|
+
async revoke(hash: string): Promise<void> {
|
|
72
|
+
this.#tokens.delete(hash);
|
|
48
73
|
}
|
|
49
74
|
|
|
50
75
|
async revokeAllForUser(userId: string | number): Promise<void> {
|
|
76
|
+
const owner = String(userId);
|
|
51
77
|
for (const [key, val] of this.#tokens) {
|
|
52
|
-
if (val.userId ===
|
|
78
|
+
if (String(val.userId) === owner) this.#tokens.delete(key);
|
|
53
79
|
}
|
|
54
80
|
}
|
|
55
81
|
|
|
56
82
|
async cleanup(): Promise<void> {
|
|
57
83
|
const now = Date.now();
|
|
58
84
|
for (const [key, val] of this.#tokens) {
|
|
59
|
-
if (val.expiresAt
|
|
85
|
+
if (!(val.expiresAt > now)) this.#tokens.delete(key);
|
|
60
86
|
}
|
|
61
87
|
}
|
|
62
88
|
}
|
|
@@ -65,3 +91,43 @@ export class MemoryRefreshTokenDriver implements RefreshTokenDriver {
|
|
|
65
91
|
export function generateRefreshToken(): string {
|
|
66
92
|
return randomBytes(48).toString("base64url");
|
|
67
93
|
}
|
|
94
|
+
|
|
95
|
+
/** `sha256(value)` as hex: what is stored, and what the driver is asked for. */
|
|
96
|
+
export function hashRefreshToken(value: string): string {
|
|
97
|
+
return hashSecret(value);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A freshly minted refresh token: what to store, and what to hand the client. */
|
|
101
|
+
export interface MintedRefreshToken {
|
|
102
|
+
stored: StoredRefreshToken;
|
|
103
|
+
/** Goes to the client. Never persisted. */
|
|
104
|
+
value: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Mint a refresh token for `userId`, valid for `ttlSeconds`. */
|
|
108
|
+
export function mintRefreshToken(
|
|
109
|
+
userId: string | number,
|
|
110
|
+
ttlSeconds: number,
|
|
111
|
+
): MintedRefreshToken {
|
|
112
|
+
// NaN or Infinity is not a lifetime: the row would never expire.
|
|
113
|
+
if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {
|
|
114
|
+
throw new WardenError(
|
|
115
|
+
"E_WARDEN_TOKEN_TTL_INVALID",
|
|
116
|
+
`ttlSeconds must be a positive finite number, got ${String(ttlSeconds)}.`,
|
|
117
|
+
{
|
|
118
|
+
hint: "Give the refresh token a lifetime in seconds, e.g. 2592000 (30 days).",
|
|
119
|
+
},
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
const value = generateRefreshToken();
|
|
123
|
+
const now = Date.now();
|
|
124
|
+
return {
|
|
125
|
+
stored: {
|
|
126
|
+
hash: hashRefreshToken(value),
|
|
127
|
+
userId,
|
|
128
|
+
expiresAt: now + ttlSeconds * 1000,
|
|
129
|
+
createdAt: now,
|
|
130
|
+
},
|
|
131
|
+
value,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
@@ -108,7 +108,8 @@ export class ResilientBlacklistDriver implements BlacklistDriver {
|
|
|
108
108
|
// The fallback first, and unconditionally: it is what this instance
|
|
109
109
|
// knows it revoked. Recording only on failure left every revocation made
|
|
110
110
|
// while the primary was healthy invisible to the fallback — and those are
|
|
111
|
-
// most of them.
|
|
111
|
+
// most of them. The default fallback sweeps expired entries on write,
|
|
112
|
+
// so recording every revocation keeps only the live ones.
|
|
112
113
|
await this.#fallback.add(jti, expiresAt);
|
|
113
114
|
try {
|
|
114
115
|
await this.#primary.add(jti, expiresAt);
|
package/src/TokenBlacklist.ts
CHANGED
|
@@ -16,12 +16,34 @@ export interface BlacklistDriver {
|
|
|
16
16
|
cleanup?(): Promise<void>;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
/** In-memory blacklist for development. */
|
|
19
|
+
/** In-memory blacklist for development, and the resilient driver's fallback. */
|
|
20
20
|
export class MemoryBlacklistDriver implements BlacklistDriver {
|
|
21
21
|
#entries: Map<string, number> = new Map();
|
|
22
22
|
|
|
23
|
+
/**
|
|
24
|
+
* Size at which the next sweep runs, doubling each time.
|
|
25
|
+
*
|
|
26
|
+
* Expired entries used to leave only on a `has()` of that exact jti or an
|
|
27
|
+
* explicit `cleanup()`, which nothing calls. Every logout and every
|
|
28
|
+
* `revoke()` added one, and `ResilientBlacklistDriver` writes every
|
|
29
|
+
* revocation into this store, so a long-lived process grew without bound.
|
|
30
|
+
* Sweeping on write bounds the map by the revocations still live, without
|
|
31
|
+
* a timer that would hold the event loop open. There is no ceiling that
|
|
32
|
+
* evicts: dropping a live entry would un-revoke a token.
|
|
33
|
+
*/
|
|
34
|
+
#sweepAt = 64;
|
|
35
|
+
|
|
36
|
+
/** Entries currently held, live or not yet swept. */
|
|
37
|
+
get size(): number {
|
|
38
|
+
return this.#entries.size;
|
|
39
|
+
}
|
|
40
|
+
|
|
23
41
|
async add(jti: string, expiresAt: number): Promise<void> {
|
|
42
|
+
// Already past its deadline: `has()` would answer false for it anyway,
|
|
43
|
+
// so storing it only costs memory.
|
|
44
|
+
if (expiresAt < Date.now()) return;
|
|
24
45
|
this.#entries.set(jti, expiresAt);
|
|
46
|
+
if (this.#entries.size > this.#sweepAt) this.#sweep();
|
|
25
47
|
}
|
|
26
48
|
|
|
27
49
|
async has(jti: string): Promise<boolean> {
|
|
@@ -35,10 +57,15 @@ export class MemoryBlacklistDriver implements BlacklistDriver {
|
|
|
35
57
|
}
|
|
36
58
|
|
|
37
59
|
async cleanup(): Promise<void> {
|
|
60
|
+
this.#sweep();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
#sweep(): void {
|
|
38
64
|
const now = Date.now();
|
|
39
65
|
for (const [jti, exp] of this.#entries) {
|
|
40
66
|
if (exp < now) this.#entries.delete(jti);
|
|
41
67
|
}
|
|
68
|
+
this.#sweepAt = Math.max(64, this.#entries.size * 2);
|
|
42
69
|
}
|
|
43
70
|
}
|
|
44
71
|
|