@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/middleware.ts
CHANGED
|
@@ -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
|
/**
|
|
@@ -479,7 +492,7 @@ export interface BouncerRegistry {
|
|
|
479
492
|
* from the authenticated user (`ctx.auth?.user`, or `null` for a guest), the
|
|
480
493
|
* shared `RightsResolver`, and the registered abilities/policies, then attaches
|
|
481
494
|
* it as `ctx.bouncer`. Handlers authorize via `await ctx.bouncer.authorize(...)`
|
|
482
|
-
* (throws `
|
|
495
|
+
* (throws `E_AUTHORIZATION_FAILURE` carrying `status: 403`, which the host's
|
|
483
496
|
* ExceptionHandler maps to a 403 response) or branch on `ctx.bouncer.allows(...)`.
|
|
484
497
|
*
|
|
485
498
|
* Unlike `wardenMiddleware` (a per-route GUARD that short-circuits public
|
|
@@ -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,6 +23,7 @@ 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";
|
|
@@ -127,11 +128,7 @@ export function createWarden(config: WardenConfig): Warden {
|
|
|
127
128
|
|
|
128
129
|
expressMiddleware() {
|
|
129
130
|
return (req, res, next) => {
|
|
130
|
-
const
|
|
131
|
-
const token =
|
|
132
|
-
typeof authHeader === "string" && authHeader.startsWith("Bearer ")
|
|
133
|
-
? authHeader.slice(7)
|
|
134
|
-
: "";
|
|
131
|
+
const token = readBearerToken(req.headers?.authorization);
|
|
135
132
|
|
|
136
133
|
if (!token) {
|
|
137
134
|
fail(
|
|
@@ -111,10 +111,11 @@ export class ApiKeyStrategy implements AuthStrategy {
|
|
|
111
111
|
/**
|
|
112
112
|
* Revoke the token behind `value`. Answers whether it existed.
|
|
113
113
|
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
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.
|
|
118
119
|
*/
|
|
119
120
|
invalidateToken(value: string): Promise<boolean> {
|
|
120
121
|
return this.#config.tokens.invalidate(new Secret(value));
|
|
@@ -154,9 +155,13 @@ export class ApiKeyStrategy implements AuthStrategy {
|
|
|
154
155
|
}
|
|
155
156
|
// A copy: the provider's object is the application's, and attaching the
|
|
156
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()`.
|
|
157
162
|
return {
|
|
158
163
|
authenticated: true,
|
|
159
|
-
user: { ...user, currentAccessToken: accessToken },
|
|
164
|
+
user: { ...user, currentAccessToken: accessToken, mfa: false },
|
|
160
165
|
};
|
|
161
166
|
}
|
|
162
167
|
}
|
|
@@ -15,6 +15,7 @@ import type {
|
|
|
15
15
|
AuthStrategy,
|
|
16
16
|
UserPayload,
|
|
17
17
|
} from "../AuthManager.js";
|
|
18
|
+
import { rejectedAsNull } from "../authFinder.js";
|
|
18
19
|
|
|
19
20
|
export interface BasicAuthConfig {
|
|
20
21
|
/**
|
|
@@ -86,11 +87,15 @@ export class BasicAuthStrategy implements AuthStrategy {
|
|
|
86
87
|
if (typeof uid !== "string" || typeof password !== "string") {
|
|
87
88
|
return { authenticated: false, error: "Invalid credentials" };
|
|
88
89
|
}
|
|
89
|
-
const user = await
|
|
90
|
+
const user = await rejectedAsNull(
|
|
91
|
+
this.#config.verifyCredentials(uid, password),
|
|
92
|
+
);
|
|
90
93
|
// One message for an unknown user and for a wrong password: telling them
|
|
91
94
|
// apart turns the endpoint into a username oracle.
|
|
92
95
|
if (!user) return { authenticated: false, error: "Invalid credentials" };
|
|
93
|
-
|
|
96
|
+
// A password is not a step-up: whatever the application's user carries
|
|
97
|
+
// under `mfa` (an "MFA enabled" column) must not satisfy `@RequireMfa()`.
|
|
98
|
+
return { authenticated: true, user: { ...user, mfa: false } };
|
|
94
99
|
}
|
|
95
100
|
|
|
96
101
|
/** Authenticate from the raw `Authorization` header value. */
|
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
AuthStrategy,
|
|
11
11
|
UserPayload,
|
|
12
12
|
} from "../AuthManager.js";
|
|
13
|
+
import { rejectedAsNull } from "../authFinder.js";
|
|
13
14
|
import { resolveExpiresInSeconds, type TokenDuration } from "../duration.js";
|
|
14
15
|
import { nativeWarden, nativeWardenLoadError } from "../native.js";
|
|
15
16
|
import type { TokenBlacklist } from "../TokenBlacklist.js";
|
|
@@ -26,8 +27,12 @@ export interface JwtClaims {
|
|
|
26
27
|
permissions?: string[];
|
|
27
28
|
iat: number;
|
|
28
29
|
exp: number;
|
|
29
|
-
/**
|
|
30
|
-
|
|
30
|
+
/**
|
|
31
|
+
* RFC 7519 JWT ID — populated at sign time so revocation can target a
|
|
32
|
+
* single token. Absent only on a token signed elsewhere, which a strategy
|
|
33
|
+
* with a blacklist refuses (it could never be revoked).
|
|
34
|
+
*/
|
|
35
|
+
jti?: string;
|
|
31
36
|
[key: string]: unknown;
|
|
32
37
|
}
|
|
33
38
|
|
|
@@ -61,14 +66,56 @@ function verify(token: string, secret: string): JwtClaims | null {
|
|
|
61
66
|
{ cause: nativeWardenLoadError() },
|
|
62
67
|
);
|
|
63
68
|
}
|
|
69
|
+
let parsed: unknown;
|
|
64
70
|
try {
|
|
65
|
-
|
|
66
|
-
const payload = JSON.parse(payloadJson) as JwtClaims;
|
|
67
|
-
if (typeof payload.sub !== "string" || !payload.sub) return null;
|
|
68
|
-
return payload;
|
|
71
|
+
parsed = JSON.parse(rust.jwtVerify(token, secret));
|
|
69
72
|
} catch {
|
|
70
73
|
return null;
|
|
71
74
|
}
|
|
75
|
+
return toJwtClaims(parsed);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function isStringArray(value: unknown): value is string[] {
|
|
79
|
+
return Array.isArray(value) && value.every((v) => typeof v === "string");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The verified payload, if it has the shape {@link JwtClaims} promises.
|
|
84
|
+
*
|
|
85
|
+
* The signature proves who wrote the claims, not what they contain. Trusted
|
|
86
|
+
* as-is, a token without `iat` slipped past an app's "iat predates
|
|
87
|
+
* passwordChangedAt" check in `findUser` (`undefined < n` is false), and a
|
|
88
|
+
* non-string `jti` reached the blacklist. Anything off-shape is refused.
|
|
89
|
+
*/
|
|
90
|
+
function toJwtClaims(value: unknown): JwtClaims | null {
|
|
91
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
const sub: unknown = Reflect.get(value, "sub");
|
|
95
|
+
const iat: unknown = Reflect.get(value, "iat");
|
|
96
|
+
const exp: unknown = Reflect.get(value, "exp");
|
|
97
|
+
const jti: unknown = Reflect.get(value, "jti");
|
|
98
|
+
const roles: unknown = Reflect.get(value, "roles");
|
|
99
|
+
const permissions: unknown = Reflect.get(value, "permissions");
|
|
100
|
+
if (typeof sub !== "string" || sub.length === 0) return null;
|
|
101
|
+
if (typeof iat !== "number" || !Number.isFinite(iat)) return null;
|
|
102
|
+
if (typeof exp !== "number" || !Number.isFinite(exp)) return null;
|
|
103
|
+
if (jti !== undefined && (typeof jti !== "string" || jti.length === 0)) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
if (roles !== undefined && !isStringArray(roles)) return null;
|
|
107
|
+
if (permissions !== undefined && !isStringArray(permissions)) return null;
|
|
108
|
+
// Optional claims are carried only when the token has them: an explicit
|
|
109
|
+
// `undefined` would show up as a key the token never asserted.
|
|
110
|
+
return {
|
|
111
|
+
...value,
|
|
112
|
+
sub,
|
|
113
|
+
iat,
|
|
114
|
+
exp,
|
|
115
|
+
...(jti === undefined ? {} : { jti }),
|
|
116
|
+
...(roles === undefined ? {} : { roles }),
|
|
117
|
+
...(permissions === undefined ? {} : { permissions }),
|
|
118
|
+
};
|
|
72
119
|
}
|
|
73
120
|
|
|
74
121
|
export interface JwtStrategyConfig {
|
|
@@ -176,7 +223,7 @@ export class JwtStrategy implements AuthStrategy {
|
|
|
176
223
|
return { authenticated: false, error: "Email and password are required" };
|
|
177
224
|
}
|
|
178
225
|
|
|
179
|
-
const user = await this.#verifyCredentials(email, password);
|
|
226
|
+
const user = await rejectedAsNull(this.#verifyCredentials(email, password));
|
|
180
227
|
if (!user) {
|
|
181
228
|
return { authenticated: false, error: "Invalid credentials" };
|
|
182
229
|
}
|
|
@@ -201,7 +248,7 @@ export class JwtStrategy implements AuthStrategy {
|
|
|
201
248
|
// trust such a token — reject it rather than let an
|
|
202
249
|
// unrevocable token through. (signToken always sets a jti;
|
|
203
250
|
// this guards legacy / externally-signed tokens.)
|
|
204
|
-
if (
|
|
251
|
+
if (payload.jti === undefined) {
|
|
205
252
|
return { authenticated: false, error: "Token missing jti claim" };
|
|
206
253
|
}
|
|
207
254
|
if (await this.#blacklist.isRevoked(payload.jti)) {
|
|
@@ -270,7 +317,9 @@ export class JwtStrategy implements AuthStrategy {
|
|
|
270
317
|
);
|
|
271
318
|
}
|
|
272
319
|
const payload = this.#verifyWithRotation(token);
|
|
273
|
-
|
|
320
|
+
// No jti, nothing to list: verify() refuses such a token anyway once a
|
|
321
|
+
// blacklist is configured, which revoking requires.
|
|
322
|
+
if (!payload || payload.jti === undefined) return false;
|
|
274
323
|
const expMs = payload.exp * 1000;
|
|
275
324
|
if (expMs <= Date.now()) return false;
|
|
276
325
|
await this.#blacklist.revoke(payload.jti, expMs);
|
|
@@ -256,7 +256,10 @@ export class SessionStrategy implements AuthStrategy {
|
|
|
256
256
|
if (!user) return null;
|
|
257
257
|
|
|
258
258
|
if (state) state.viaRemember = true;
|
|
259
|
-
|
|
259
|
+
// A revived session has not stepped up (seatSession forgets the marker
|
|
260
|
+
// too): `findUser`'s own `mfa` field must not satisfy `@RequireMfa()`
|
|
261
|
+
// on the request the cookie was replayed on.
|
|
262
|
+
return { user: { ...user, mfa: false }, cookieValue: recycled.value };
|
|
260
263
|
}
|
|
261
264
|
|
|
262
265
|
/**
|
|
@@ -86,6 +86,27 @@ export function hasCommands(
|
|
|
86
86
|
return missingCommands(value, commands).length === 0;
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
/**
|
|
90
|
+
* Whether a client resolved earlier has ended for good, and must be resolved
|
|
91
|
+
* again rather than used.
|
|
92
|
+
*
|
|
93
|
+
* ioredis reaches `end` once its retry strategy gives up (quasar's generated
|
|
94
|
+
* config gives up after ten attempts, about three seconds of outage), or after
|
|
95
|
+
* `quit()`/`disconnect()`. From there every command rejects with "Connection is
|
|
96
|
+
* closed." and the client never comes back. Quasar drops such a connection and
|
|
97
|
+
* hands out a fresh one on the next `connection(name)`, so a store that kept
|
|
98
|
+
* the first answer of its resolver stayed on the dead client until the process
|
|
99
|
+
* restarted, even once Redis was back.
|
|
100
|
+
*
|
|
101
|
+
* `close` is NOT terminal: ioredis reconnects from it by itself, and throwing
|
|
102
|
+
* that client away would leak its socket. A client with no `status` (a test
|
|
103
|
+
* double, another library) never counts as ended. Only meaningful for a
|
|
104
|
+
* resolver: a client handed in directly is the caller's to replace.
|
|
105
|
+
*/
|
|
106
|
+
export function hasEnded(client: unknown): boolean {
|
|
107
|
+
return memberValue(readMember(client, "status")) === "end";
|
|
108
|
+
}
|
|
109
|
+
|
|
89
110
|
export interface QuasarConnectionRequest<T> {
|
|
90
111
|
/** The package asking. It prefixes every message this can raise. */
|
|
91
112
|
pkg: string;
|
package/stubs/config/auth.stub
CHANGED
|
@@ -12,6 +12,9 @@ export default defineConfig({
|
|
|
12
12
|
expiresIn: process.env.JWT_EXPIRY ?? 3600,
|
|
13
13
|
// TODO: wire these to your user model (e.g. via your ORM).
|
|
14
14
|
// The JWT guard needs both to issue and verify tokens.
|
|
15
|
+
// For verifyCredentials, build on authFinder({ hash, findForAuth }) from
|
|
16
|
+
// '@c9up/warden': it pays a hash for an unknown email too, so the login
|
|
17
|
+
// response time does not reveal which accounts exist.
|
|
15
18
|
findUser: async (_id) => {
|
|
16
19
|
throw new Error('TODO: implement findUser(id) for the JWT guard in config/auth.ts')
|
|
17
20
|
},
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* Regenerate `src/native/generated.ts` from the Rust.
|
|
4
|
-
*
|
|
5
|
-
* Node rather than a shell script because this runs inside `build:napi`, and
|
|
6
|
-
* that runs on the Windows prebuild runner too: a bash `mktemp` there hands
|
|
7
|
-
* cargo a `/tmp/...` path the native proc-macro cannot write to, so the
|
|
8
|
-
* type-def file comes back empty and the build fails for no visible reason.
|
|
9
|
-
*
|
|
10
|
-
* One crate at a time on purpose: with napi-derive 2 the writes all went to a
|
|
11
|
-
* single `TYPE_DEF_TMP_PATH` and a parallel build interleaved them
|
|
12
|
-
* while cargo compiles, and a parallel build interleaves the writes —
|
|
13
|
-
* definitions go missing, silently, and the generated file comes out short.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import { execFileSync } from 'node:child_process'
|
|
17
|
-
import { createRequire } from 'node:module'
|
|
18
|
-
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
19
|
-
import { tmpdir } from 'node:os'
|
|
20
|
-
import { dirname, join } from 'node:path'
|
|
21
|
-
import { fileURLToPath } from 'node:url'
|
|
22
|
-
|
|
23
|
-
const CRATES = ['warden-engine-napi']
|
|
24
|
-
|
|
25
|
-
const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
|
|
26
|
-
const output = join('src', 'native', 'generated.ts')
|
|
27
|
-
const scratch = mkdtempSync(join(tmpdir(), 'napi-types-'))
|
|
28
|
-
|
|
29
|
-
try {
|
|
30
|
-
const lines = []
|
|
31
|
-
for (const crate of CRATES) {
|
|
32
|
-
const perCrate = join(scratch, crate)
|
|
33
|
-
writeFileSync(perCrate, '')
|
|
34
|
-
execFileSync('cargo', ['build', '-p', crate], {
|
|
35
|
-
cwd: packageRoot,
|
|
36
|
-
env: { ...process.env, NAPI_TYPE_DEF_TMP_FOLDER: scratch },
|
|
37
|
-
stdio: ['ignore', 'ignore', 'inherit'],
|
|
38
|
-
})
|
|
39
|
-
const emitted = readFileSync(perCrate, 'utf8').split('\n').filter(Boolean)
|
|
40
|
-
if (emitted.length === 0) {
|
|
41
|
-
throw new Error(
|
|
42
|
-
`[napi-types] ${crate} emitted nothing — is napi-derive's "type-def" feature on?`,
|
|
43
|
-
)
|
|
44
|
-
}
|
|
45
|
-
lines.push(...emitted)
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
const combined = join(scratch, 'combined.jsonl')
|
|
49
|
-
writeFileSync(combined, `${lines.join('\n')}\n`)
|
|
50
|
-
|
|
51
|
-
execFileSync(
|
|
52
|
-
process.execPath,
|
|
53
|
-
[join('scripts', 'generate-napi-types.mjs'), combined, output],
|
|
54
|
-
{ cwd: packageRoot, stdio: 'inherit' },
|
|
55
|
-
)
|
|
56
|
-
|
|
57
|
-
// Formatted here rather than excluded from the linter: the file is checked
|
|
58
|
-
// in, so it should read like the rest of the tree — and formatting it at
|
|
59
|
-
// generation means it never shows up as a diff someone has to fix by hand.
|
|
60
|
-
// Resolved through the package entry rather than `node_modules/.bin`, whose
|
|
61
|
-
// shim is a shell script the Windows runner cannot execute directly.
|
|
62
|
-
const biome = createRequire(import.meta.url).resolve('@biomejs/biome/bin/biome')
|
|
63
|
-
execFileSync(process.execPath, [biome, 'format', '--write', output], {
|
|
64
|
-
cwd: packageRoot,
|
|
65
|
-
stdio: ['ignore', 'ignore', 'inherit'],
|
|
66
|
-
})
|
|
67
|
-
} finally {
|
|
68
|
-
rmSync(scratch, { recursive: true, force: true })
|
|
69
|
-
}
|
package/scripts/copy-napi.mjs
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { copyFileSync, existsSync } from 'node:fs'
|
|
2
|
-
import { dirname, join, resolve } from 'node:path'
|
|
3
|
-
import { arch, env, platform } from 'node:process'
|
|
4
|
-
import { fileURLToPath } from 'node:url'
|
|
5
|
-
|
|
6
|
-
const here = dirname(fileURLToPath(import.meta.url))
|
|
7
|
-
const root = join(here, '..')
|
|
8
|
-
const CRATE = 'warden_engine_napi'
|
|
9
|
-
const TAG = '[warden:napi]'
|
|
10
|
-
|
|
11
|
-
// Rust target triple -> { suffix, os }. Set CARGO_BUILD_TARGET to cross-compile
|
|
12
|
-
// (e.g. build the x86_64-apple-darwin binary on an arm64 macOS runner). When
|
|
13
|
-
// unset we fall back to the host platform/arch and the default target/release.
|
|
14
|
-
const tripleMap = {
|
|
15
|
-
'x86_64-unknown-linux-gnu': { suffix: 'linux-x64-gnu', os: 'linux' },
|
|
16
|
-
'aarch64-unknown-linux-gnu': { suffix: 'linux-arm64-gnu', os: 'linux' },
|
|
17
|
-
'x86_64-apple-darwin': { suffix: 'darwin-x64', os: 'darwin' },
|
|
18
|
-
'aarch64-apple-darwin': { suffix: 'darwin-arm64', os: 'darwin' },
|
|
19
|
-
'x86_64-pc-windows-msvc': { suffix: 'win32-x64-msvc', os: 'win32' },
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const hostSuffixMap = {
|
|
23
|
-
'linux-x64': 'linux-x64-gnu',
|
|
24
|
-
'linux-arm64': 'linux-arm64-gnu',
|
|
25
|
-
'darwin-x64': 'darwin-x64',
|
|
26
|
-
'darwin-arm64': 'darwin-arm64',
|
|
27
|
-
'win32-x64': 'win32-x64-msvc',
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// Cargo writes its artifacts under CARGO_TARGET_DIR when that is set — a
|
|
31
|
-
// shared cache, a CI mount — so they are not under this package's `target/` at
|
|
32
|
-
// all. A relative value is resolved against the directory cargo ran in, which
|
|
33
|
-
// is this package root.
|
|
34
|
-
const targetDir = env.CARGO_TARGET_DIR
|
|
35
|
-
? resolve(root, env.CARGO_TARGET_DIR)
|
|
36
|
-
: join(root, 'target')
|
|
37
|
-
|
|
38
|
-
const triple = env.CARGO_BUILD_TARGET ?? ''
|
|
39
|
-
let suffix
|
|
40
|
-
let os
|
|
41
|
-
let releaseDir
|
|
42
|
-
if (triple) {
|
|
43
|
-
const entry = tripleMap[triple]
|
|
44
|
-
if (!entry) {
|
|
45
|
-
throw new Error(`${TAG} unsupported CARGO_BUILD_TARGET: ${triple}`)
|
|
46
|
-
}
|
|
47
|
-
suffix = entry.suffix
|
|
48
|
-
os = entry.os
|
|
49
|
-
releaseDir = join(targetDir, triple, 'release')
|
|
50
|
-
} else {
|
|
51
|
-
suffix = hostSuffixMap[`${platform}-${arch}`]
|
|
52
|
-
os = platform
|
|
53
|
-
releaseDir = join(targetDir, 'release')
|
|
54
|
-
if (!suffix) {
|
|
55
|
-
throw new Error(`${TAG} unsupported platform/arch: ${platform}-${arch}`)
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
const candidates =
|
|
60
|
-
os === 'win32'
|
|
61
|
-
? [join(releaseDir, `${CRATE}.dll`), join(releaseDir, `lib${CRATE}.dll`)]
|
|
62
|
-
: os === 'darwin'
|
|
63
|
-
? [join(releaseDir, `lib${CRATE}.dylib`)]
|
|
64
|
-
: [join(releaseDir, `lib${CRATE}.so`)]
|
|
65
|
-
|
|
66
|
-
const source = candidates.find((candidate) => existsSync(candidate))
|
|
67
|
-
if (!source) {
|
|
68
|
-
throw new Error(
|
|
69
|
-
`${TAG} native library not found. Looked for:\n${candidates.map((p) => `- ${p}`).join('\n')}`,
|
|
70
|
-
)
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
const target = join(root, `index.${suffix}.node`)
|
|
74
|
-
copyFileSync(source, target)
|
|
75
|
-
console.log(`${TAG} copied ${source} -> ${target}`)
|
|
@@ -1,156 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* Generate the TypeScript surface of the native module FROM the Rust.
|
|
4
|
-
*
|
|
5
|
-
* `napi-derive`'s `type-def` feature emits one JSON line per exported item
|
|
6
|
-
* while cargo compiles. Those lines are the source of truth: they are derived
|
|
7
|
-
* from the `#[napi]` items themselves, so a signature cannot drift from the
|
|
8
|
-
* Rust without this file changing.
|
|
9
|
-
*
|
|
10
|
-
* Hand-written interfaces are what this replaces, and they do drift — nothing
|
|
11
|
-
* on the TypeScript side notices when a `pub fn` gains a parameter or stops
|
|
12
|
-
* being `async`.
|
|
13
|
-
*
|
|
14
|
-
* One thing napi-rs cannot infer: the shape of a `JsFunction` callback. It
|
|
15
|
-
* emits `(...args: any[]) => any`. Any such parameter is refined below, by
|
|
16
|
-
* name, and the script fails if a refinement no longer matches anything — so
|
|
17
|
-
* the table cannot rot either.
|
|
18
|
-
*
|
|
19
|
-
* TYPE_DEF_TMP_PATH=<file> cargo build -p <crate>
|
|
20
|
-
* node scripts/generate-napi-types.mjs <file> <out.d.ts>
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
import { readFileSync, writeFileSync } from 'node:fs'
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Callback signatures napi-rs erases to `any`, restored here.
|
|
27
|
-
*
|
|
28
|
-
* Keyed by `<owner>.<method>`; the value replaces the whole parameter. Every
|
|
29
|
-
* entry must match, or the script fails: a stale refinement is how a hand
|
|
30
|
-
* annotation quietly stops describing the Rust.
|
|
31
|
-
*
|
|
32
|
-
* Empty while this crate exposes no `JsFunction` parameter — add an entry the
|
|
33
|
-
* day one appears, rather than letting an `any` through.
|
|
34
|
-
*/
|
|
35
|
-
const CALLBACK_REFINEMENTS = {}
|
|
36
|
-
|
|
37
|
-
const [input, output] = process.argv.slice(2)
|
|
38
|
-
if (!input || !output) {
|
|
39
|
-
console.error('usage: generate-napi-types.mjs <type-def file> <out.d.ts>')
|
|
40
|
-
process.exit(2)
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const entries = readFileSync(input, 'utf8')
|
|
44
|
-
.split('\n')
|
|
45
|
-
.map((l) => l.trim())
|
|
46
|
-
.filter(Boolean)
|
|
47
|
-
.map((l) => JSON.parse(l))
|
|
48
|
-
|
|
49
|
-
const used = new Set()
|
|
50
|
-
|
|
51
|
-
/** Apply the refinements that belong to `owner`, tracking which ones matched. */
|
|
52
|
-
function refine(owner, body) {
|
|
53
|
-
let out = body
|
|
54
|
-
for (const [key, { from, to }] of Object.entries(CALLBACK_REFINEMENTS)) {
|
|
55
|
-
const [entryOwner] = key.split('.')
|
|
56
|
-
if (entryOwner !== owner) continue
|
|
57
|
-
if (out.includes(from)) {
|
|
58
|
-
out = out.replace(from, to)
|
|
59
|
-
used.add(key)
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
return out
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* JSDoc as emitted by napi-derive, indented to sit above its member.
|
|
67
|
-
*
|
|
68
|
-
* `*` followed by `/` inside the text closes the comment early — a Rust doc
|
|
69
|
-
* example holding a cron expression (`0 */5 * * *`) is enough to do it, and
|
|
70
|
-
* the generated file then fails to parse. Escaped rather than stripped, so the
|
|
71
|
-
* example still reads correctly.
|
|
72
|
-
*/
|
|
73
|
-
function docBlock(doc, indent = '') {
|
|
74
|
-
if (!doc) return ''
|
|
75
|
-
// Escape every `*/` EXCEPT the one that closes the block. A Rust doc example
|
|
76
|
-
// holding a cron expression (`0 */5 * * *`) closes the comment early
|
|
77
|
-
// otherwise, and the generated file stops parsing — but escaping the closer
|
|
78
|
-
// too breaks it just as thoroughly, whether the block spans one line or many.
|
|
79
|
-
const closer = doc.lastIndexOf('*/')
|
|
80
|
-
const escaped =
|
|
81
|
-
closer === -1
|
|
82
|
-
? doc
|
|
83
|
-
: doc.slice(0, closer).replaceAll('*/', '*\\/') + doc.slice(closer)
|
|
84
|
-
return (
|
|
85
|
-
escaped
|
|
86
|
-
.split('\n')
|
|
87
|
-
.filter((l) => l.length > 0)
|
|
88
|
-
.map((l) => `${indent}${l}`)
|
|
89
|
-
.join('\n') + '\n'
|
|
90
|
-
)
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const interfaces = entries.filter((e) => e.kind === 'interface')
|
|
94
|
-
const structs = entries.filter((e) => e.kind === 'struct')
|
|
95
|
-
const impls = new Map(entries.filter((e) => e.kind === 'impl').map((e) => [e.name, e]))
|
|
96
|
-
const fns = entries.filter((e) => e.kind === 'fn')
|
|
97
|
-
|
|
98
|
-
const out = [
|
|
99
|
-
'// GENERATED FROM THE RUST — do not edit.',
|
|
100
|
-
'//',
|
|
101
|
-
"// Produced by scripts/generate-napi-types.mjs from napi-derive's type-def",
|
|
102
|
-
'// output. Editing this file by hand puts it back where it started: a',
|
|
103
|
-
'// description that can disagree with the code it describes.',
|
|
104
|
-
'',
|
|
105
|
-
]
|
|
106
|
-
|
|
107
|
-
for (const iface of interfaces) {
|
|
108
|
-
out.push(docBlock(iface.js_doc))
|
|
109
|
-
out.push(`export interface ${iface.name} {`)
|
|
110
|
-
for (const line of iface.def.split('\n')) {
|
|
111
|
-
out.push(line ? ` ${line.trim()}` : '')
|
|
112
|
-
}
|
|
113
|
-
out.push('}', '')
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
for (const struct of structs) {
|
|
117
|
-
const impl = impls.get(struct.name)
|
|
118
|
-
out.push(docBlock(struct.js_doc))
|
|
119
|
-
out.push(`export declare class ${struct.name} {`)
|
|
120
|
-
if (impl) {
|
|
121
|
-
for (const line of refine(struct.name, impl.def).split('\n')) {
|
|
122
|
-
out.push(line ? ` ${line.trim()}` : '')
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
out.push('}', '')
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
for (const fn of fns) {
|
|
129
|
-
out.push(docBlock(fn.js_doc))
|
|
130
|
-
// napi-derive emits the whole declaration for a function, unlike a struct
|
|
131
|
-
// where `def` holds only the members.
|
|
132
|
-
const declaration = fn.def.trim()
|
|
133
|
-
// napi-derive 3 emits a bare `function name(...)` where 2 emitted the
|
|
134
|
-
// signature after the name; concatenating onto the former produced
|
|
135
|
-
// `function xfunction x(...)`.
|
|
136
|
-
const rendered = declaration.startsWith('export declare function')
|
|
137
|
-
? declaration
|
|
138
|
-
: declaration.startsWith('function ')
|
|
139
|
-
? `export declare ${declaration}`
|
|
140
|
-
: `export declare function ${fn.name}${declaration}`
|
|
141
|
-
out.push(`${rendered};`, '')
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
const stale = Object.keys(CALLBACK_REFINEMENTS).filter((k) => !used.has(k))
|
|
145
|
-
if (stale.length > 0) {
|
|
146
|
-
console.error(
|
|
147
|
-
`[napi-types] refinement(s) that matched nothing: ${stale.join(', ')}\n` +
|
|
148
|
-
'[napi-types] the Rust changed under them — update or remove the entry.',
|
|
149
|
-
)
|
|
150
|
-
process.exit(1)
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
writeFileSync(output, out.join('\n'))
|
|
154
|
-
console.log(
|
|
155
|
-
`[napi-types] ${output} — ${interfaces.length} interface(s), ${structs.length} class(es), ${fns.length} function(s)`,
|
|
156
|
-
)
|