@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/middleware.ts
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import { Authenticator } from "./Authenticator.js";
|
|
20
|
-
import { AuthManager, type UserPayload } from "./AuthManager.js";
|
|
20
|
+
import { AuthManager, tokenAllows, type UserPayload } from "./AuthManager.js";
|
|
21
21
|
import type { BasePolicy } from "./bouncer/BasePolicy.js";
|
|
22
22
|
import { Bouncer } from "./bouncer/Bouncer.js";
|
|
23
23
|
import type { Ability, PolicyContainerResolver } from "./bouncer/types.js";
|
|
@@ -176,11 +176,24 @@ export interface WardenContext {
|
|
|
176
176
|
[key: string]: unknown;
|
|
177
177
|
};
|
|
178
178
|
roles?: string[];
|
|
179
|
+
/** What the payload carries — not an authorization input. */
|
|
179
180
|
permissions?: string[];
|
|
180
|
-
|
|
181
|
+
/**
|
|
182
|
+
* The permission check a gate must use: resolved through the rights
|
|
183
|
+
* resolver and narrowed by the request's access token. Optional, like the
|
|
184
|
+
* rest of this structural slot, so a host's own auth state still fits.
|
|
185
|
+
*/
|
|
186
|
+
hasPermission?(permission: string, scope?: Scope): Promise<boolean>;
|
|
187
|
+
/** {@link hasPermission} for a list: true only when every one holds. */
|
|
188
|
+
hasAllPermissions?(
|
|
189
|
+
permissions: readonly string[],
|
|
190
|
+
scope?: Scope,
|
|
191
|
+
): Promise<boolean>;
|
|
192
|
+
/** Resolves to the user (warden's Authenticator); a host's may resolve to nothing. */
|
|
193
|
+
authenticate?(): Promise<unknown>;
|
|
181
194
|
check?(): Promise<boolean>;
|
|
182
195
|
getUserOrFail?(): { id: string; [key: string]: unknown } | undefined;
|
|
183
|
-
use?(name
|
|
196
|
+
use?(name?: string): unknown;
|
|
184
197
|
readonly authenticationAttempted?: boolean;
|
|
185
198
|
};
|
|
186
199
|
/**
|
|
@@ -245,10 +258,21 @@ export async function wardenMiddleware(ctx: WardenContext, next: WardenNext) {
|
|
|
245
258
|
// (fail-open) — the exact bug this precedence prevents.
|
|
246
259
|
const controller = ctx.route?.controller ?? ctx.controller;
|
|
247
260
|
const action = ctx.route?.action ?? ctx.action;
|
|
248
|
-
const
|
|
261
|
+
const declared =
|
|
249
262
|
controller && action ? getGuardMetadata(controller, action) : [];
|
|
263
|
+
// `@Role`, `@Permission` and `@RequireMfa` say who may run the action, which
|
|
264
|
+
// presupposes knowing who is asking: without `@Guard` beside them they imply
|
|
265
|
+
// the default guard. Reading them only under `@Guard` left a route declaring
|
|
266
|
+
// `@Role('admin')` alone open to anonymous requests.
|
|
267
|
+
const strategies =
|
|
268
|
+
declared.length === 0 &&
|
|
269
|
+
controller &&
|
|
270
|
+
action &&
|
|
271
|
+
requiresAuthorization(controller, action)
|
|
272
|
+
? [auth.defaultStrategyName]
|
|
273
|
+
: declared;
|
|
250
274
|
|
|
251
|
-
// No guard
|
|
275
|
+
// No guard and no authorization decorator — pass through (public endpoint).
|
|
252
276
|
if (strategies.length === 0) {
|
|
253
277
|
await next();
|
|
254
278
|
return;
|
|
@@ -321,6 +345,18 @@ export async function wardenMiddleware(ctx: WardenContext, next: WardenNext) {
|
|
|
321
345
|
await next();
|
|
322
346
|
}
|
|
323
347
|
|
|
348
|
+
/** Whether the action carries any decorator that restricts who may run it. */
|
|
349
|
+
function requiresAuthorization(
|
|
350
|
+
controller: object,
|
|
351
|
+
action: string | symbol,
|
|
352
|
+
): boolean {
|
|
353
|
+
return (
|
|
354
|
+
getRoleMetadata(controller, action).length > 0 ||
|
|
355
|
+
getPermissionMetadata(controller, action).length > 0 ||
|
|
356
|
+
getRequireMfaMetadata(controller, action)
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
324
360
|
/**
|
|
325
361
|
* Silent auth middleware (AdonisJS `silent_auth` parity) — a GLOBAL middleware
|
|
326
362
|
* that populates `ctx.auth` from the request's credentials when they're valid,
|
|
@@ -456,7 +492,7 @@ export interface BouncerRegistry {
|
|
|
456
492
|
* from the authenticated user (`ctx.auth?.user`, or `null` for a guest), the
|
|
457
493
|
* shared `RightsResolver`, and the registered abilities/policies, then attaches
|
|
458
494
|
* it as `ctx.bouncer`. Handlers authorize via `await ctx.bouncer.authorize(...)`
|
|
459
|
-
* (throws `
|
|
495
|
+
* (throws `E_AUTHORIZATION_FAILURE` carrying `status: 403`, which the host's
|
|
460
496
|
* ExceptionHandler maps to a 403 response) or branch on `ctx.bouncer.allows(...)`.
|
|
461
497
|
*
|
|
462
498
|
* Unlike `wardenMiddleware` (a per-route GUARD that short-circuits public
|
|
@@ -472,11 +508,15 @@ export async function initializeBouncer(ctx: WardenContext, next: WardenNext) {
|
|
|
472
508
|
const candidate = await tryResolve(ctx, "bouncer:registry");
|
|
473
509
|
const registry = isBouncerRegistry(candidate) ? candidate : undefined;
|
|
474
510
|
|
|
475
|
-
const user = ctx.auth?.user ?? null;
|
|
476
511
|
const scope: Scope = registry?.resolveScope
|
|
477
512
|
? await registry.resolveScope(toScopeContext(ctx))
|
|
478
513
|
: "global";
|
|
479
514
|
|
|
515
|
+
// The user is read when the first check runs, not now: a handler that
|
|
516
|
+
// authenticates itself (`await ctx.auth.authenticate()`) and then
|
|
517
|
+
// authorizes must be judged as the user it just signed in, not as the
|
|
518
|
+
// guest this middleware saw.
|
|
519
|
+
const user = (): UserPayload | null => ctx.auth?.user ?? null;
|
|
480
520
|
const bouncer = new Bouncer(user, registry?.abilities, registry?.policies, {
|
|
481
521
|
scope,
|
|
482
522
|
resolver,
|
|
@@ -545,7 +585,11 @@ async function checkAuthorization(
|
|
|
545
585
|
}
|
|
546
586
|
const effective = await auth.resolvePermissions(user, scope);
|
|
547
587
|
if (requiredPermissions.length > 0) {
|
|
548
|
-
|
|
588
|
+
// The user must hold it, and the token the request came in with, if
|
|
589
|
+
// any, must allow it: an intersection, never a union.
|
|
590
|
+
const missing = requiredPermissions.filter(
|
|
591
|
+
(p) => !effective.has(p) || !tokenAllows(user, p),
|
|
592
|
+
);
|
|
549
593
|
if (missing.length > 0) return `Missing permissions: ${missing.join(", ")}`;
|
|
550
594
|
}
|
|
551
595
|
if (requiredRoles.length > 0) {
|
package/src/native.ts
CHANGED
|
@@ -5,25 +5,41 @@
|
|
|
5
5
|
* other consumer) throws `E_WARDEN_NAPI_REQUIRED` at use time. Password
|
|
6
6
|
* hashing is the sole responsibility of `@c9up/sigil` (story 40.1).
|
|
7
7
|
*/
|
|
8
|
-
import { loadNativeBinary } from "./vendor/nativeBinary.js";
|
|
8
|
+
import { hasFunctions, loadNativeBinary } from "./vendor/nativeBinary.js";
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
11
|
+
* What this package calls on the engine, typed as the Rust declares it.
|
|
12
12
|
*
|
|
13
13
|
* Derived from `./native/generated.js` — written by `pnpm build:napi-types`
|
|
14
14
|
* from napi-derive's own `type-def` output — rather than restated here, where
|
|
15
15
|
* nothing would notice a `pub fn` gaining a parameter or changing its return.
|
|
16
16
|
*/
|
|
17
|
-
|
|
17
|
+
const NATIVE_CALLS = ["jwtSign", "jwtVerify"] as const;
|
|
18
|
+
|
|
19
|
+
export type NativeWarden = Pick<
|
|
20
|
+
typeof import("./native/generated.js"),
|
|
21
|
+
(typeof NATIVE_CALLS)[number]
|
|
22
|
+
>;
|
|
23
|
+
|
|
24
|
+
/** What the package calls, checked at load: a stale binary loads just as well. */
|
|
25
|
+
function isNativeWarden(value: unknown): value is NativeWarden {
|
|
26
|
+
return hasFunctions(value, NATIVE_CALLS);
|
|
27
|
+
}
|
|
18
28
|
|
|
19
29
|
// Absent is not an error here: `JwtStrategy` throws E_WARDEN_NAPI_REQUIRED at
|
|
20
30
|
// use time, which names what the caller was trying to do. The loader reports
|
|
21
31
|
// what happened and this decides — the platform table itself is shared, since
|
|
22
32
|
// a package that misses a new target fails only on that platform.
|
|
23
|
-
const attempt = loadNativeBinary
|
|
33
|
+
const attempt = loadNativeBinary(isNativeWarden, NATIVE_CALLS);
|
|
24
34
|
const native = attempt.loaded ? attempt.binary : undefined;
|
|
35
|
+
const loadError = attempt.loaded ? undefined : attempt.cause;
|
|
25
36
|
|
|
26
37
|
/** Get the native engine. Returns undefined if not loaded — caller must throw. */
|
|
27
38
|
export function nativeWarden(): NativeWarden | undefined {
|
|
28
39
|
return native;
|
|
29
40
|
}
|
|
41
|
+
|
|
42
|
+
/** Why the engine is not loaded, for the `cause` of the error a caller throws. */
|
|
43
|
+
export function nativeWardenLoadError(): unknown {
|
|
44
|
+
return loadError;
|
|
45
|
+
}
|
package/src/quasar.ts
CHANGED
|
@@ -9,12 +9,22 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import type { RedisLikeClient } from "./RedisBlacklistDriver.js";
|
|
12
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
hasCommands,
|
|
14
|
+
quasarConnection as loadQuasarConnection,
|
|
15
|
+
} from "./vendor/quasarConnection.js";
|
|
13
16
|
|
|
14
17
|
// Only what the driver documents itself as needing: `set` with an "EX" ttl,
|
|
15
18
|
// and `exists`. Demanding key scans here would reject a client that works.
|
|
16
19
|
const REQUIRED = ["set", "exists"] as const;
|
|
17
20
|
|
|
21
|
+
/**
|
|
22
|
+
* The connection is handed over only once it carries every command above.
|
|
23
|
+
*/
|
|
24
|
+
function isRedisLikeClient(value: unknown): value is RedisLikeClient {
|
|
25
|
+
return hasCommands(value, REQUIRED);
|
|
26
|
+
}
|
|
27
|
+
|
|
18
28
|
/**
|
|
19
29
|
* A resolver — quasar is loaded on first use, not at config time.
|
|
20
30
|
*/
|
|
@@ -22,10 +32,11 @@ export function quasarConnection(
|
|
|
22
32
|
name?: string,
|
|
23
33
|
): () => Promise<RedisLikeClient> {
|
|
24
34
|
return async () =>
|
|
25
|
-
loadQuasarConnection
|
|
35
|
+
loadQuasarConnection({
|
|
26
36
|
pkg: "warden",
|
|
27
37
|
name,
|
|
28
38
|
required: REQUIRED,
|
|
39
|
+
isConnection: isRedisLikeClient,
|
|
29
40
|
what: "the token blacklist",
|
|
30
41
|
raise: (_reason, message, cause) => new Error(message, { cause }),
|
|
31
42
|
});
|
|
@@ -43,6 +43,33 @@ class ResolvedPermissions implements EffectivePermissions {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
/**
|
|
47
|
+
* `effective` as the REQUEST may use it: when the user came in with an access
|
|
48
|
+
* token, every permission must also be allowed by that token.
|
|
49
|
+
*
|
|
50
|
+
* The one place the intersection happens for a resolved set, so the coarse
|
|
51
|
+
* helpers (`AuthManager.hasPermission`, the decorator gate) and a policy's
|
|
52
|
+
* `this.permissions` cannot answer differently for the same request. Roles stay
|
|
53
|
+
* the user's: a token restricts what may be DONE, not who the user is.
|
|
54
|
+
*/
|
|
55
|
+
export function narrowToAccessToken(
|
|
56
|
+
effective: EffectivePermissions,
|
|
57
|
+
user: UserPayload,
|
|
58
|
+
): EffectivePermissions {
|
|
59
|
+
const token = user.currentAccessToken;
|
|
60
|
+
if (token === undefined) return effective;
|
|
61
|
+
const allowed = (permission: string): boolean =>
|
|
62
|
+
effective.has(permission) && token.allows(permission);
|
|
63
|
+
return {
|
|
64
|
+
has: allowed,
|
|
65
|
+
hasAll: (permissions) => permissions.every(allowed),
|
|
66
|
+
hasAny: (permissions) => permissions.some(allowed),
|
|
67
|
+
permissions: new Set([...effective.permissions].filter(allowed)),
|
|
68
|
+
roles: effective.roles,
|
|
69
|
+
scope: effective.scope,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
46
73
|
export class RightsResolver {
|
|
47
74
|
constructor(private readonly store: RightsStore) {}
|
|
48
75
|
|
package/src/sanitize.ts
CHANGED
|
@@ -10,8 +10,10 @@ import type { UserPayload } from "./AuthManager.js";
|
|
|
10
10
|
|
|
11
11
|
export function sanitizePayload(user: UserPayload): void {
|
|
12
12
|
for (const key of ["__proto__", "constructor", "prototype"]) {
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
// Own keys only: `constructor` is always reachable through the
|
|
14
|
+
// prototype, and deleting an inherited name is a no-op anyway.
|
|
15
|
+
if (Object.hasOwn(user, key)) {
|
|
16
|
+
delete user[key];
|
|
15
17
|
}
|
|
16
18
|
}
|
|
17
19
|
}
|
package/src/services/main.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import type { AuthManager } from "../AuthManager.js";
|
|
14
|
+
import { WardenError } from "../errors.js";
|
|
14
15
|
|
|
15
16
|
let instance: AuthManager | undefined;
|
|
16
17
|
|
|
@@ -37,10 +38,21 @@ export function clearAuth(): void {
|
|
|
37
38
|
instance = undefined;
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
|
|
41
|
+
// The target is never read through — every trap forwards to `instance`.
|
|
42
|
+
const target: AuthManager = Object.create(null);
|
|
43
|
+
|
|
44
|
+
const auth: AuthManager = new Proxy(target, {
|
|
41
45
|
get(_target, prop) {
|
|
46
|
+
// Whatever inspects a value before using it reads `then` (a promise or an
|
|
47
|
+
// async factory resolving with it decides whether it is thenable) and
|
|
48
|
+
// symbols (inspection, coercion, module interop). None is a member of
|
|
49
|
+
// AuthManager, so answer undefined and let a genuine access report.
|
|
50
|
+
if (typeof prop === "symbol" || prop === "then") {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
42
53
|
if (!instance) {
|
|
43
|
-
throw new
|
|
54
|
+
throw new WardenError(
|
|
55
|
+
"NOT_BOOTED",
|
|
44
56
|
"[warden] AuthManager singleton accessed before WardenProvider.boot() ran. " +
|
|
45
57
|
"Check that `@c9up/warden/provider` is listed in your reamrc.ts providers.",
|
|
46
58
|
);
|
package/src/standalone.ts
CHANGED
|
@@ -23,11 +23,29 @@ import {
|
|
|
23
23
|
type AuthStrategy,
|
|
24
24
|
type UserPayload,
|
|
25
25
|
} from "./AuthManager.js";
|
|
26
|
+
import { readBearerToken } from "./bearer.js";
|
|
26
27
|
import type { WardenConfig } from "./config.js";
|
|
27
28
|
import { ApiKeyStrategy } from "./strategies/ApiKeyStrategy.js";
|
|
28
29
|
import { JwtStrategy } from "./strategies/JwtStrategy.js";
|
|
29
30
|
import { SessionStrategy } from "./strategies/SessionStrategy.js";
|
|
30
31
|
|
|
32
|
+
/**
|
|
33
|
+
* The slice of an Express-style request the middleware reads and writes.
|
|
34
|
+
* Structural, so an Express, Connect or Polka request fits without a cast.
|
|
35
|
+
*/
|
|
36
|
+
export interface StandaloneRequest {
|
|
37
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
38
|
+
/** The verification result, set on success. */
|
|
39
|
+
auth?: AuthResult;
|
|
40
|
+
/** The authenticated user, set on success (Express convention). */
|
|
41
|
+
user?: UserPayload;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The slice of an Express-style response the middleware writes to. */
|
|
45
|
+
export interface StandaloneResponse {
|
|
46
|
+
status(code: number): { json(body: unknown): unknown };
|
|
47
|
+
}
|
|
48
|
+
|
|
31
49
|
export interface Warden {
|
|
32
50
|
/** Verify a bearer token. Returns auth result with user payload. */
|
|
33
51
|
verify(token: string, strategy?: string): Promise<AuthResult>;
|
|
@@ -36,18 +54,32 @@ export interface Warden {
|
|
|
36
54
|
credentials: Record<string, unknown>,
|
|
37
55
|
strategy?: string,
|
|
38
56
|
): Promise<AuthResult>;
|
|
39
|
-
/**
|
|
40
|
-
|
|
57
|
+
/**
|
|
58
|
+
* Mint a token for a user through a token-issuing guard: the one named, or
|
|
59
|
+
* the default guard. Rejects with `E_WARDEN_STRATEGY_CANNOT_ISSUE` when that
|
|
60
|
+
* guard mints no tokens (a session guard, an access-tokens guard).
|
|
61
|
+
*/
|
|
62
|
+
generateToken(user: UserPayload, guard?: string): Promise<string>;
|
|
41
63
|
/** The underlying AuthManager for advanced use. */
|
|
42
64
|
manager: AuthManager;
|
|
43
65
|
/** Express middleware — extracts Bearer token, verifies, attaches `req.auth`. */
|
|
44
66
|
expressMiddleware(): (
|
|
45
|
-
req:
|
|
46
|
-
res:
|
|
67
|
+
req: StandaloneRequest,
|
|
68
|
+
res: StandaloneResponse,
|
|
47
69
|
next: () => void,
|
|
48
70
|
) => void;
|
|
49
71
|
}
|
|
50
72
|
|
|
73
|
+
/** Send one JSON error, shaped like the Ream middleware's. */
|
|
74
|
+
function fail(
|
|
75
|
+
res: StandaloneResponse,
|
|
76
|
+
status: number,
|
|
77
|
+
code: string,
|
|
78
|
+
message: string,
|
|
79
|
+
): void {
|
|
80
|
+
res.status(status).json({ error: { code, message } });
|
|
81
|
+
}
|
|
82
|
+
|
|
51
83
|
/**
|
|
52
84
|
* Create a standalone Warden instance — no Ream container needed.
|
|
53
85
|
*/
|
|
@@ -86,46 +118,54 @@ export function createWarden(config: WardenConfig): Warden {
|
|
|
86
118
|
authenticate: (credentials, strategy) =>
|
|
87
119
|
manager.authenticate(credentials, strategy),
|
|
88
120
|
|
|
89
|
-
async generateToken(user: UserPayload): Promise<string> {
|
|
90
|
-
|
|
91
|
-
|
|
121
|
+
async generateToken(user: UserPayload, guard?: string): Promise<string> {
|
|
122
|
+
// The guard the application configured, not one named `jwt`: a
|
|
123
|
+
// `guards: { api: jwtGuard(...) }` config has no guard by that name.
|
|
124
|
+
return manager.issueFor(user, guard);
|
|
92
125
|
},
|
|
93
126
|
|
|
94
127
|
manager,
|
|
95
128
|
|
|
96
129
|
expressMiddleware() {
|
|
97
130
|
return (req, res, next) => {
|
|
98
|
-
const
|
|
99
|
-
const authHeader = headers?.authorization ?? "";
|
|
100
|
-
const token =
|
|
101
|
-
typeof authHeader === "string" && authHeader.startsWith("Bearer ")
|
|
102
|
-
? authHeader.slice(7)
|
|
103
|
-
: "";
|
|
131
|
+
const token = readBearerToken(req.headers?.authorization);
|
|
104
132
|
|
|
105
133
|
if (!token) {
|
|
106
|
-
(
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
},
|
|
113
|
-
});
|
|
134
|
+
fail(
|
|
135
|
+
res,
|
|
136
|
+
401,
|
|
137
|
+
"E_WARDEN_UNAUTHORIZED",
|
|
138
|
+
"Missing authentication token",
|
|
139
|
+
);
|
|
114
140
|
return;
|
|
115
141
|
}
|
|
116
142
|
|
|
117
143
|
manager
|
|
118
144
|
.verify(token)
|
|
119
145
|
.then((result) => {
|
|
146
|
+
if (result.strategyCrash === true) {
|
|
147
|
+
// The guard threw — a database down, a bug — which is a
|
|
148
|
+
// server incident, not a bad credential: a 500, and a
|
|
149
|
+
// generic message. The thrown text (a host, a port, a
|
|
150
|
+
// query) is for the logs, never for the client.
|
|
151
|
+
console.error(
|
|
152
|
+
`[warden] strategy threw during verify(): ${result.error ?? "unknown error"}`,
|
|
153
|
+
);
|
|
154
|
+
fail(
|
|
155
|
+
res,
|
|
156
|
+
500,
|
|
157
|
+
"E_WARDEN_AUTH_STRATEGY_ERROR",
|
|
158
|
+
"Authentication unavailable. Check server logs.",
|
|
159
|
+
);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
120
162
|
if (!result.authenticated || !result.user) {
|
|
121
|
-
(
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
},
|
|
128
|
-
});
|
|
163
|
+
fail(
|
|
164
|
+
res,
|
|
165
|
+
401,
|
|
166
|
+
"E_WARDEN_UNAUTHORIZED",
|
|
167
|
+
result.error ?? "Authentication failed",
|
|
168
|
+
);
|
|
129
169
|
return;
|
|
130
170
|
}
|
|
131
171
|
// Attach auth result to the request object (Express convention).
|
|
@@ -134,14 +174,12 @@ export function createWarden(config: WardenConfig): Warden {
|
|
|
134
174
|
next();
|
|
135
175
|
})
|
|
136
176
|
.catch(() => {
|
|
137
|
-
(
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
},
|
|
144
|
-
});
|
|
177
|
+
fail(
|
|
178
|
+
res,
|
|
179
|
+
500,
|
|
180
|
+
"E_WARDEN_AUTH_ERROR",
|
|
181
|
+
"Internal authentication error",
|
|
182
|
+
);
|
|
145
183
|
});
|
|
146
184
|
};
|
|
147
185
|
},
|
|
@@ -1,23 +1,54 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Access-tokens authentication strategy (opaque API tokens).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Reads the token from `Authorization: Bearer <token>` or the configured
|
|
5
|
+
* header (`x-api-key` by default), verifies it through an access-tokens
|
|
6
|
+
* provider — which stores only a hash, compares in constant time and checks
|
|
7
|
+
* expiry — then loads the user it belongs to.
|
|
8
|
+
*
|
|
9
|
+
* The token's abilities stay ON THE TOKEN: the user is handed to the request
|
|
10
|
+
* with `currentAccessToken`, and a handler asks it
|
|
11
|
+
* (`ctx.auth.user.currentAccessToken.allows('orders:write')`). They are never
|
|
12
|
+
* merged into `user.permissions`, which holds the user's own permissions: a
|
|
13
|
+
* token whose ability happened to share a permission's name would otherwise
|
|
14
|
+
* grant that permission to a user who does not hold it, and a token restricted
|
|
15
|
+
* to a few abilities would still carry every permission of its user. Warden's
|
|
16
|
+
* permission checks (`@Permission`, `hasPermission`) require both: the user's
|
|
17
|
+
* permission AND the token's ability (`tokenAllows`).
|
|
5
18
|
*
|
|
6
19
|
* @implements MISS-8
|
|
7
20
|
*/
|
|
8
21
|
|
|
22
|
+
import type {
|
|
23
|
+
AccessToken,
|
|
24
|
+
AccessTokensProviderContract,
|
|
25
|
+
CreateAccessTokenOptions,
|
|
26
|
+
TokenOwner,
|
|
27
|
+
} from "../AccessToken.js";
|
|
9
28
|
import type {
|
|
10
29
|
AuthClientResponse,
|
|
11
30
|
AuthResult,
|
|
12
31
|
AuthStrategy,
|
|
13
32
|
UserPayload,
|
|
14
33
|
} from "../AuthManager.js";
|
|
34
|
+
import { WardenError } from "../errors.js";
|
|
35
|
+
import { Secret } from "../Secret.js";
|
|
15
36
|
|
|
16
37
|
export interface ApiKeyConfig {
|
|
38
|
+
/** Header read beside `Authorization: Bearer`. Default `x-api-key`. */
|
|
17
39
|
headerName?: string;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Verifies a presented token and mints new ones — an
|
|
42
|
+
* `AccessTokensProvider` over the application's token table, or the
|
|
43
|
+
* application's own implementation of the contract.
|
|
44
|
+
*/
|
|
45
|
+
tokens: AccessTokensProviderContract;
|
|
46
|
+
/**
|
|
47
|
+
* Load the user a verified token belongs to. Called on every request, so a
|
|
48
|
+
* token whose account was deleted or disabled stops working: answer `null`
|
|
49
|
+
* and the request is refused.
|
|
50
|
+
*/
|
|
51
|
+
findUser: (id: string | number) => Promise<UserPayload | null>;
|
|
21
52
|
}
|
|
22
53
|
|
|
23
54
|
export class ApiKeyStrategy implements AuthStrategy {
|
|
@@ -25,10 +56,28 @@ export class ApiKeyStrategy implements AuthStrategy {
|
|
|
25
56
|
// spelling is still accepted as a guard name / credential trigger by the
|
|
26
57
|
// middleware and providers (see `API_KEY_GUARD_NAMES`) for back-compat.
|
|
27
58
|
name = "access_tokens";
|
|
28
|
-
#config: ApiKeyConfig;
|
|
29
|
-
#headerName: string;
|
|
59
|
+
readonly #config: ApiKeyConfig;
|
|
60
|
+
readonly #headerName: string;
|
|
30
61
|
|
|
31
62
|
constructor(config: ApiKeyConfig) {
|
|
63
|
+
// A config written for the earlier `findByKey` shape has no provider:
|
|
64
|
+
// refused at boot rather than at the first request.
|
|
65
|
+
const tokens: unknown = Reflect.get(Object(config), "tokens");
|
|
66
|
+
if (typeof Reflect.get(Object(tokens), "verify") !== "function") {
|
|
67
|
+
throw new WardenError(
|
|
68
|
+
"INVALID_CONFIG",
|
|
69
|
+
"The access-tokens guard needs `tokens`, a provider that verifies hashed tokens.",
|
|
70
|
+
{
|
|
71
|
+
hint: "apiKeyGuard({ tokens: new AccessTokensProvider({ store }), findUser: (id) => User.find(id) })",
|
|
72
|
+
},
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
if (typeof config.findUser !== "function") {
|
|
76
|
+
throw new WardenError(
|
|
77
|
+
"INVALID_CONFIG",
|
|
78
|
+
"The access-tokens guard needs `findUser`, to load the user a token belongs to.",
|
|
79
|
+
);
|
|
80
|
+
}
|
|
32
81
|
this.#config = config;
|
|
33
82
|
this.#headerName = config.headerName ?? "x-api-key";
|
|
34
83
|
}
|
|
@@ -43,50 +92,76 @@ export class ApiKeyStrategy implements AuthStrategy {
|
|
|
43
92
|
password: string;
|
|
44
93
|
}): Promise<AuthResult> {
|
|
45
94
|
throw new Error(
|
|
46
|
-
"ApiKeyStrategy does not support credential-based auth. Use verify() with the
|
|
95
|
+
"ApiKeyStrategy does not support credential-based auth. Use verify() with the access token.",
|
|
47
96
|
);
|
|
48
97
|
}
|
|
49
98
|
|
|
50
99
|
/**
|
|
51
|
-
*
|
|
52
|
-
* `
|
|
100
|
+
* Mint a token for `user` through the provider. The returned token carries
|
|
101
|
+
* `value` this once: hand it to the client now.
|
|
102
|
+
*/
|
|
103
|
+
createToken(
|
|
104
|
+
user: TokenOwner,
|
|
105
|
+
abilities?: string[],
|
|
106
|
+
options?: CreateAccessTokenOptions,
|
|
107
|
+
): Promise<AccessToken> {
|
|
108
|
+
return this.#config.tokens.create(user, abilities, options);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Revoke the token behind `value`. Answers whether it existed.
|
|
53
113
|
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
114
|
+
* Upstream's guard is built per request and revokes the token it
|
|
115
|
+
* authenticated with, so it takes no argument: that shape is the request's
|
|
116
|
+
* guard, `ctx.auth.use('api').invalidateToken()`. A warden strategy is
|
|
117
|
+
* shared by every request and keeps none of them, so here the value is
|
|
118
|
+
* passed in.
|
|
57
119
|
*/
|
|
58
|
-
|
|
59
|
-
return
|
|
60
|
-
headers: {
|
|
61
|
-
authorization: `Bearer ${key}`,
|
|
62
|
-
[this.#headerName]: key,
|
|
63
|
-
},
|
|
64
|
-
};
|
|
120
|
+
invalidateToken(value: string): Promise<boolean> {
|
|
121
|
+
return this.#config.tokens.invalidate(new Secret(value));
|
|
65
122
|
}
|
|
66
123
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
124
|
+
/**
|
|
125
|
+
* What a test client sends to be `user`: a real token, minted through the
|
|
126
|
+
* provider, so the test authenticates the way the application will.
|
|
127
|
+
*/
|
|
128
|
+
async authenticateAsClient(
|
|
129
|
+
user: TokenOwner,
|
|
130
|
+
abilities?: string[],
|
|
131
|
+
options?: CreateAccessTokenOptions,
|
|
132
|
+
): Promise<AuthClientResponse> {
|
|
133
|
+
const token = await this.createToken(user, abilities, options);
|
|
134
|
+
const value = token.value?.release();
|
|
135
|
+
if (value === undefined) {
|
|
136
|
+
throw new WardenError(
|
|
137
|
+
"INVALID_CONFIG",
|
|
138
|
+
"The token provider returned a token without its value from create().",
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
return { headers: { authorization: `Bearer ${value}` } };
|
|
142
|
+
}
|
|
70
143
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
// `currentAccessToken.allows(scope)` and are NOT consulted by Bouncer
|
|
83
|
-
// ability/policy checks. So an API key carrying `orders.create` is NOT
|
|
84
|
-
// auto-granted by `@Permission('orders.create')` — that's intentional,
|
|
85
|
-
// not a bug. Gate API-key routes on scopes with an explicit app-level
|
|
86
|
-
// check against `ctx.auth.user.permissions`.
|
|
87
|
-
const merged = new Set([...(user.permissions ?? []), ...result.scopes]);
|
|
88
|
-
user.permissions = [...merged];
|
|
144
|
+
async verify(token: string): Promise<AuthResult> {
|
|
145
|
+
const accessToken = await this.#config.tokens.verify(new Secret(token));
|
|
146
|
+
if (accessToken === null) {
|
|
147
|
+
return { authenticated: false, error: "Invalid access token" };
|
|
148
|
+
}
|
|
149
|
+
const user = await this.#config.findUser(accessToken.tokenableId);
|
|
150
|
+
if (!user) {
|
|
151
|
+
return {
|
|
152
|
+
authenticated: false,
|
|
153
|
+
error: "The account behind this token is no longer available",
|
|
154
|
+
};
|
|
89
155
|
}
|
|
90
|
-
|
|
156
|
+
// A copy: the provider's object is the application's, and attaching the
|
|
157
|
+
// token to it would leak one request's token into the next.
|
|
158
|
+
//
|
|
159
|
+
// `mfa` is the step-up of THIS credential, and an access token carries
|
|
160
|
+
// none: whatever `findUser` said (an "MFA enabled" column, typically)
|
|
161
|
+
// must not satisfy `@RequireMfa()`.
|
|
162
|
+
return {
|
|
163
|
+
authenticated: true,
|
|
164
|
+
user: { ...user, currentAccessToken: accessToken, mfa: false },
|
|
165
|
+
};
|
|
91
166
|
}
|
|
92
167
|
}
|