@c9up/warden 0.2.5 → 0.2.6
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 +70 -3
- 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 +26 -12
- package/dist/AttemptStore.js.map +1 -1
- package/dist/AuthManager.d.ts +33 -2
- package/dist/AuthManager.d.ts.map +1 -1
- package/dist/AuthManager.js +23 -2
- package/dist/AuthManager.js.map +1 -1
- package/dist/Authenticator.d.ts +19 -1
- package/dist/Authenticator.d.ts.map +1 -1
- package/dist/Authenticator.js +37 -3
- 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/ResilientBlacklistDriver.d.ts +23 -6
- package/dist/ResilientBlacklistDriver.d.ts.map +1 -1
- package/dist/ResilientBlacklistDriver.js +24 -8
- package/dist/ResilientBlacklistDriver.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/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/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/mfa/MfaManager.d.ts +16 -4
- package/dist/mfa/MfaManager.d.ts.map +1 -1
- package/dist/mfa/MfaManager.js +32 -6
- package/dist/mfa/MfaManager.js.map +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +27 -5
- 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/standalone.d.ts +24 -3
- package/dist/standalone.d.ts.map +1 -1
- package/dist/standalone.js +21 -29
- package/dist/standalone.js.map +1 -1
- package/dist/strategies/ApiKeyStrategy.d.ts +45 -12
- package/dist/strategies/ApiKeyStrategy.d.ts.map +1 -1
- package/dist/strategies/ApiKeyStrategy.js +71 -37
- package/dist/strategies/ApiKeyStrategy.js.map +1 -1
- package/dist/strategies/JwtStrategy.d.ts.map +1 -1
- package/dist/strategies/JwtStrategy.js +3 -3
- package/dist/strategies/JwtStrategy.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 +26 -3
- package/dist/vendor/quasarConnection.d.ts.map +1 -1
- package/dist/vendor/quasarConnection.js +44 -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.win32-x64-msvc.node +0 -0
- package/package.json +7 -2
- package/src/AccessToken.ts +550 -0
- package/src/AttemptStore.ts +29 -13
- package/src/AuthManager.ts +40 -2
- package/src/Authenticator.ts +39 -3
- package/src/Guard.ts +18 -5
- package/src/ResilientBlacklistDriver.ts +28 -8
- package/src/WardenProvider.ts +6 -83
- package/src/config.ts +8 -4
- package/src/index.ts +18 -0
- package/src/mfa/MfaManager.ts +39 -6
- package/src/middleware.ts +36 -5
- package/src/native.ts +20 -4
- package/src/quasar.ts +13 -2
- package/src/standalone.ts +74 -33
- package/src/strategies/ApiKeyStrategy.ts +112 -42
- package/src/strategies/JwtStrategy.ts +3 -1
- package/src/templateTags.ts +117 -0
- package/src/vendor/nativeBinary.ts +82 -6
- package/src/vendor/quasarConnection.ts +84 -22
package/src/Authenticator.ts
CHANGED
|
@@ -545,9 +545,45 @@ export class GuardAccessor {
|
|
|
545
545
|
if (user) user.mfa = true;
|
|
546
546
|
}
|
|
547
547
|
|
|
548
|
-
/**
|
|
549
|
-
|
|
550
|
-
|
|
548
|
+
/**
|
|
549
|
+
* Log the current user out of this guard (session guards).
|
|
550
|
+
*
|
|
551
|
+
* Ends the remember-me credential too, as upstream's session guard does: the
|
|
552
|
+
* cookie is cleared and the stored token behind it deleted. Leaving either
|
|
553
|
+
* meant the next request, with an empty session, was signed straight back
|
|
554
|
+
* in from the cookie.
|
|
555
|
+
*
|
|
556
|
+
* The cookie is cleared first and whatever happens next: a store that fails
|
|
557
|
+
* to delete the row must not leave the browser holding the credential. The
|
|
558
|
+
* store's error is still thrown, after the session is ended, because a token
|
|
559
|
+
* row that survived a logout is something the application has to know about.
|
|
560
|
+
*
|
|
561
|
+
* NAMED DEVIATION — upstream deletes the row only once the presented secret
|
|
562
|
+
* matches it and only for the signed-in user. Here the row is deleted from
|
|
563
|
+
* the identifier the (encrypted) cookie names whatever the secret: a cookie
|
|
564
|
+
* whose secret no longer matches is one a stolen copy already recycled, and
|
|
565
|
+
* a logout from the real browser is exactly when that copy must die.
|
|
566
|
+
*/
|
|
567
|
+
async logout(): Promise<void> {
|
|
568
|
+
const session = this.#requireSession();
|
|
569
|
+
const strategy = strategyOrUndefined(this.#auth, this.#name);
|
|
570
|
+
const issuer =
|
|
571
|
+
strategy && isRememberMeIssuer(strategy) ? strategy : undefined;
|
|
572
|
+
const read = this.#ctx.request.encryptedCookie;
|
|
573
|
+
const cookie =
|
|
574
|
+
issuer && read
|
|
575
|
+
? read.call(this.#ctx.request, issuer.rememberMeCookieName)
|
|
576
|
+
: null;
|
|
577
|
+
this.#clearRememberMe();
|
|
578
|
+
let revocation: Promise<void> = Promise.resolve();
|
|
579
|
+
if (issuer && cookie) {
|
|
580
|
+
revocation = issuer.revokeRememberMeToken(cookie);
|
|
581
|
+
// Observed here so a failing store is not an unhandled rejection
|
|
582
|
+
// while the session is being ended; it is rethrown below.
|
|
583
|
+
revocation.catch(() => undefined);
|
|
584
|
+
}
|
|
585
|
+
await this.#auth.logout(session, this.#name, this.#state);
|
|
586
|
+
await revocation;
|
|
551
587
|
}
|
|
552
588
|
|
|
553
589
|
#requireSession(): SessionStore {
|
package/src/Guard.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @implements FR50, FR51
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
// Side-effect import: registers the `Reflect.defineMetadata` / `
|
|
7
|
+
// Side-effect import: registers the `Reflect.defineMetadata` / `getMetadata`
|
|
8
8
|
// methods used below. Pulled in here (not transitively via the framework)
|
|
9
9
|
// so warden remains self-sufficient when published / consumed standalone.
|
|
10
10
|
import "reflect-metadata";
|
|
@@ -44,12 +44,25 @@ export function Role(...roles: string[]): MethodDecorator {
|
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
/*
|
|
48
|
+
* The readers below walk the prototype chain (`Reflect.getMetadata`), so an
|
|
49
|
+
* action a controller inherits keeps the guard and the authorization its parent
|
|
50
|
+
* declared: `class UsersController extends AdminController {}` routes
|
|
51
|
+
* `[UsersController, 'index']` to a method declared on `AdminController`, and
|
|
52
|
+
* reading only the subclass's own metadata made that route public.
|
|
53
|
+
*
|
|
54
|
+
* The metadata belongs to the action NAME, not to the function: an override
|
|
55
|
+
* that declares nothing inherits its parent's decorators too, so redefining a
|
|
56
|
+
* method can never drop a guard by accident. An override that declares its own
|
|
57
|
+
* decorator replaces the parent's for that decorator.
|
|
58
|
+
*/
|
|
59
|
+
|
|
47
60
|
/** Get guard metadata. */
|
|
48
61
|
export function getGuardMetadata(
|
|
49
62
|
target: object,
|
|
50
63
|
propertyKey: string | symbol,
|
|
51
64
|
): string[] {
|
|
52
|
-
return Reflect.
|
|
65
|
+
return Reflect.getMetadata(GUARD_KEY, target, propertyKey) ?? [];
|
|
53
66
|
}
|
|
54
67
|
|
|
55
68
|
/** Get permission metadata. */
|
|
@@ -57,7 +70,7 @@ export function getPermissionMetadata(
|
|
|
57
70
|
target: object,
|
|
58
71
|
propertyKey: string | symbol,
|
|
59
72
|
): string[] {
|
|
60
|
-
return Reflect.
|
|
73
|
+
return Reflect.getMetadata(PERMISSION_KEY, target, propertyKey) ?? [];
|
|
61
74
|
}
|
|
62
75
|
|
|
63
76
|
/** Get role metadata. */
|
|
@@ -65,7 +78,7 @@ export function getRoleMetadata(
|
|
|
65
78
|
target: object,
|
|
66
79
|
propertyKey: string | symbol,
|
|
67
80
|
): string[] {
|
|
68
|
-
return Reflect.
|
|
81
|
+
return Reflect.getMetadata(ROLE_KEY, target, propertyKey) ?? [];
|
|
69
82
|
}
|
|
70
83
|
|
|
71
84
|
/**
|
|
@@ -85,5 +98,5 @@ export function getRequireMfaMetadata(
|
|
|
85
98
|
target: object,
|
|
86
99
|
propertyKey: string | symbol,
|
|
87
100
|
): boolean {
|
|
88
|
-
return Reflect.
|
|
101
|
+
return Reflect.getMetadata(MFA_KEY, target, propertyKey) ?? false;
|
|
89
102
|
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* `RedisBlacklistDriver`) with an in-memory fallback so a cache outage never
|
|
4
4
|
* takes the whole app down.
|
|
5
5
|
*
|
|
6
|
-
* Policy (fail-
|
|
6
|
+
* Policy (fail-closed on reads, unless `failOpen`):
|
|
7
7
|
* - `add()` — records the revocation in BOTH, always. The fallback is this
|
|
8
8
|
* instance's own record of what it has revoked, not a log of its
|
|
9
9
|
* outages: writing only on failure meant a token revoked while
|
|
@@ -12,11 +12,23 @@
|
|
|
12
12
|
* through. A primary failure still does not fail the logout.
|
|
13
13
|
* - `has()` — asks the fallback FIRST: what this instance revoked is known
|
|
14
14
|
* locally and needs no round trip. Otherwise it asks the
|
|
15
|
-
* primary, and if that throws,
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
15
|
+
* primary, and if that throws, rethrows: the guard asking treats
|
|
16
|
+
* it as a crashed strategy (a 500, or a guest under silent auth),
|
|
17
|
+
* never as "not revoked".
|
|
18
|
+
*
|
|
19
|
+
* Answering "not revoked" (fail-open) assumed every consumer was
|
|
20
|
+
* a short-lived access token. The same blacklist backs a session
|
|
21
|
+
* guard's logout under the cookie store, listed for twice the
|
|
22
|
+
* session lifetime, and JWTs issued for days: during an outage
|
|
23
|
+
* every sign-in revoked by ANOTHER instance, or before this
|
|
24
|
+
* process started, was accepted again. Answering "revoked"
|
|
25
|
+
* instead would not do either: a session guard forgets a revoked
|
|
26
|
+
* sign-in, so an outage would log every user out for good.
|
|
27
|
+
*
|
|
28
|
+
* `failOpen: true` restores the old answer for a deployment whose
|
|
29
|
+
* only consumer is a JWT guard with a short `expiresIn`, where
|
|
30
|
+
* availability through an outage is worth more than a revocation
|
|
31
|
+
* missed for at most one token lifetime.
|
|
20
32
|
*
|
|
21
33
|
* Every degradation invokes `onDegrade`. The default reports the first failure
|
|
22
34
|
* per operation and then a periodic count: an outage that logs on every request
|
|
@@ -36,6 +48,11 @@ export interface BlacklistDegradeEvent {
|
|
|
36
48
|
export interface ResilientBlacklistConfig {
|
|
37
49
|
/** Invoked whenever the primary driver fails and the fallback is used. */
|
|
38
50
|
onDegrade?: (event: BlacklistDegradeEvent) => void;
|
|
51
|
+
/**
|
|
52
|
+
* Let a credential through when the primary cannot answer and this instance
|
|
53
|
+
* never revoked it. Off by default: see the policy above for what it costs.
|
|
54
|
+
*/
|
|
55
|
+
failOpen?: boolean;
|
|
39
56
|
}
|
|
40
57
|
|
|
41
58
|
/** How long a repeat of the same failing operation stays folded into a count. */
|
|
@@ -74,6 +91,7 @@ export class ResilientBlacklistDriver implements BlacklistDriver {
|
|
|
74
91
|
readonly #primary: BlacklistDriver;
|
|
75
92
|
readonly #fallback: BlacklistDriver;
|
|
76
93
|
readonly #onDegrade: (event: BlacklistDegradeEvent) => void;
|
|
94
|
+
readonly #failOpen: boolean;
|
|
77
95
|
|
|
78
96
|
constructor(
|
|
79
97
|
primary: BlacklistDriver,
|
|
@@ -83,6 +101,7 @@ export class ResilientBlacklistDriver implements BlacklistDriver {
|
|
|
83
101
|
this.#primary = primary;
|
|
84
102
|
this.#fallback = fallback;
|
|
85
103
|
this.#onDegrade = config.onDegrade ?? makeDefaultOnDegrade();
|
|
104
|
+
this.#failOpen = config.failOpen === true;
|
|
86
105
|
}
|
|
87
106
|
|
|
88
107
|
async add(jti: string, expiresAt: number): Promise<void> {
|
|
@@ -108,8 +127,9 @@ export class ResilientBlacklistDriver implements BlacklistDriver {
|
|
|
108
127
|
return await this.#primary.has(jti);
|
|
109
128
|
} catch (error) {
|
|
110
129
|
this.#onDegrade({ op: "has", error });
|
|
111
|
-
//
|
|
112
|
-
return false;
|
|
130
|
+
// Neither store can say the credential was not revoked.
|
|
131
|
+
if (this.#failOpen) return false;
|
|
132
|
+
throw error;
|
|
113
133
|
}
|
|
114
134
|
}
|
|
115
135
|
|
package/src/WardenProvider.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { clearAuth, getAuth, setAuth } from "./services/main.js";
|
|
|
10
10
|
import { ApiKeyStrategy } from "./strategies/ApiKeyStrategy.js";
|
|
11
11
|
import { JwtStrategy } from "./strategies/JwtStrategy.js";
|
|
12
12
|
import { SessionStrategy } from "./strategies/SessionStrategy.js";
|
|
13
|
+
import { installBouncerTemplateTags } from "./templateTags.js";
|
|
13
14
|
|
|
14
15
|
interface WardenContainer {
|
|
15
16
|
singleton(token: unknown, factory: () => unknown): void;
|
|
@@ -23,6 +24,8 @@ interface WardenConfigStore {
|
|
|
23
24
|
export interface WardenAppContext {
|
|
24
25
|
container: WardenContainer;
|
|
25
26
|
config: WardenConfigStore;
|
|
27
|
+
/** Set by the template engine's provider constructor (`InkerProvider`). */
|
|
28
|
+
usingInker?: boolean;
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
export default class WardenProvider {
|
|
@@ -184,90 +187,10 @@ export default class WardenProvider {
|
|
|
184
187
|
|
|
185
188
|
/**
|
|
186
189
|
* Publish `@can` / `@cannot` to the template engine, as AdonisJS's bouncer
|
|
187
|
-
* does
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
* Both are BLOCK tags and both AWAIT — the check returns a promise — so they
|
|
191
|
-
* render on the async path and raise on a synchronous one, matching upstream
|
|
192
|
-
* (which emits `await bouncer.can(...)`). The checks themselves come from
|
|
193
|
-
* `ctx.bouncer.templateHelpers`, shared into the view per request.
|
|
194
|
-
*
|
|
195
|
-
* Resolved through the container: warden must not depend on the engine, and
|
|
196
|
-
* an app with no template layer simply skips this.
|
|
190
|
+
* does — through the engine package's module singleton, guarded by
|
|
191
|
+
* `usingInker` (see `installBouncerTemplateTags`).
|
|
197
192
|
*/
|
|
198
193
|
async #registerTemplateTags(): Promise<void> {
|
|
199
|
-
|
|
200
|
-
if (engine === undefined) return;
|
|
201
|
-
for (const tagName of ["can", "cannot"] as const) {
|
|
202
|
-
engine.registerTag({
|
|
203
|
-
tagName,
|
|
204
|
-
block: true,
|
|
205
|
-
seekable: true,
|
|
206
|
-
async compile(_parser, buffer, token) {
|
|
207
|
-
// The shared bag lives in the render scope under `bouncer`.
|
|
208
|
-
const bouncer = token.evaluate(
|
|
209
|
-
"typeof bouncer === 'undefined' ? undefined : bouncer",
|
|
210
|
-
);
|
|
211
|
-
const check = Reflect.get(Object(bouncer), tagName);
|
|
212
|
-
if (typeof check !== "function") {
|
|
213
|
-
// No bouncer on this request: deny rather than render an
|
|
214
|
-
// unguarded body.
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
const args = token.evaluate(`[${token.properties.jsArg}]`);
|
|
218
|
-
const allowed = await check.apply(
|
|
219
|
-
bouncer,
|
|
220
|
-
Array.isArray(args) ? args : [],
|
|
221
|
-
);
|
|
222
|
-
if (allowed === true) buffer.writeRaw(await token.renderBody());
|
|
223
|
-
},
|
|
224
|
-
});
|
|
225
|
-
}
|
|
194
|
+
await installBouncerTemplateTags(this.app.usingInker === true);
|
|
226
195
|
}
|
|
227
|
-
|
|
228
|
-
/** The template engine, if the host installed one. */
|
|
229
|
-
async #resolveTemplateEngine(): Promise<TemplateEngineLike | undefined> {
|
|
230
|
-
for (const token of ["inker", "view"]) {
|
|
231
|
-
try {
|
|
232
|
-
const binding: unknown = await this.app.container.resolve(token);
|
|
233
|
-
for (const candidate of [
|
|
234
|
-
binding,
|
|
235
|
-
Reflect.get(Object(binding), "_templates"),
|
|
236
|
-
]) {
|
|
237
|
-
if (
|
|
238
|
-
typeof candidate === "object" &&
|
|
239
|
-
candidate !== null &&
|
|
240
|
-
typeof Reflect.get(candidate, "registerTag") === "function"
|
|
241
|
-
) {
|
|
242
|
-
return {
|
|
243
|
-
registerTag: Reflect.get(candidate, "registerTag").bind(
|
|
244
|
-
candidate,
|
|
245
|
-
),
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
} catch {
|
|
250
|
-
// A host without a template layer is not an error.
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
return undefined;
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/** The only surface warden needs of a template engine. */
|
|
258
|
-
interface TemplateEngineLike {
|
|
259
|
-
registerTag(tag: {
|
|
260
|
-
tagName: string;
|
|
261
|
-
block: boolean;
|
|
262
|
-
seekable: boolean;
|
|
263
|
-
compile(
|
|
264
|
-
parser: unknown,
|
|
265
|
-
buffer: { writeRaw(text: string): void },
|
|
266
|
-
token: {
|
|
267
|
-
properties: { jsArg: string };
|
|
268
|
-
renderBody(): string | Promise<string>;
|
|
269
|
-
evaluate(expression: string): unknown;
|
|
270
|
-
},
|
|
271
|
-
): void | Promise<void>;
|
|
272
|
-
}): void;
|
|
273
196
|
}
|
package/src/config.ts
CHANGED
|
@@ -86,7 +86,10 @@ export function sessionGuard(config: SessionStrategyConfig): GuardFactory {
|
|
|
86
86
|
return new SessionStrategy(config);
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
-
/**
|
|
89
|
+
/**
|
|
90
|
+
* Build an access-tokens guard from its config (AdonisJS `tokensGuard()`
|
|
91
|
+
* shape): `apiKeyGuard({ tokens: new AccessTokensProvider({ store }), findUser })`.
|
|
92
|
+
*/
|
|
90
93
|
export function apiKeyGuard(config: ApiKeyConfig): GuardFactory {
|
|
91
94
|
return new ApiKeyStrategy(config);
|
|
92
95
|
}
|
|
@@ -126,9 +129,10 @@ export interface WardenConfig {
|
|
|
126
129
|
*/
|
|
127
130
|
session?: SessionStrategyConfig;
|
|
128
131
|
/**
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
+
* Access-tokens strategy configuration: a `tokens` provider (hashed,
|
|
133
|
+
* prefixed, expiring tokens with abilities) and `findUser`. Registered as
|
|
134
|
+
* `access_tokens` and `api-key`; without it, `@Guard('access_tokens')`
|
|
135
|
+
* throws.
|
|
132
136
|
*/
|
|
133
137
|
apiKey?: ApiKeyConfig;
|
|
134
138
|
/**
|
package/src/index.ts
CHANGED
|
@@ -6,6 +6,22 @@
|
|
|
6
6
|
|
|
7
7
|
import "./augmentations.js";
|
|
8
8
|
|
|
9
|
+
export type {
|
|
10
|
+
AccessTokenAttributes,
|
|
11
|
+
AccessTokenStore,
|
|
12
|
+
AccessTokensProviderContract,
|
|
13
|
+
AccessTokensProviderOptions,
|
|
14
|
+
CreateAccessTokenOptions,
|
|
15
|
+
StoredAccessToken,
|
|
16
|
+
TokenOwner,
|
|
17
|
+
} from "./AccessToken.js";
|
|
18
|
+
export {
|
|
19
|
+
AccessToken,
|
|
20
|
+
AccessTokensProvider,
|
|
21
|
+
crc32,
|
|
22
|
+
MemoryAccessTokenStore,
|
|
23
|
+
} from "./AccessToken.js";
|
|
24
|
+
|
|
9
25
|
export type {
|
|
10
26
|
AttemptCount,
|
|
11
27
|
AttemptRedisClient,
|
|
@@ -24,11 +40,13 @@ export type {
|
|
|
24
40
|
AuthConfig,
|
|
25
41
|
AuthResult,
|
|
26
42
|
AuthStrategy,
|
|
43
|
+
CurrentAccessToken,
|
|
27
44
|
UserPayload,
|
|
28
45
|
} from "./AuthManager.js";
|
|
29
46
|
export {
|
|
30
47
|
AuthManager,
|
|
31
48
|
authEventPrefix,
|
|
49
|
+
tokenAllows,
|
|
32
50
|
type WardenEmitter,
|
|
33
51
|
} from "./AuthManager.js";
|
|
34
52
|
export type {
|
package/src/mfa/MfaManager.ts
CHANGED
|
@@ -157,10 +157,26 @@ export class MfaManager {
|
|
|
157
157
|
return { factorId: factor.id, secret, uri };
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
-
/**
|
|
161
|
-
|
|
160
|
+
/**
|
|
161
|
+
* Confirm a pending TOTP factor of `userId` by verifying a first code.
|
|
162
|
+
*
|
|
163
|
+
* Takes the owner beside the factor id and refuses a factor that belongs
|
|
164
|
+
* to someone else: a factor id is something an application passes through
|
|
165
|
+
* a request, and one leaked through a log or a support tool must not let
|
|
166
|
+
* another account act on it. The attempt counts against the same lockout
|
|
167
|
+
* as {@link verify}, so the first code cannot be guessed without limit.
|
|
168
|
+
*/
|
|
169
|
+
async confirmTotp(
|
|
170
|
+
userId: string,
|
|
171
|
+
factorId: string,
|
|
172
|
+
code: string,
|
|
173
|
+
): Promise<boolean> {
|
|
162
174
|
const totp = this.#requireTotp();
|
|
163
|
-
const
|
|
175
|
+
const key = lockoutKey(userId);
|
|
176
|
+
if (!(await this.#limiter.attempt(key)).allowed) {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
const factor = await this.#ownedFactor(userId, factorId);
|
|
164
180
|
if (factor?.kind !== "totp" || !factor.secret) {
|
|
165
181
|
return false;
|
|
166
182
|
}
|
|
@@ -168,6 +184,7 @@ export class MfaManager {
|
|
|
168
184
|
return false;
|
|
169
185
|
}
|
|
170
186
|
await this.#store.save({ ...factor, confirmedAt: Date.now() });
|
|
187
|
+
await this.#limiter.clear(key);
|
|
171
188
|
return true;
|
|
172
189
|
}
|
|
173
190
|
|
|
@@ -293,9 +310,25 @@ export class MfaManager {
|
|
|
293
310
|
return factors.some((f) => f.confirmedAt !== undefined);
|
|
294
311
|
}
|
|
295
312
|
|
|
296
|
-
/**
|
|
297
|
-
|
|
298
|
-
|
|
313
|
+
/**
|
|
314
|
+
* Remove one of `userId`'s factors (e.g. the user disables their
|
|
315
|
+
* authenticator). Answers whether a factor was removed: `false` for an
|
|
316
|
+
* unknown id or one owned by another user, which is left in place.
|
|
317
|
+
*/
|
|
318
|
+
async disableFactor(userId: string, factorId: string): Promise<boolean> {
|
|
319
|
+
const factor = await this.#ownedFactor(userId, factorId);
|
|
320
|
+
if (factor === null) return false;
|
|
321
|
+
await this.#store.delete(factor.id);
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** The factor, only when it belongs to `userId`. */
|
|
326
|
+
async #ownedFactor(
|
|
327
|
+
userId: string,
|
|
328
|
+
factorId: string,
|
|
329
|
+
): Promise<MfaFactor | null> {
|
|
330
|
+
const factor = await this.#store.findById(factorId);
|
|
331
|
+
return factor !== null && factor.userId === userId ? factor : null;
|
|
299
332
|
}
|
|
300
333
|
|
|
301
334
|
#requireTotp(): TotpProvider {
|
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";
|
|
@@ -245,10 +245,21 @@ export async function wardenMiddleware(ctx: WardenContext, next: WardenNext) {
|
|
|
245
245
|
// (fail-open) — the exact bug this precedence prevents.
|
|
246
246
|
const controller = ctx.route?.controller ?? ctx.controller;
|
|
247
247
|
const action = ctx.route?.action ?? ctx.action;
|
|
248
|
-
const
|
|
248
|
+
const declared =
|
|
249
249
|
controller && action ? getGuardMetadata(controller, action) : [];
|
|
250
|
+
// `@Role`, `@Permission` and `@RequireMfa` say who may run the action, which
|
|
251
|
+
// presupposes knowing who is asking: without `@Guard` beside them they imply
|
|
252
|
+
// the default guard. Reading them only under `@Guard` left a route declaring
|
|
253
|
+
// `@Role('admin')` alone open to anonymous requests.
|
|
254
|
+
const strategies =
|
|
255
|
+
declared.length === 0 &&
|
|
256
|
+
controller &&
|
|
257
|
+
action &&
|
|
258
|
+
requiresAuthorization(controller, action)
|
|
259
|
+
? [auth.defaultStrategyName]
|
|
260
|
+
: declared;
|
|
250
261
|
|
|
251
|
-
// No guard
|
|
262
|
+
// No guard and no authorization decorator — pass through (public endpoint).
|
|
252
263
|
if (strategies.length === 0) {
|
|
253
264
|
await next();
|
|
254
265
|
return;
|
|
@@ -321,6 +332,18 @@ export async function wardenMiddleware(ctx: WardenContext, next: WardenNext) {
|
|
|
321
332
|
await next();
|
|
322
333
|
}
|
|
323
334
|
|
|
335
|
+
/** Whether the action carries any decorator that restricts who may run it. */
|
|
336
|
+
function requiresAuthorization(
|
|
337
|
+
controller: object,
|
|
338
|
+
action: string | symbol,
|
|
339
|
+
): boolean {
|
|
340
|
+
return (
|
|
341
|
+
getRoleMetadata(controller, action).length > 0 ||
|
|
342
|
+
getPermissionMetadata(controller, action).length > 0 ||
|
|
343
|
+
getRequireMfaMetadata(controller, action)
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
|
|
324
347
|
/**
|
|
325
348
|
* Silent auth middleware (AdonisJS `silent_auth` parity) — a GLOBAL middleware
|
|
326
349
|
* that populates `ctx.auth` from the request's credentials when they're valid,
|
|
@@ -472,11 +495,15 @@ export async function initializeBouncer(ctx: WardenContext, next: WardenNext) {
|
|
|
472
495
|
const candidate = await tryResolve(ctx, "bouncer:registry");
|
|
473
496
|
const registry = isBouncerRegistry(candidate) ? candidate : undefined;
|
|
474
497
|
|
|
475
|
-
const user = ctx.auth?.user ?? null;
|
|
476
498
|
const scope: Scope = registry?.resolveScope
|
|
477
499
|
? await registry.resolveScope(toScopeContext(ctx))
|
|
478
500
|
: "global";
|
|
479
501
|
|
|
502
|
+
// The user is read when the first check runs, not now: a handler that
|
|
503
|
+
// authenticates itself (`await ctx.auth.authenticate()`) and then
|
|
504
|
+
// authorizes must be judged as the user it just signed in, not as the
|
|
505
|
+
// guest this middleware saw.
|
|
506
|
+
const user = (): UserPayload | null => ctx.auth?.user ?? null;
|
|
480
507
|
const bouncer = new Bouncer(user, registry?.abilities, registry?.policies, {
|
|
481
508
|
scope,
|
|
482
509
|
resolver,
|
|
@@ -545,7 +572,11 @@ async function checkAuthorization(
|
|
|
545
572
|
}
|
|
546
573
|
const effective = await auth.resolvePermissions(user, scope);
|
|
547
574
|
if (requiredPermissions.length > 0) {
|
|
548
|
-
|
|
575
|
+
// The user must hold it, and the token the request came in with, if
|
|
576
|
+
// any, must allow it: an intersection, never a union.
|
|
577
|
+
const missing = requiredPermissions.filter(
|
|
578
|
+
(p) => !effective.has(p) || !tokenAllows(user, p),
|
|
579
|
+
);
|
|
549
580
|
if (missing.length > 0) return `Missing permissions: ${missing.join(", ")}`;
|
|
550
581
|
}
|
|
551
582
|
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
|
});
|