@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/standalone.ts
CHANGED
|
@@ -28,6 +28,23 @@ import { ApiKeyStrategy } from "./strategies/ApiKeyStrategy.js";
|
|
|
28
28
|
import { JwtStrategy } from "./strategies/JwtStrategy.js";
|
|
29
29
|
import { SessionStrategy } from "./strategies/SessionStrategy.js";
|
|
30
30
|
|
|
31
|
+
/**
|
|
32
|
+
* The slice of an Express-style request the middleware reads and writes.
|
|
33
|
+
* Structural, so an Express, Connect or Polka request fits without a cast.
|
|
34
|
+
*/
|
|
35
|
+
export interface StandaloneRequest {
|
|
36
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
37
|
+
/** The verification result, set on success. */
|
|
38
|
+
auth?: AuthResult;
|
|
39
|
+
/** The authenticated user, set on success (Express convention). */
|
|
40
|
+
user?: UserPayload;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The slice of an Express-style response the middleware writes to. */
|
|
44
|
+
export interface StandaloneResponse {
|
|
45
|
+
status(code: number): { json(body: unknown): unknown };
|
|
46
|
+
}
|
|
47
|
+
|
|
31
48
|
export interface Warden {
|
|
32
49
|
/** Verify a bearer token. Returns auth result with user payload. */
|
|
33
50
|
verify(token: string, strategy?: string): Promise<AuthResult>;
|
|
@@ -36,18 +53,32 @@ export interface Warden {
|
|
|
36
53
|
credentials: Record<string, unknown>,
|
|
37
54
|
strategy?: string,
|
|
38
55
|
): Promise<AuthResult>;
|
|
39
|
-
/**
|
|
40
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Mint a token for a user through a token-issuing guard: the one named, or
|
|
58
|
+
* the default guard. Rejects with `E_WARDEN_STRATEGY_CANNOT_ISSUE` when that
|
|
59
|
+
* guard mints no tokens (a session guard, an access-tokens guard).
|
|
60
|
+
*/
|
|
61
|
+
generateToken(user: UserPayload, guard?: string): Promise<string>;
|
|
41
62
|
/** The underlying AuthManager for advanced use. */
|
|
42
63
|
manager: AuthManager;
|
|
43
64
|
/** Express middleware — extracts Bearer token, verifies, attaches `req.auth`. */
|
|
44
65
|
expressMiddleware(): (
|
|
45
|
-
req:
|
|
46
|
-
res:
|
|
66
|
+
req: StandaloneRequest,
|
|
67
|
+
res: StandaloneResponse,
|
|
47
68
|
next: () => void,
|
|
48
69
|
) => void;
|
|
49
70
|
}
|
|
50
71
|
|
|
72
|
+
/** Send one JSON error, shaped like the Ream middleware's. */
|
|
73
|
+
function fail(
|
|
74
|
+
res: StandaloneResponse,
|
|
75
|
+
status: number,
|
|
76
|
+
code: string,
|
|
77
|
+
message: string,
|
|
78
|
+
): void {
|
|
79
|
+
res.status(status).json({ error: { code, message } });
|
|
80
|
+
}
|
|
81
|
+
|
|
51
82
|
/**
|
|
52
83
|
* Create a standalone Warden instance — no Ream container needed.
|
|
53
84
|
*/
|
|
@@ -86,46 +117,58 @@ export function createWarden(config: WardenConfig): Warden {
|
|
|
86
117
|
authenticate: (credentials, strategy) =>
|
|
87
118
|
manager.authenticate(credentials, strategy),
|
|
88
119
|
|
|
89
|
-
async generateToken(user: UserPayload): Promise<string> {
|
|
90
|
-
|
|
91
|
-
|
|
120
|
+
async generateToken(user: UserPayload, guard?: string): Promise<string> {
|
|
121
|
+
// The guard the application configured, not one named `jwt`: a
|
|
122
|
+
// `guards: { api: jwtGuard(...) }` config has no guard by that name.
|
|
123
|
+
return manager.issueFor(user, guard);
|
|
92
124
|
},
|
|
93
125
|
|
|
94
126
|
manager,
|
|
95
127
|
|
|
96
128
|
expressMiddleware() {
|
|
97
129
|
return (req, res, next) => {
|
|
98
|
-
const
|
|
99
|
-
const authHeader = headers?.authorization ?? "";
|
|
130
|
+
const authHeader = req.headers?.authorization;
|
|
100
131
|
const token =
|
|
101
132
|
typeof authHeader === "string" && authHeader.startsWith("Bearer ")
|
|
102
133
|
? authHeader.slice(7)
|
|
103
134
|
: "";
|
|
104
135
|
|
|
105
136
|
if (!token) {
|
|
106
|
-
(
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
},
|
|
113
|
-
});
|
|
137
|
+
fail(
|
|
138
|
+
res,
|
|
139
|
+
401,
|
|
140
|
+
"E_WARDEN_UNAUTHORIZED",
|
|
141
|
+
"Missing authentication token",
|
|
142
|
+
);
|
|
114
143
|
return;
|
|
115
144
|
}
|
|
116
145
|
|
|
117
146
|
manager
|
|
118
147
|
.verify(token)
|
|
119
148
|
.then((result) => {
|
|
149
|
+
if (result.strategyCrash === true) {
|
|
150
|
+
// The guard threw — a database down, a bug — which is a
|
|
151
|
+
// server incident, not a bad credential: a 500, and a
|
|
152
|
+
// generic message. The thrown text (a host, a port, a
|
|
153
|
+
// query) is for the logs, never for the client.
|
|
154
|
+
console.error(
|
|
155
|
+
`[warden] strategy threw during verify(): ${result.error ?? "unknown error"}`,
|
|
156
|
+
);
|
|
157
|
+
fail(
|
|
158
|
+
res,
|
|
159
|
+
500,
|
|
160
|
+
"E_WARDEN_AUTH_STRATEGY_ERROR",
|
|
161
|
+
"Authentication unavailable. Check server logs.",
|
|
162
|
+
);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
120
165
|
if (!result.authenticated || !result.user) {
|
|
121
|
-
(
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
},
|
|
128
|
-
});
|
|
166
|
+
fail(
|
|
167
|
+
res,
|
|
168
|
+
401,
|
|
169
|
+
"E_WARDEN_UNAUTHORIZED",
|
|
170
|
+
result.error ?? "Authentication failed",
|
|
171
|
+
);
|
|
129
172
|
return;
|
|
130
173
|
}
|
|
131
174
|
// Attach auth result to the request object (Express convention).
|
|
@@ -134,14 +177,12 @@ export function createWarden(config: WardenConfig): Warden {
|
|
|
134
177
|
next();
|
|
135
178
|
})
|
|
136
179
|
.catch(() => {
|
|
137
|
-
(
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
},
|
|
144
|
-
});
|
|
180
|
+
fail(
|
|
181
|
+
res,
|
|
182
|
+
500,
|
|
183
|
+
"E_WARDEN_AUTH_ERROR",
|
|
184
|
+
"Internal authentication error",
|
|
185
|
+
);
|
|
145
186
|
});
|
|
146
187
|
};
|
|
147
188
|
},
|
|
@@ -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,71 @@ 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
|
+
* NAMED DEVIATION — upstream's guard is built per request and revokes the
|
|
115
|
+
* token it authenticated with, so it takes no argument. A warden strategy
|
|
116
|
+
* is shared by every request and keeps none of them, so the value is passed
|
|
117
|
+
* in; a sign-out handler has it, it is the request's credential.
|
|
57
118
|
*/
|
|
58
|
-
|
|
59
|
-
return
|
|
60
|
-
headers: {
|
|
61
|
-
authorization: `Bearer ${key}`,
|
|
62
|
-
[this.#headerName]: key,
|
|
63
|
-
},
|
|
64
|
-
};
|
|
119
|
+
invalidateToken(value: string): Promise<boolean> {
|
|
120
|
+
return this.#config.tokens.invalidate(new Secret(value));
|
|
65
121
|
}
|
|
66
122
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
123
|
+
/**
|
|
124
|
+
* What a test client sends to be `user`: a real token, minted through the
|
|
125
|
+
* provider, so the test authenticates the way the application will.
|
|
126
|
+
*/
|
|
127
|
+
async authenticateAsClient(
|
|
128
|
+
user: TokenOwner,
|
|
129
|
+
abilities?: string[],
|
|
130
|
+
options?: CreateAccessTokenOptions,
|
|
131
|
+
): Promise<AuthClientResponse> {
|
|
132
|
+
const token = await this.createToken(user, abilities, options);
|
|
133
|
+
const value = token.value?.release();
|
|
134
|
+
if (value === undefined) {
|
|
135
|
+
throw new WardenError(
|
|
136
|
+
"INVALID_CONFIG",
|
|
137
|
+
"The token provider returned a token without its value from create().",
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
return { headers: { authorization: `Bearer ${value}` } };
|
|
141
|
+
}
|
|
70
142
|
|
|
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];
|
|
143
|
+
async verify(token: string): Promise<AuthResult> {
|
|
144
|
+
const accessToken = await this.#config.tokens.verify(new Secret(token));
|
|
145
|
+
if (accessToken === null) {
|
|
146
|
+
return { authenticated: false, error: "Invalid access token" };
|
|
147
|
+
}
|
|
148
|
+
const user = await this.#config.findUser(accessToken.tokenableId);
|
|
149
|
+
if (!user) {
|
|
150
|
+
return {
|
|
151
|
+
authenticated: false,
|
|
152
|
+
error: "The account behind this token is no longer available",
|
|
153
|
+
};
|
|
89
154
|
}
|
|
90
|
-
|
|
155
|
+
// A copy: the provider's object is the application's, and attaching the
|
|
156
|
+
// token to it would leak one request's token into the next.
|
|
157
|
+
return {
|
|
158
|
+
authenticated: true,
|
|
159
|
+
user: { ...user, currentAccessToken: accessToken },
|
|
160
|
+
};
|
|
91
161
|
}
|
|
92
162
|
}
|
|
@@ -11,7 +11,7 @@ import type {
|
|
|
11
11
|
UserPayload,
|
|
12
12
|
} from "../AuthManager.js";
|
|
13
13
|
import { resolveExpiresInSeconds, type TokenDuration } from "../duration.js";
|
|
14
|
-
import { nativeWarden } from "../native.js";
|
|
14
|
+
import { nativeWarden, nativeWardenLoadError } from "../native.js";
|
|
15
15
|
import type { TokenBlacklist } from "../TokenBlacklist.js";
|
|
16
16
|
|
|
17
17
|
/**
|
|
@@ -47,6 +47,7 @@ function sign(payload: JwtClaims, secret: string): string {
|
|
|
47
47
|
if (!rust) {
|
|
48
48
|
throw new Error(
|
|
49
49
|
"[E_WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
|
|
50
|
+
{ cause: nativeWardenLoadError() },
|
|
50
51
|
);
|
|
51
52
|
}
|
|
52
53
|
return rust.jwtSign(JSON.stringify(payload), secret);
|
|
@@ -57,6 +58,7 @@ function verify(token: string, secret: string): JwtClaims | null {
|
|
|
57
58
|
if (!rust) {
|
|
58
59
|
throw new Error(
|
|
59
60
|
"[E_WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
|
|
61
|
+
{ cause: nativeWardenLoadError() },
|
|
60
62
|
);
|
|
61
63
|
}
|
|
62
64
|
try {
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { WardenError } from "./errors.js";
|
|
2
|
+
|
|
3
|
+
/** The only surface warden needs of a template engine. */
|
|
4
|
+
export interface TemplateEngineLike {
|
|
5
|
+
registerTag(tag: {
|
|
6
|
+
tagName: string;
|
|
7
|
+
block: boolean;
|
|
8
|
+
seekable: boolean;
|
|
9
|
+
compile(
|
|
10
|
+
parser: unknown,
|
|
11
|
+
buffer: { writeRaw(text: string): void },
|
|
12
|
+
token: {
|
|
13
|
+
properties: { jsArg: string };
|
|
14
|
+
renderBody(): string | Promise<string>;
|
|
15
|
+
evaluate(expression: string): unknown;
|
|
16
|
+
},
|
|
17
|
+
): void | Promise<void>;
|
|
18
|
+
}): void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Register `@can` / `@cannot`, as AdonisJS's bouncer publishes them. A
|
|
23
|
+
* migrated template keeps `@can('PostPolicy.edit', post) … @endcan` unchanged.
|
|
24
|
+
*
|
|
25
|
+
* Both are BLOCK tags and both AWAIT — the check returns a promise — so they
|
|
26
|
+
* render on the async path and raise on a synchronous one, matching upstream
|
|
27
|
+
* (which emits `await bouncer.can(...)`). The checks themselves come from
|
|
28
|
+
* `ctx.bouncer.templateHelpers`, shared into the view per request.
|
|
29
|
+
*/
|
|
30
|
+
export function registerBouncerTemplateTags(engine: TemplateEngineLike): void {
|
|
31
|
+
for (const tagName of ["can", "cannot"] as const) {
|
|
32
|
+
engine.registerTag({
|
|
33
|
+
tagName,
|
|
34
|
+
block: true,
|
|
35
|
+
seekable: true,
|
|
36
|
+
async compile(_parser, buffer, token) {
|
|
37
|
+
// The shared bag lives in the render scope under `bouncer`.
|
|
38
|
+
const bouncer = token.evaluate(
|
|
39
|
+
"typeof bouncer === 'undefined' ? undefined : bouncer",
|
|
40
|
+
);
|
|
41
|
+
const check = Reflect.get(Object(bouncer), tagName);
|
|
42
|
+
if (typeof check !== "function") {
|
|
43
|
+
// No bouncer on this request: deny rather than render an
|
|
44
|
+
// unguarded body.
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const args = token.evaluate(`[${token.properties.jsArg}]`);
|
|
48
|
+
const allowed = await check.apply(
|
|
49
|
+
bouncer,
|
|
50
|
+
Array.isArray(args) ? args : [],
|
|
51
|
+
);
|
|
52
|
+
if (allowed === true) buffer.writeRaw(await token.renderBody());
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Loads the template engine package. Swappable so a test needs no engine. */
|
|
59
|
+
export type EnginePackageLoader = () => Promise<unknown>;
|
|
60
|
+
|
|
61
|
+
const loadInker: EnginePackageLoader = () => {
|
|
62
|
+
// Built rather than written inline: inker is an OPTIONAL peer, and a
|
|
63
|
+
// literal `import("@c9up/inker")` makes a bundler resolve it at build time
|
|
64
|
+
// for an application that never installed it. Computed, it only runs
|
|
65
|
+
// behind the `usingInker` flag.
|
|
66
|
+
const specifier = "@c9up/inker";
|
|
67
|
+
return import(/* @vite-ignore */ specifier);
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
function unusable(detail: string): WardenError {
|
|
71
|
+
return new WardenError(
|
|
72
|
+
"E_WARDEN_TEMPLATE_ENGINE_UNUSABLE",
|
|
73
|
+
`The template engine is installed but @can / @cannot cannot be registered: ${detail}`,
|
|
74
|
+
{
|
|
75
|
+
hint: "`@c9up/inker` must default-export its plugin registrar (`inker.use(plugin)`), whose plugins receive an engine with `registerTag()`.",
|
|
76
|
+
},
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Publish the bouncer tags the way AdonisJS's bouncer does with Edge: through
|
|
82
|
+
* the engine package's MODULE SINGLETON (`inker.use(plugin)`), guarded by the
|
|
83
|
+
* host's `usingInker` flag — never by resolving a container binding. `use()`
|
|
84
|
+
* queues the plugin and the engine runs it before its next render, whenever
|
|
85
|
+
* the engine was built.
|
|
86
|
+
*
|
|
87
|
+
* Returns whether the tags were handed over. A registrar or an engine of the
|
|
88
|
+
* wrong shape is an error, not a skip: an unregistered `@can` would render as
|
|
89
|
+
* plain text and show the guarded body's markup to everyone.
|
|
90
|
+
*/
|
|
91
|
+
export async function installBouncerTemplateTags(
|
|
92
|
+
usingInker: boolean,
|
|
93
|
+
load: EnginePackageLoader = loadInker,
|
|
94
|
+
): Promise<boolean> {
|
|
95
|
+
if (!usingInker) return false;
|
|
96
|
+
const module: unknown = await load();
|
|
97
|
+
const registrar =
|
|
98
|
+
typeof module === "object" && module !== null
|
|
99
|
+
? Reflect.get(module, "default")
|
|
100
|
+
: undefined;
|
|
101
|
+
const use = Reflect.get(Object(registrar), "use");
|
|
102
|
+
if (typeof use !== "function") {
|
|
103
|
+
throw unusable("its default export has no use()");
|
|
104
|
+
}
|
|
105
|
+
use.call(registrar, (engine: unknown) => {
|
|
106
|
+
const register = Reflect.get(Object(engine), "registerTag");
|
|
107
|
+
if (typeof register !== "function") {
|
|
108
|
+
throw unusable("the engine has no registerTag()");
|
|
109
|
+
}
|
|
110
|
+
registerBouncerTemplateTags({
|
|
111
|
+
registerTag: (tag) => {
|
|
112
|
+
register.call(engine, tag);
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
@@ -87,24 +87,100 @@ export type NativeBinaryResult<T> =
|
|
|
87
87
|
| { loaded: true; binary: T }
|
|
88
88
|
| { loaded: false; suffix: string | undefined; cause?: unknown };
|
|
89
89
|
|
|
90
|
+
/** Whether `value` carries a function under `name` (a napi class is one too). */
|
|
91
|
+
function hasFunction(value: object, name: string): boolean {
|
|
92
|
+
const member: unknown = Reflect.get(value, name);
|
|
93
|
+
return typeof member === "function";
|
|
94
|
+
}
|
|
95
|
+
|
|
90
96
|
/**
|
|
91
|
-
*
|
|
97
|
+
* The names among `names` that `value` does not carry as functions.
|
|
98
|
+
*
|
|
99
|
+
* Classes count, being functions, and so does a class's static member: `value`
|
|
100
|
+
* may itself be a function. What a guard rejects is only useful named, so the
|
|
101
|
+
* loader reports this list rather than a bare "no".
|
|
102
|
+
*/
|
|
103
|
+
export function missingFunctions(
|
|
104
|
+
value: unknown,
|
|
105
|
+
names: readonly string[],
|
|
106
|
+
): string[] {
|
|
107
|
+
if (
|
|
108
|
+
value === null ||
|
|
109
|
+
(typeof value !== "object" && typeof value !== "function")
|
|
110
|
+
) {
|
|
111
|
+
return [...names];
|
|
112
|
+
}
|
|
113
|
+
return names.filter((name) => !hasFunction(value, name));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Whether `value` carries every one of `names` as a function.
|
|
118
|
+
*
|
|
119
|
+
* The building block of the guard a package hands to `loadNativeBinary`, over
|
|
120
|
+
* the list of what it actually calls on its binary — the same list it passes
|
|
121
|
+
* as `expects`, so the message can name what is missing.
|
|
122
|
+
*/
|
|
123
|
+
export function hasFunctions(
|
|
124
|
+
value: unknown,
|
|
125
|
+
names: readonly string[],
|
|
126
|
+
): value is object {
|
|
127
|
+
if (
|
|
128
|
+
value === null ||
|
|
129
|
+
(typeof value !== "object" && typeof value !== "function")
|
|
130
|
+
) {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
return missingFunctions(value, names).length === 0;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Load `<package root>/index.<suffix>.node`, and check it is the binary the
|
|
138
|
+
* package calls.
|
|
92
139
|
*
|
|
93
140
|
* The path is fixed rather than passed: this file is generated into
|
|
94
141
|
* `<package>/src/vendor/`, so the package root is always two levels up, from
|
|
95
142
|
* `src` and from `dist` alike.
|
|
143
|
+
*
|
|
144
|
+
* `isBinary` is the package's own check of what it calls. A declaration only
|
|
145
|
+
* says what the Rust promises: a stale build, or one from another version,
|
|
146
|
+
* loads just as well and then fails on the first missing call, far from here.
|
|
147
|
+
* A rejected module is reported as a failed load, so the package's policy
|
|
148
|
+
* (degrade or refuse) applies to it unchanged. `expects`, the list the guard is
|
|
149
|
+
* built from, lets that report name the missing calls.
|
|
96
150
|
*/
|
|
97
|
-
export function loadNativeBinary<T>(
|
|
151
|
+
export function loadNativeBinary<T>(
|
|
152
|
+
isBinary: (value: unknown) => value is T,
|
|
153
|
+
expects?: readonly string[],
|
|
154
|
+
): NativeBinaryResult<T> {
|
|
98
155
|
const suffix = nativeBinarySuffix();
|
|
99
156
|
if (suffix === undefined) return { loaded: false, suffix };
|
|
100
157
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
158
|
+
let loaded: unknown;
|
|
101
159
|
try {
|
|
102
160
|
const nodeRequire = createRequire(import.meta.url);
|
|
103
|
-
|
|
104
|
-
loaded: true,
|
|
105
|
-
binary: nodeRequire(join(here, `../../index.${suffix}.node`)) as T,
|
|
106
|
-
};
|
|
161
|
+
loaded = nodeRequire(join(here, `../../index.${suffix}.node`));
|
|
107
162
|
} catch (cause) {
|
|
108
163
|
return { loaded: false, suffix, cause };
|
|
109
164
|
}
|
|
165
|
+
if (isBinary(loaded)) return { loaded: true, binary: loaded };
|
|
166
|
+
return {
|
|
167
|
+
loaded: false,
|
|
168
|
+
suffix,
|
|
169
|
+
cause: new Error(
|
|
170
|
+
`index.${suffix}.node loaded, but ${rejection(loaded, expects)}. ` +
|
|
171
|
+
"The binary is stale or from another version: rebuild it.",
|
|
172
|
+
),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** What a rejected binary lacks, or, without a list to check, what it has. */
|
|
177
|
+
function rejection(loaded: unknown, expects?: readonly string[]): string {
|
|
178
|
+
const missing =
|
|
179
|
+
expects === undefined ? [] : missingFunctions(loaded, expects);
|
|
180
|
+
if (missing.length > 0) return `it lacks ${missing.join(", ")}`;
|
|
181
|
+
const exported =
|
|
182
|
+
typeof loaded === "object" && loaded !== null
|
|
183
|
+
? Object.keys(loaded).filter((name) => hasFunction(loaded, name))
|
|
184
|
+
: [];
|
|
185
|
+
return `it is not the binary this package calls (it exports: ${exported.length > 0 ? exported.join(", ") : "none"})`;
|
|
110
186
|
}
|