@open-artifact/host-plugin 0.0.0-stage → 0.13.0
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/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +191 -2
- package/package.json +42 -4
- package/src/contract.d.ts +264 -0
- package/src/contract.js +1000 -0
- package/src/index.d.ts +832 -0
- package/src/index.js +338 -0
- package/src/testing.d.ts +169 -0
- package/src/testing.js +364 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@open-artifact/host-plugin`: the plugin API of the Open Artifact cloud host, version 1.
|
|
3
|
+
*
|
|
4
|
+
* A plugin is a plain object exported by an ES module:
|
|
5
|
+
*
|
|
6
|
+
* ```js
|
|
7
|
+
* export default {
|
|
8
|
+
* id: 'hello',
|
|
9
|
+
* apiVersion: 1,
|
|
10
|
+
* on: { 'artifact.created': (event, ctx) => ctx.log(`${event.by.name} made ${event.artifact.title}`) },
|
|
11
|
+
* };
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* It needs nothing from this package. Import it for editor help ({@link definePlugin}, the types), for the small helpers
|
|
15
|
+
* at the end of this file (JSON answers, request bodies, HMAC signatures, JWTs), and for the test kit
|
|
16
|
+
* (`@open-artifact/host-plugin/testing`).
|
|
17
|
+
*
|
|
18
|
+
* How a plugin talks to the host: only through its hooks, each `(input, ctx) => result`, with Web-standard types
|
|
19
|
+
* (`Request`, `Response`, `fetch`, WebCrypto), so one plugin runs on the Node host and on Cloudflare alike.
|
|
20
|
+
*
|
|
21
|
+
* The stability promise (API version 1): the host may add fields to every input, every event and `ctx`, and may add
|
|
22
|
+
* hooks, events and guard actions, at any release. Your plugin keeps working as long as it ignores what it does not
|
|
23
|
+
* know. Removing or changing anything here is a new `apiVersion`, and the host keeps running plugins of the previous
|
|
24
|
+
* version for at least one release cycle. `ctx.host.supports(name)` tells you whether this host has a feature.
|
|
25
|
+
*
|
|
26
|
+
* Failure policy: every hook call has a time limit (5 s unless the operator sets `timeoutMs`). Sign-in, permission
|
|
27
|
+
* and guard hooks fail CLOSED (an error, a timeout or an answer of the wrong shape means: not signed in, no access,
|
|
28
|
+
* denied). Event handlers and `wake.deliver` fail OPEN (the host logs it and carries on as if the plugin were absent).
|
|
29
|
+
*
|
|
30
|
+
* A time limit stops waiting, not running: it cannot interrupt a plugin stuck in synchronous code (a busy loop, a
|
|
31
|
+
* huge regular expression). Such a plugin holds up the whole host process (or Worker isolate), so keep hooks
|
|
32
|
+
* asynchronous and short.
|
|
33
|
+
*/
|
|
34
|
+
/** The plugin API version this package describes. A plugin sets `apiVersion` to it. */
|
|
35
|
+
export const PLUGIN_API_VERSION = 1;
|
|
36
|
+
/**
|
|
37
|
+
* Returns the plugin as it is. It only gives your editor the types: with it, `ctx.config` in every hook has the
|
|
38
|
+
* settings your `config` schema declares.
|
|
39
|
+
*
|
|
40
|
+
* ```ts
|
|
41
|
+
* export default definePlugin({
|
|
42
|
+
* id: 'hello', apiVersion: 1,
|
|
43
|
+
* config: { greeting: { type: 'string', default: 'Hello' } },
|
|
44
|
+
* on: { 'user.signed_in': (e, ctx) => ctx.log(`${ctx.config.greeting}, ${e.user.name}`) },
|
|
45
|
+
* });
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export function definePlugin(plugin) {
|
|
49
|
+
return plugin;
|
|
50
|
+
}
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
// Helpers: HTTP
|
|
53
|
+
/**
|
|
54
|
+
* An error a route handler throws to answer with a status: `throw new HttpError(403, 'Bad signature.')` answers
|
|
55
|
+
* `403 {"code": "plugin_error", "message": "Bad signature."}`. Any other error answers a generic 500 (and is logged).
|
|
56
|
+
*/
|
|
57
|
+
export class HttpError extends Error {
|
|
58
|
+
status;
|
|
59
|
+
constructor(status, message) {
|
|
60
|
+
super(message);
|
|
61
|
+
this.name = 'HttpError';
|
|
62
|
+
this.status = status >= 400 && status <= 599 ? Math.floor(status) : 500;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** A JSON answer (`Content-Type: application/json`, `Cache-Control: no-store` unless `init` sets them). */
|
|
66
|
+
export function json(value, init = {}) {
|
|
67
|
+
const headers = new Headers(init.headers);
|
|
68
|
+
if (!headers.has('content-type'))
|
|
69
|
+
headers.set('content-type', 'application/json; charset=utf-8');
|
|
70
|
+
if (!headers.has('cache-control'))
|
|
71
|
+
headers.set('cache-control', 'no-store');
|
|
72
|
+
return new Response(JSON.stringify(value), { ...init, headers });
|
|
73
|
+
}
|
|
74
|
+
/** The largest body {@link readJson} and {@link readBody} read by default: 1 MiB. */
|
|
75
|
+
export const DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
|
|
76
|
+
/** A request's whole body as bytes, refusing more than `maxBytes` (an {@link HttpError} 413). */
|
|
77
|
+
export async function readBody(request, maxBytes = DEFAULT_MAX_BODY_BYTES) {
|
|
78
|
+
const declared = Number(request.headers.get('content-length'));
|
|
79
|
+
if (Number.isFinite(declared) && declared > maxBytes)
|
|
80
|
+
throw new HttpError(413, `The request body is larger than ${maxBytes} bytes.`);
|
|
81
|
+
if (!request.body)
|
|
82
|
+
return new Uint8Array(0);
|
|
83
|
+
const reader = request.body.getReader();
|
|
84
|
+
const chunks = [];
|
|
85
|
+
let size = 0;
|
|
86
|
+
for (;;) {
|
|
87
|
+
const step = await reader.read();
|
|
88
|
+
if (step.done)
|
|
89
|
+
break;
|
|
90
|
+
size += step.value.byteLength;
|
|
91
|
+
if (size > maxBytes) {
|
|
92
|
+
await reader.cancel().catch(() => undefined);
|
|
93
|
+
throw new HttpError(413, `The request body is larger than ${maxBytes} bytes.`);
|
|
94
|
+
}
|
|
95
|
+
chunks.push(step.value);
|
|
96
|
+
}
|
|
97
|
+
const out = new Uint8Array(size);
|
|
98
|
+
let offset = 0;
|
|
99
|
+
for (const chunk of chunks) {
|
|
100
|
+
out.set(chunk, offset);
|
|
101
|
+
offset += chunk.byteLength;
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
/** A request's body as text (UTF-8): what a signature is checked over. */
|
|
106
|
+
export async function readText(request, maxBytes = DEFAULT_MAX_BODY_BYTES) {
|
|
107
|
+
return new TextDecoder().decode(await readBody(request, maxBytes));
|
|
108
|
+
}
|
|
109
|
+
/** A request's body as JSON (an {@link HttpError} 400 when it is not JSON, 413 past `maxBytes`). */
|
|
110
|
+
export async function readJson(request, maxBytes = DEFAULT_MAX_BODY_BYTES) {
|
|
111
|
+
const text = await readText(request, maxBytes);
|
|
112
|
+
try {
|
|
113
|
+
return JSON.parse(text);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
throw new HttpError(400, 'The request body is not JSON.');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// Helpers: comparing secrets and signatures
|
|
121
|
+
const encoder = new TextEncoder();
|
|
122
|
+
const bytesOf = (value) => (typeof value === 'string' ? encoder.encode(value) : value);
|
|
123
|
+
/**
|
|
124
|
+
* Whether two secrets are equal, taking the same time whatever their content (so the time an answer takes does not
|
|
125
|
+
* tell an attacker how much of a guess was right). Use it instead of `===` for every secret and signature.
|
|
126
|
+
*/
|
|
127
|
+
export function timingSafeEqual(a, b) {
|
|
128
|
+
const x = bytesOf(a);
|
|
129
|
+
const y = bytesOf(b);
|
|
130
|
+
const length = Math.max(x.length, y.length);
|
|
131
|
+
let diff = x.length ^ y.length;
|
|
132
|
+
for (let i = 0; i < length; i++)
|
|
133
|
+
diff |= (x[i] ?? 0) ^ (y[i] ?? 0);
|
|
134
|
+
return diff === 0;
|
|
135
|
+
}
|
|
136
|
+
function toHex(bytes) {
|
|
137
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
138
|
+
}
|
|
139
|
+
function toBase64(bytes) {
|
|
140
|
+
let binary = '';
|
|
141
|
+
for (const b of bytes)
|
|
142
|
+
binary += String.fromCharCode(b);
|
|
143
|
+
return btoa(binary);
|
|
144
|
+
}
|
|
145
|
+
function encodeBytes(bytes, encoding) {
|
|
146
|
+
if (encoding === 'hex')
|
|
147
|
+
return toHex(bytes);
|
|
148
|
+
const base64 = toBase64(bytes);
|
|
149
|
+
return encoding === 'base64' ? base64 : base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
150
|
+
}
|
|
151
|
+
async function hmac(secret, body) {
|
|
152
|
+
const key = await crypto.subtle.importKey('raw', bytesOf(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
153
|
+
return new Uint8Array(await crypto.subtle.sign('HMAC', key, bytesOf(body)));
|
|
154
|
+
}
|
|
155
|
+
/** The HMAC-SHA256 of `body` under `secret`, written in `encoding` (default hex): to sign what a plugin sends. */
|
|
156
|
+
export async function signHmacSha256(input) {
|
|
157
|
+
return encodeBytes(await hmac(input.secret, input.body), input.encoding ?? 'hex');
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Whether `signature` is the HMAC-SHA256 of `body` under `secret` (compared in constant time). `body` must be the
|
|
161
|
+
* exact bytes received ({@link readText}), not re-serialized JSON. A `prefix` such as `sha256=` is removed from the
|
|
162
|
+
* signature first when present. Hex is compared without regard to case.
|
|
163
|
+
*/
|
|
164
|
+
export async function verifyHmacSha256(input) {
|
|
165
|
+
if (!input.signature)
|
|
166
|
+
return false;
|
|
167
|
+
let given = input.signature.trim();
|
|
168
|
+
if (input.prefix && given.startsWith(input.prefix))
|
|
169
|
+
given = given.slice(input.prefix.length);
|
|
170
|
+
const encoding = input.encoding ?? 'hex';
|
|
171
|
+
if (encoding === 'hex')
|
|
172
|
+
given = given.toLowerCase();
|
|
173
|
+
if (encoding === 'base64url')
|
|
174
|
+
given = given.replace(/=+$/, '');
|
|
175
|
+
const expected = encodeBytes(await hmac(input.secret, input.body), encoding);
|
|
176
|
+
return timingSafeEqual(given, expected);
|
|
177
|
+
}
|
|
178
|
+
function base64urlDecode(text) {
|
|
179
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text))
|
|
180
|
+
return null;
|
|
181
|
+
try {
|
|
182
|
+
const binary = atob(text.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (text.length % 4)) % 4));
|
|
183
|
+
const out = new Uint8Array(binary.length);
|
|
184
|
+
for (let i = 0; i < binary.length; i++)
|
|
185
|
+
out[i] = binary.charCodeAt(i);
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function decodeJsonPart(part) {
|
|
193
|
+
const bytes = base64urlDecode(part);
|
|
194
|
+
if (!bytes)
|
|
195
|
+
return null;
|
|
196
|
+
try {
|
|
197
|
+
const value = JSON.parse(new TextDecoder().decode(bytes));
|
|
198
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : null;
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
const JWKS_TTL_MS = 10 * 60_000;
|
|
205
|
+
const JWKS_REFRESH_MS = 30_000;
|
|
206
|
+
const jwksCache = new Map();
|
|
207
|
+
async function jwksKeys(url, fetcher, now, refresh) {
|
|
208
|
+
const kept = jwksCache.get(url);
|
|
209
|
+
if (kept && !refresh && now - kept.at < JWKS_TTL_MS)
|
|
210
|
+
return kept.keys;
|
|
211
|
+
// An unknown `kid` refetches, but at most every 30 seconds: tokens with made-up kids must not hammer the key server.
|
|
212
|
+
if (kept && refresh && now - kept.at < JWKS_REFRESH_MS)
|
|
213
|
+
return kept.keys;
|
|
214
|
+
const response = await fetcher(url, { headers: { accept: 'application/json' } });
|
|
215
|
+
if (!response.ok)
|
|
216
|
+
throw new Error(`the key set at ${url} answered ${response.status}`);
|
|
217
|
+
const body = (await response.json());
|
|
218
|
+
const keys = Array.isArray(body.keys) ? body.keys.filter((k) => typeof k === 'object' && k !== null) : [];
|
|
219
|
+
jwksCache.set(url, { keys, at: now });
|
|
220
|
+
return keys;
|
|
221
|
+
}
|
|
222
|
+
/** Whether a key can verify `alg`: an RSA public key for RS256, a P-256 key for ES256, a symmetric key for HS256. */
|
|
223
|
+
function keyFits(key, alg) {
|
|
224
|
+
if (key.use !== undefined && key.use !== 'sig')
|
|
225
|
+
return false;
|
|
226
|
+
if (key.alg !== undefined && key.alg !== alg)
|
|
227
|
+
return false;
|
|
228
|
+
if (alg === 'RS256')
|
|
229
|
+
return key.kty === 'RSA' && typeof key.n === 'string' && typeof key.e === 'string';
|
|
230
|
+
if (alg === 'ES256')
|
|
231
|
+
return key.kty === 'EC' && key.crv === 'P-256' && typeof key.x === 'string' && typeof key.y === 'string';
|
|
232
|
+
return key.kty === 'oct' && typeof key.k === 'string';
|
|
233
|
+
}
|
|
234
|
+
async function verifySignature(alg, key, data, signature) {
|
|
235
|
+
try {
|
|
236
|
+
if (alg === 'RS256') {
|
|
237
|
+
const imported = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: key.n, e: key.e }, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']);
|
|
238
|
+
return await crypto.subtle.verify('RSASSA-PKCS1-v1_5', imported, signature, data);
|
|
239
|
+
}
|
|
240
|
+
if (alg === 'ES256') {
|
|
241
|
+
// A JWS ES256 signature is raw r||s (64 bytes), which is what WebCrypto's ECDSA takes.
|
|
242
|
+
if (signature.length !== 64)
|
|
243
|
+
return false;
|
|
244
|
+
const imported = await crypto.subtle.importKey('jwk', { kty: 'EC', crv: 'P-256', x: key.x, y: key.y }, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
|
|
245
|
+
return await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, imported, signature, data);
|
|
246
|
+
}
|
|
247
|
+
const secret = base64urlDecode(key.k ?? '');
|
|
248
|
+
if (!secret || secret.length === 0)
|
|
249
|
+
return false;
|
|
250
|
+
const imported = await crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
|
|
251
|
+
return await crypto.subtle.verify('HMAC', imported, signature, data);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const ALGORITHMS = ['RS256', 'ES256', 'HS256'];
|
|
258
|
+
/**
|
|
259
|
+
* Verifies a compact JWT (JWS): its signature (RS256 and ES256 with public keys, HS256 with a shared secret; never
|
|
260
|
+
* `none`, and never an algorithm the key is not for), then `exp`, `nbf`, `iss` and `aud`. Keys come from `key` or
|
|
261
|
+
* from `jwksUrl` (by the token's `kid`; an unknown `kid` refetches the set once). Pass `ctx.fetch` as `fetcher`.
|
|
262
|
+
* Never throws for a bad token: the answer says why.
|
|
263
|
+
*/
|
|
264
|
+
export async function verifyJwt(options, fetcher = (input, init) => fetch(input, init)) {
|
|
265
|
+
const parts = options.token.split('.');
|
|
266
|
+
if (parts.length !== 3)
|
|
267
|
+
return { valid: false, reason: 'not a JWT' };
|
|
268
|
+
const [h, p, s] = parts;
|
|
269
|
+
const header = decodeJsonPart(h);
|
|
270
|
+
const claims = decodeJsonPart(p);
|
|
271
|
+
const signature = base64urlDecode(s);
|
|
272
|
+
if (!header || !claims || !signature || typeof header.alg !== 'string')
|
|
273
|
+
return { valid: false, reason: 'not a JWT' };
|
|
274
|
+
const alg = header.alg;
|
|
275
|
+
const accepted = options.algorithms ?? ALGORITHMS;
|
|
276
|
+
if (!ALGORITHMS.includes(alg) || !accepted.includes(alg))
|
|
277
|
+
return { valid: false, reason: `algorithm ${alg} is not accepted` };
|
|
278
|
+
const algorithm = alg;
|
|
279
|
+
const kid = typeof header.kid === 'string' ? header.kid : undefined;
|
|
280
|
+
const nowDate = options.now ?? new Date();
|
|
281
|
+
let candidates;
|
|
282
|
+
if (options.key !== undefined) {
|
|
283
|
+
const key = typeof options.key === 'string' ? { kty: 'oct', k: encodeBytes(encoder.encode(options.key), 'base64url') } : options.key;
|
|
284
|
+
candidates = [key];
|
|
285
|
+
}
|
|
286
|
+
else if (options.jwksUrl) {
|
|
287
|
+
try {
|
|
288
|
+
candidates = await jwksKeys(options.jwksUrl, fetcher, nowDate.getTime(), false);
|
|
289
|
+
if (kid !== undefined && !candidates.some((k) => k.kid === kid))
|
|
290
|
+
candidates = await jwksKeys(options.jwksUrl, fetcher, nowDate.getTime(), true);
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
return { valid: false, reason: `the signing keys could not be fetched: ${error instanceof Error ? error.message : String(error)}`, unavailable: true };
|
|
294
|
+
}
|
|
295
|
+
if (kid !== undefined)
|
|
296
|
+
candidates = candidates.filter((k) => k.kid === kid);
|
|
297
|
+
}
|
|
298
|
+
else {
|
|
299
|
+
return { valid: false, reason: 'no key or jwksUrl to verify with' };
|
|
300
|
+
}
|
|
301
|
+
const fitting = candidates.filter((k) => keyFits(k, algorithm));
|
|
302
|
+
if (fitting.length === 0)
|
|
303
|
+
return { valid: false, reason: `no ${algorithm} key${kid ? ` with kid ${kid}` : ''}` };
|
|
304
|
+
const data = encoder.encode(`${h}.${p}`);
|
|
305
|
+
let verified = false;
|
|
306
|
+
for (const key of fitting) {
|
|
307
|
+
if (await verifySignature(algorithm, key, data, signature)) {
|
|
308
|
+
verified = true;
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (!verified)
|
|
313
|
+
return { valid: false, reason: 'bad signature' };
|
|
314
|
+
const now = nowDate.getTime() / 1000;
|
|
315
|
+
const tolerance = options.clockToleranceSeconds ?? 60;
|
|
316
|
+
if (claims.exp === undefined) {
|
|
317
|
+
if (options.requireExpiry !== false)
|
|
318
|
+
return { valid: false, reason: 'no expiry (exp)' };
|
|
319
|
+
}
|
|
320
|
+
else if (typeof claims.exp !== 'number' || now - tolerance >= claims.exp) {
|
|
321
|
+
return { valid: false, reason: 'expired' };
|
|
322
|
+
}
|
|
323
|
+
if (claims.nbf !== undefined && (typeof claims.nbf !== 'number' || now + tolerance < claims.nbf))
|
|
324
|
+
return { valid: false, reason: 'not valid yet (nbf)' };
|
|
325
|
+
if (options.issuer !== undefined && claims.iss !== options.issuer)
|
|
326
|
+
return { valid: false, reason: 'wrong issuer' };
|
|
327
|
+
if (options.audience !== undefined) {
|
|
328
|
+
const wanted = Array.isArray(options.audience) ? options.audience : [options.audience];
|
|
329
|
+
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
330
|
+
if (!aud.some((a) => typeof a === 'string' && wanted.includes(a)))
|
|
331
|
+
return { valid: false, reason: 'wrong audience' };
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
valid: true,
|
|
335
|
+
claims,
|
|
336
|
+
header: { alg, ...(kid !== undefined ? { kid } : {}), ...(typeof header.typ === 'string' ? { typ: header.typ } : {}) },
|
|
337
|
+
};
|
|
338
|
+
}
|
package/src/testing.d.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@open-artifact/host-plugin/testing`: run a plugin's hooks in a unit test, with no host.
|
|
3
|
+
*
|
|
4
|
+
* ```js
|
|
5
|
+
* import { test } from 'node:test';
|
|
6
|
+
* import assert from 'node:assert/strict';
|
|
7
|
+
* import { createPluginHarness } from '@open-artifact/host-plugin/testing';
|
|
8
|
+
* import plugin from './my-plugin.mjs';
|
|
9
|
+
*
|
|
10
|
+
* test('editors from the directory', async () => {
|
|
11
|
+
* const h = createPluginHarness(plugin, {
|
|
12
|
+
* config: { url: 'https://perms.example.com', secret: { env: 'PERMS_SECRET' } },
|
|
13
|
+
* env: { PERMS_SECRET: 'x'.repeat(32) },
|
|
14
|
+
* fetch: async () => Response.json({ role: 'editor' }),
|
|
15
|
+
* });
|
|
16
|
+
* const artifact = h.addArtifact({ title: 'Plan' });
|
|
17
|
+
* const { role } = await h.role({ principal: h.userPrincipal(h.addUser({ email: 'ann@example.com' })), artifact, role: null });
|
|
18
|
+
* assert.equal(role, 'editor');
|
|
19
|
+
* });
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* The harness checks the plugin and its settings with the host's own rules (`./contract.ts`): it throws what the
|
|
23
|
+
* host would refuse to start with. Each hook is then called as the host calls it: in order, under the time limit,
|
|
24
|
+
* with the same failure policy (sign-in, permission and guard hooks fail closed, events and `wake.deliver` open) and
|
|
25
|
+
* the same answer checks. Failures are kept in `failures`; `ctx.log`, `ctx.host.audit` and `ctx.fetch` calls in
|
|
26
|
+
* `logs`, `audits` and `fetches`.
|
|
27
|
+
*/
|
|
28
|
+
import { type CheckedPlugin } from './contract.ts';
|
|
29
|
+
import type { ArtifactInfo, ArtifactRole, GuardAction, GuardDetails, Identity, PluginContext, PluginEventMap, PluginEventName, PluginKv, Principal, UserInfo, UserPrincipal, WakePayload } from './index.ts';
|
|
30
|
+
/** How to set up a harness. */
|
|
31
|
+
export interface HarnessOptions {
|
|
32
|
+
/** The settings, as the operator would write them (`{env: NAME}` references included). */
|
|
33
|
+
config?: Record<string, unknown>;
|
|
34
|
+
/** The environment `{env: NAME}` settings read. */
|
|
35
|
+
env?: Record<string, string | undefined>;
|
|
36
|
+
/** The clock: a fixed time (moved with `advance`), or a function. Default: 2026-01-01T00:00:00Z. */
|
|
37
|
+
now?: Date | (() => Date);
|
|
38
|
+
/** Answers `ctx.fetch` (and gets the `Request`). Without it, a call to `ctx.fetch` fails the hook. */
|
|
39
|
+
fetch?: (request: Request) => Response | Promise<Response>;
|
|
40
|
+
/** Each hook call's time limit, ms (default 5000, as the host). */
|
|
41
|
+
timeoutMs?: number;
|
|
42
|
+
/** The operator's `cacheSeconds` for the entry: replaces the plugin's `authz.cacheSeconds`, as the host does. */
|
|
43
|
+
cacheSeconds?: number;
|
|
44
|
+
/** The site's address (default `https://artifacts.example.test`). */
|
|
45
|
+
appOrigin?: string;
|
|
46
|
+
/** The host version `ctx.host.version` says (default `0.0.0-test`). */
|
|
47
|
+
hostVersion?: string;
|
|
48
|
+
/** What `ctx.host.supports` answers true for (default: all of API version 1). */
|
|
49
|
+
features?: readonly string[];
|
|
50
|
+
}
|
|
51
|
+
/** A hook call that failed, as the host would log it. */
|
|
52
|
+
export interface HarnessFailure {
|
|
53
|
+
hook: string;
|
|
54
|
+
reason: 'threw' | 'timeout' | 'shape';
|
|
55
|
+
message: string;
|
|
56
|
+
}
|
|
57
|
+
/** The plugin under test, and every way to call it. */
|
|
58
|
+
export interface PluginHarness<Config = Record<string, unknown>> {
|
|
59
|
+
/** The plugin as the host checked it (its hooks, routes, schema). */
|
|
60
|
+
plugin: CheckedPlugin;
|
|
61
|
+
/** What the host would report and ignore (unknown hooks, an inline secret). */
|
|
62
|
+
warnings: string[];
|
|
63
|
+
/** The validated settings. */
|
|
64
|
+
config: Readonly<Config>;
|
|
65
|
+
/** A context like the one hooks get, to call your own helpers with. */
|
|
66
|
+
ctx: PluginContext<Config>;
|
|
67
|
+
kv: PluginKv & {
|
|
68
|
+
dump(): Record<string, unknown>;
|
|
69
|
+
};
|
|
70
|
+
logs: Array<{
|
|
71
|
+
message: string;
|
|
72
|
+
fields?: Record<string, unknown>;
|
|
73
|
+
}>;
|
|
74
|
+
audits: Array<{
|
|
75
|
+
action: string;
|
|
76
|
+
detail: unknown;
|
|
77
|
+
}>;
|
|
78
|
+
fetches: Request[];
|
|
79
|
+
failures: HarnessFailure[];
|
|
80
|
+
/** Every `ctx.host.access.invalidate` call (null: all artifacts). */
|
|
81
|
+
invalidated: Array<string | null>;
|
|
82
|
+
/** The fake site's users and artifacts, which `ctx.host.users` and `ctx.host.artifacts` read. */
|
|
83
|
+
users: Map<string, UserInfo>;
|
|
84
|
+
artifacts: Map<string, ArtifactInfo>;
|
|
85
|
+
/** Adds a user (defaults filled in). */
|
|
86
|
+
addUser(user?: Partial<UserInfo>): UserInfo;
|
|
87
|
+
/** Adds an artifact (defaults filled in). */
|
|
88
|
+
addArtifact(artifact?: Partial<ArtifactInfo>): ArtifactInfo;
|
|
89
|
+
/** A user as a principal (`groups` as the host keeps them, `<provider>:<group>`). */
|
|
90
|
+
userPrincipal(user: UserInfo, groups?: string[]): UserPrincipal;
|
|
91
|
+
/** Moves the fixed clock forward. */
|
|
92
|
+
advance(ms: number): void;
|
|
93
|
+
/** `auth.authenticate`: the identity, or null (also after a failure). */
|
|
94
|
+
authenticate(request: Request): Promise<Identity | null>;
|
|
95
|
+
/** `auth.signIn.start`. Throws when it fails (the host shows a sign-in error). */
|
|
96
|
+
signInStart(input?: {
|
|
97
|
+
request?: Request;
|
|
98
|
+
returnTo?: string;
|
|
99
|
+
callbackUrl?: string;
|
|
100
|
+
}): Promise<Response>;
|
|
101
|
+
/** `auth.signIn.finish`. Throws when it fails. */
|
|
102
|
+
signInFinish(request: Request): Promise<{
|
|
103
|
+
identity: Identity;
|
|
104
|
+
returnTo?: string;
|
|
105
|
+
}>;
|
|
106
|
+
/** `auth.identity`: the identity to sign in, or a refusal (also after a failure). */
|
|
107
|
+
identity(identity: Identity, provider?: string): Promise<{
|
|
108
|
+
identity: Identity;
|
|
109
|
+
} | {
|
|
110
|
+
reject: string;
|
|
111
|
+
}>;
|
|
112
|
+
/** `auth.signOutUrl`. */
|
|
113
|
+
signOutUrl(principal: UserPrincipal): Promise<string | null>;
|
|
114
|
+
/** `authz.role`, as one link of the host's chain: the role after it, and how long the host would reuse it. */
|
|
115
|
+
role(input: {
|
|
116
|
+
principal: Principal;
|
|
117
|
+
artifact: ArtifactInfo;
|
|
118
|
+
role: ArtifactRole | null;
|
|
119
|
+
}): Promise<{
|
|
120
|
+
role: ArtifactRole | null;
|
|
121
|
+
cacheSeconds: number | null;
|
|
122
|
+
}>;
|
|
123
|
+
/** `authz.artifacts`. */
|
|
124
|
+
artifactsFor(principal: Principal): Promise<string[]>;
|
|
125
|
+
/** `guard`: allowed, or the sentence the person would see. */
|
|
126
|
+
guard<A extends GuardAction>(action: A, input: {
|
|
127
|
+
principal: Principal;
|
|
128
|
+
artifact?: ArtifactInfo;
|
|
129
|
+
detail: GuardDetails[A];
|
|
130
|
+
}): Promise<{
|
|
131
|
+
allowed: true;
|
|
132
|
+
} | {
|
|
133
|
+
allowed: false;
|
|
134
|
+
reason: string;
|
|
135
|
+
}>;
|
|
136
|
+
/** Sends an event and waits for the handler (the host does not wait; a failure lands in `failures`). */
|
|
137
|
+
emit<E extends PluginEventName>(event: E, payload: PluginEventMap[E] & {
|
|
138
|
+
at?: string;
|
|
139
|
+
}): Promise<void>;
|
|
140
|
+
/** `wake.deliver`: whether it delivered (false after a failure). */
|
|
141
|
+
deliverWake(input: {
|
|
142
|
+
artifact: ArtifactInfo;
|
|
143
|
+
owner: UserInfo;
|
|
144
|
+
payload: WakePayload;
|
|
145
|
+
from: {
|
|
146
|
+
name: string;
|
|
147
|
+
role: ArtifactRole;
|
|
148
|
+
userId?: string;
|
|
149
|
+
};
|
|
150
|
+
}): Promise<boolean>;
|
|
151
|
+
/**
|
|
152
|
+
* A request to one of the plugin's routes. `path` is the route's path (`/invalidate`) or the full one
|
|
153
|
+
* (`/plugins/<id>/invalidate`); `principal` is who the host says sends it (default anonymous). The host's answers
|
|
154
|
+
* for no route (404), another method (405) and a cross-site write to a route that is not public (403) apply.
|
|
155
|
+
*/
|
|
156
|
+
request(method: string, path: string, init?: RequestInit & {
|
|
157
|
+
principal?: Principal;
|
|
158
|
+
}): Promise<Response>;
|
|
159
|
+
}
|
|
160
|
+
/** The harness refused the plugin, as the host would refuse to start: `problems` lists why. */
|
|
161
|
+
export declare class PluginRefusedError extends Error {
|
|
162
|
+
readonly problems: readonly string[];
|
|
163
|
+
constructor(problems: readonly string[]);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* A harness for `plugin` (the object your module exports). Throws a {@link PluginRefusedError} when the host would
|
|
167
|
+
* refuse the plugin or its settings, with the host's messages.
|
|
168
|
+
*/
|
|
169
|
+
export declare function createPluginHarness<Config = Record<string, unknown>>(plugin: unknown, options?: HarnessOptions): PluginHarness<Config>;
|