@open-artifact/host-plugin 0.0.0-stage → 0.14.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/testing.js
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
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 { answers, artifactListOptions, checkIdentity, checkPlugin, DEFAULT_TIMEOUT_MS, EVENT_NAMES, ALL_FEATURES, checkKvKey, encodeKvValue, httpErrorOf, isSameOriginWrite, KV_LIMITS, kvExpiry, kvFull, kvListLimit, matchRoute, redact, runHook, runValidate, validateConfig, } from "./contract.js";
|
|
29
|
+
/** The harness refused the plugin, as the host would refuse to start: `problems` lists why. */
|
|
30
|
+
export class PluginRefusedError extends Error {
|
|
31
|
+
problems;
|
|
32
|
+
constructor(problems) {
|
|
33
|
+
super(problems.join('\n'));
|
|
34
|
+
this.name = 'PluginRefusedError';
|
|
35
|
+
this.problems = problems;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const DEFAULT_NOW = new Date('2026-01-01T00:00:00.000Z');
|
|
39
|
+
function memoryKv(now) {
|
|
40
|
+
const store = new Map();
|
|
41
|
+
const alive = (entry) => entry.expiresAt === null || entry.expiresAt > now().toISOString();
|
|
42
|
+
const sweep = () => {
|
|
43
|
+
for (const [key, entry] of store)
|
|
44
|
+
if (!alive(entry))
|
|
45
|
+
store.delete(key);
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
async get(key) {
|
|
49
|
+
checkKvKey(key);
|
|
50
|
+
const entry = store.get(key);
|
|
51
|
+
if (!entry || !alive(entry)) {
|
|
52
|
+
store.delete(key);
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
return JSON.parse(entry.value);
|
|
56
|
+
},
|
|
57
|
+
async set(key, value, options = {}) {
|
|
58
|
+
checkKvKey(key);
|
|
59
|
+
const text = encodeKvValue(value);
|
|
60
|
+
const expiresAt = kvExpiry(now(), options.ttlSeconds);
|
|
61
|
+
if (!store.has(key)) {
|
|
62
|
+
sweep();
|
|
63
|
+
if (store.size >= KV_LIMITS.maxKeys)
|
|
64
|
+
throw kvFull();
|
|
65
|
+
}
|
|
66
|
+
store.set(key, { value: text, expiresAt });
|
|
67
|
+
},
|
|
68
|
+
async delete(key) {
|
|
69
|
+
checkKvKey(key);
|
|
70
|
+
store.delete(key);
|
|
71
|
+
},
|
|
72
|
+
async list(options = {}) {
|
|
73
|
+
const limit = kvListLimit(options.limit);
|
|
74
|
+
sweep();
|
|
75
|
+
return [...store.entries()]
|
|
76
|
+
.filter(([key]) => (options.prefix === undefined || key.startsWith(options.prefix)) && (options.after === undefined || key > options.after))
|
|
77
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
78
|
+
.slice(0, limit)
|
|
79
|
+
.map(([key, entry]) => ({ key, value: JSON.parse(entry.value), expiresAt: entry.expiresAt }));
|
|
80
|
+
},
|
|
81
|
+
dump() {
|
|
82
|
+
sweep();
|
|
83
|
+
return Object.fromEntries([...store.entries()].map(([key, entry]) => [key, JSON.parse(entry.value)]));
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* A harness for `plugin` (the object your module exports). Throws a {@link PluginRefusedError} when the host would
|
|
89
|
+
* refuse the plugin or its settings, with the host's messages.
|
|
90
|
+
*/
|
|
91
|
+
export function createPluginHarness(plugin, options = {}) {
|
|
92
|
+
const checked = checkPlugin(plugin, 'The plugin', options.hostVersion ? { hostVersion: options.hostVersion } : {});
|
|
93
|
+
if (!checked.plugin)
|
|
94
|
+
throw new PluginRefusedError(checked.errors);
|
|
95
|
+
const p = options.cacheSeconds !== undefined ? { ...checked.plugin, cacheSeconds: options.cacheSeconds } : checked.plugin;
|
|
96
|
+
const settings = validateConfig(p.id, p.schema, options.config, options.env ?? {});
|
|
97
|
+
if (settings.errors.length > 0)
|
|
98
|
+
throw new PluginRefusedError(settings.errors);
|
|
99
|
+
const refused = runValidate(p, settings.config).map((problem) => redact(problem, settings.secrets));
|
|
100
|
+
if (refused.length > 0)
|
|
101
|
+
throw new PluginRefusedError(refused);
|
|
102
|
+
const warnings = [...checked.warnings, ...settings.warnings];
|
|
103
|
+
let fixed = options.now instanceof Date ? options.now : DEFAULT_NOW;
|
|
104
|
+
const now = typeof options.now === 'function' ? options.now : () => fixed;
|
|
105
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
106
|
+
const appOrigin = options.appOrigin ?? 'https://artifacts.example.test';
|
|
107
|
+
const features = new Set(options.features ?? ALL_FEATURES);
|
|
108
|
+
const logs = [];
|
|
109
|
+
const audits = [];
|
|
110
|
+
const fetches = [];
|
|
111
|
+
const failures = [];
|
|
112
|
+
const invalidated = [];
|
|
113
|
+
const users = new Map();
|
|
114
|
+
const artifacts = new Map();
|
|
115
|
+
const kv = memoryKv(now);
|
|
116
|
+
let counter = 0;
|
|
117
|
+
const host = {
|
|
118
|
+
apiVersion: p.apiVersion,
|
|
119
|
+
version: options.hostVersion ?? '0.0.0-test',
|
|
120
|
+
appOrigin,
|
|
121
|
+
supports: (name) => features.has(name),
|
|
122
|
+
users: {
|
|
123
|
+
get: async (id) => users.get(id) ?? null,
|
|
124
|
+
findByEmail: async (email) => [...users.values()].find((u) => u.email === email.trim().toLowerCase()) ?? null,
|
|
125
|
+
},
|
|
126
|
+
artifacts: {
|
|
127
|
+
get: async (id) => artifacts.get(id) ?? null,
|
|
128
|
+
// As the hosts answer: outside the trash, in id order, a page at a time (the same cap).
|
|
129
|
+
list: async (options) => {
|
|
130
|
+
const { owner, after, limit } = artifactListOptions(options);
|
|
131
|
+
const all = [...artifacts.values()]
|
|
132
|
+
.filter((a) => a.trashedAt === null && (!owner || a.owner === owner) && (!after || a.id > after))
|
|
133
|
+
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
134
|
+
const page = all.slice(0, limit).map(({ id, title, type, owner: by, updatedAt }) => ({ id, title, type, owner: by, updatedAt }));
|
|
135
|
+
return { artifacts: page, next: all.length > limit ? page.at(-1).id : null };
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
access: {
|
|
139
|
+
invalidate: async (artifactId) => {
|
|
140
|
+
invalidated.push(artifactId ?? null);
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
audit: async (action, detail) => {
|
|
144
|
+
audits.push({ action, detail: detail ?? null });
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
function contextFor(signal) {
|
|
148
|
+
return {
|
|
149
|
+
plugin: { id: p.id },
|
|
150
|
+
config: settings.config,
|
|
151
|
+
log: (message, fields) => {
|
|
152
|
+
logs.push({ message: redact(String(message), settings.secrets), ...(fields !== undefined ? { fields } : {}) });
|
|
153
|
+
},
|
|
154
|
+
fetch: async (resource, init) => {
|
|
155
|
+
const request = new Request(resource, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal });
|
|
156
|
+
fetches.push(request.clone());
|
|
157
|
+
if (!options.fetch)
|
|
158
|
+
throw new Error(`ctx.fetch(${request.url}) was called, but the harness has no fetch stub: pass {fetch} to createPluginHarness.`);
|
|
159
|
+
return options.fetch(request);
|
|
160
|
+
},
|
|
161
|
+
kv,
|
|
162
|
+
now,
|
|
163
|
+
signal,
|
|
164
|
+
host,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
async function call(hook, invoke, check) {
|
|
168
|
+
const controller = new AbortController();
|
|
169
|
+
const ctx = contextFor(controller.signal);
|
|
170
|
+
const outcome = await runHook(() => invoke(ctx), check, timeoutMs, controller);
|
|
171
|
+
if (!outcome.ok)
|
|
172
|
+
failures.push({ hook, reason: outcome.reason, message: outcome.message });
|
|
173
|
+
return outcome;
|
|
174
|
+
}
|
|
175
|
+
const source = p.source;
|
|
176
|
+
const has = (hook) => p.hooks.includes(hook);
|
|
177
|
+
const harness = {
|
|
178
|
+
plugin: p,
|
|
179
|
+
warnings,
|
|
180
|
+
config: settings.config,
|
|
181
|
+
ctx: contextFor(new AbortController().signal),
|
|
182
|
+
kv,
|
|
183
|
+
logs,
|
|
184
|
+
audits,
|
|
185
|
+
fetches,
|
|
186
|
+
failures,
|
|
187
|
+
invalidated,
|
|
188
|
+
users,
|
|
189
|
+
artifacts,
|
|
190
|
+
addUser(user = {}) {
|
|
191
|
+
const id = user.id ?? `user_${++counter}`;
|
|
192
|
+
const info = {
|
|
193
|
+
id,
|
|
194
|
+
name: user.name ?? `User ${counter}`,
|
|
195
|
+
email: user.email?.toLowerCase() ?? null,
|
|
196
|
+
emailVerified: user.emailVerified ?? user.email !== undefined,
|
|
197
|
+
avatar: user.avatar ?? null,
|
|
198
|
+
siteRole: user.siteRole ?? 'member',
|
|
199
|
+
createdAt: user.createdAt ?? now().toISOString(),
|
|
200
|
+
disabled: user.disabled ?? false,
|
|
201
|
+
};
|
|
202
|
+
users.set(id, info);
|
|
203
|
+
return info;
|
|
204
|
+
},
|
|
205
|
+
addArtifact(artifact = {}) {
|
|
206
|
+
const id = artifact.id ?? `art_${now().getTime().toString(36).padStart(9, '0')}${(++counter).toString(16).padStart(16, '0')}`;
|
|
207
|
+
const at = now().toISOString();
|
|
208
|
+
const info = {
|
|
209
|
+
id,
|
|
210
|
+
type: artifact.type ?? 'slides',
|
|
211
|
+
title: artifact.title ?? 'Untitled',
|
|
212
|
+
owner: artifact.owner ?? 'owner',
|
|
213
|
+
generalAccess: artifact.generalAccess ?? 'restricted',
|
|
214
|
+
createdAt: artifact.createdAt ?? at,
|
|
215
|
+
updatedAt: artifact.updatedAt ?? at,
|
|
216
|
+
trashedAt: artifact.trashedAt ?? null,
|
|
217
|
+
};
|
|
218
|
+
artifacts.set(id, info);
|
|
219
|
+
return info;
|
|
220
|
+
},
|
|
221
|
+
userPrincipal(user, groups) {
|
|
222
|
+
return {
|
|
223
|
+
kind: 'user',
|
|
224
|
+
id: user.id,
|
|
225
|
+
name: user.name,
|
|
226
|
+
...(user.email ? { email: user.email, emailVerified: user.emailVerified } : {}),
|
|
227
|
+
...(user.avatar ? { avatar: user.avatar } : {}),
|
|
228
|
+
...(groups ? { groups } : {}),
|
|
229
|
+
siteRole: user.siteRole,
|
|
230
|
+
};
|
|
231
|
+
},
|
|
232
|
+
advance(ms) {
|
|
233
|
+
fixed = new Date(fixed.getTime() + ms);
|
|
234
|
+
},
|
|
235
|
+
async authenticate(request) {
|
|
236
|
+
if (!has('auth.authenticate'))
|
|
237
|
+
return null;
|
|
238
|
+
const bare = new Request(request.url, { method: request.method, headers: request.headers });
|
|
239
|
+
const outcome = await call('auth.authenticate', (ctx) => source.auth.authenticate.call(source.auth, { request: bare }, ctx), answers.authenticate);
|
|
240
|
+
return outcome.ok ? outcome.value : null;
|
|
241
|
+
},
|
|
242
|
+
async signInStart(input = {}) {
|
|
243
|
+
if (!has('auth.signIn'))
|
|
244
|
+
throw new Error('The plugin has no auth.signIn.');
|
|
245
|
+
const signIn = source.auth.signIn;
|
|
246
|
+
const request = input.request ?? new Request(`${appOrigin}/auth/plugin:${p.id}/start`);
|
|
247
|
+
const outcome = await call('auth.signIn', (ctx) => signIn.start.call(signIn, { request, returnTo: input.returnTo ?? '/', callbackUrl: input.callbackUrl ?? `${appOrigin}/auth/plugin:${p.id}/callback` }, ctx), answers.signInStart);
|
|
248
|
+
if (!outcome.ok)
|
|
249
|
+
throw new Error(`auth.signIn.start failed (${outcome.reason}): ${outcome.message}`);
|
|
250
|
+
return outcome.value;
|
|
251
|
+
},
|
|
252
|
+
async signInFinish(request) {
|
|
253
|
+
if (!has('auth.signIn'))
|
|
254
|
+
throw new Error('The plugin has no auth.signIn.');
|
|
255
|
+
const signIn = source.auth.signIn;
|
|
256
|
+
const outcome = await call('auth.signIn', (ctx) => signIn.finish.call(signIn, { request }, ctx), answers.signInFinish);
|
|
257
|
+
if (!outcome.ok)
|
|
258
|
+
throw new Error(`auth.signIn.finish failed (${outcome.reason}): ${outcome.message}`);
|
|
259
|
+
return outcome.value;
|
|
260
|
+
},
|
|
261
|
+
async identity(identity, provider = 'oidc:test') {
|
|
262
|
+
const given = checkIdentity(identity) ?? structuredClone(identity);
|
|
263
|
+
if (!has('auth.identity'))
|
|
264
|
+
return { identity: given };
|
|
265
|
+
const outcome = await call('auth.identity', (ctx) => source.auth.identity.call(source.auth, { identity: structuredClone(given), provider }, ctx), (answer) => answers.identity(answer, given.subject));
|
|
266
|
+
if (!outcome.ok)
|
|
267
|
+
return { reject: 'This sign-in could not be checked just now. Try again in a moment.' };
|
|
268
|
+
const value = outcome.value;
|
|
269
|
+
if ('reject' in value)
|
|
270
|
+
return { reject: value.reject };
|
|
271
|
+
return { identity: 'identity' in value ? value.identity : given };
|
|
272
|
+
},
|
|
273
|
+
async signOutUrl(principal) {
|
|
274
|
+
if (!has('auth.signOutUrl'))
|
|
275
|
+
return null;
|
|
276
|
+
const outcome = await call('auth.signOutUrl', (ctx) => source.auth.signOutUrl.call(source.auth, { principal: structuredClone(principal) }, ctx), answers.signOutUrl);
|
|
277
|
+
return outcome.ok ? outcome.value : null;
|
|
278
|
+
},
|
|
279
|
+
async role(input) {
|
|
280
|
+
if (!has('authz.role'))
|
|
281
|
+
return { role: input.role, cacheSeconds: null };
|
|
282
|
+
const outcome = await call('authz.role', (ctx) => source.authz.role.call(source.authz, structuredClone(input), ctx), answers.role);
|
|
283
|
+
if (!outcome.ok)
|
|
284
|
+
return { role: null, cacheSeconds: 0 };
|
|
285
|
+
return { role: outcome.value.opinion ? outcome.value.role : input.role, cacheSeconds: p.cacheSeconds };
|
|
286
|
+
},
|
|
287
|
+
async artifactsFor(principal) {
|
|
288
|
+
if (!has('authz.artifacts'))
|
|
289
|
+
return [];
|
|
290
|
+
const outcome = await call('authz.artifacts', (ctx) => source.authz.artifacts.call(source.authz, { principal: structuredClone(principal) }, ctx), answers.artifacts);
|
|
291
|
+
return outcome.ok ? outcome.value : [];
|
|
292
|
+
},
|
|
293
|
+
async guard(action, input) {
|
|
294
|
+
if (!has('guard'))
|
|
295
|
+
return { allowed: true };
|
|
296
|
+
const asked = { action, principal: input.principal, ...(input.artifact ? { artifact: input.artifact } : {}), detail: input.detail };
|
|
297
|
+
const outcome = await call('guard', (ctx) => source.guard.call(source, structuredClone(asked), ctx), answers.guard);
|
|
298
|
+
if (!outcome.ok)
|
|
299
|
+
return { allowed: false, reason: `This could not be checked just now (${p.name}). Try again in a moment.` };
|
|
300
|
+
return outcome.value ? { allowed: false, reason: outcome.value.deny } : { allowed: true };
|
|
301
|
+
},
|
|
302
|
+
async emit(event, payload) {
|
|
303
|
+
if (!EVENT_NAMES.includes(event))
|
|
304
|
+
throw new TypeError(`No such event: ${String(event)}.`);
|
|
305
|
+
if (!has(`on.${event}`))
|
|
306
|
+
return;
|
|
307
|
+
const handlers = source.on;
|
|
308
|
+
const full = { ...payload, event, at: payload.at ?? now().toISOString() };
|
|
309
|
+
await call(`on.${event}`, (ctx) => handlers[event].call(handlers, structuredClone(full), ctx), answers.event);
|
|
310
|
+
},
|
|
311
|
+
async deliverWake(input) {
|
|
312
|
+
if (!has('wake.deliver'))
|
|
313
|
+
return false;
|
|
314
|
+
const outcome = await call('wake.deliver', (ctx) => source.wake.deliver.call(source.wake, structuredClone(input), ctx), answers.deliver);
|
|
315
|
+
return outcome.ok ? outcome.value : false;
|
|
316
|
+
},
|
|
317
|
+
async request(method, path, init = {}) {
|
|
318
|
+
const { principal = { kind: 'anonymous' }, ...requestInit } = init;
|
|
319
|
+
const prefix = `/plugins/${p.id}`;
|
|
320
|
+
const full = path.startsWith(`${prefix}/`) || path === prefix ? path : `${prefix}${path.startsWith('/') ? path : `/${path}`}`;
|
|
321
|
+
const request = new Request(`${appOrigin}${full}`, { ...requestInit, method });
|
|
322
|
+
const rest = new URL(request.url).pathname.split('/').filter((s) => s !== '').slice(2);
|
|
323
|
+
const wanted = method.toUpperCase();
|
|
324
|
+
const allow = new Set();
|
|
325
|
+
let found = null;
|
|
326
|
+
let getMatch = null;
|
|
327
|
+
for (const route of p.routes) {
|
|
328
|
+
const params = matchRoute(route.segments, rest);
|
|
329
|
+
if (!params)
|
|
330
|
+
continue;
|
|
331
|
+
if (route.method === '*' || route.method === wanted) {
|
|
332
|
+
found = { route, params };
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
if (wanted === 'HEAD' && route.method === 'GET' && !getMatch)
|
|
336
|
+
getMatch = { route, params };
|
|
337
|
+
allow.add(route.method);
|
|
338
|
+
}
|
|
339
|
+
found ??= getMatch;
|
|
340
|
+
const answer = (status, code, message, headers) => Response.json({ code, message }, { status, ...(headers ? { headers } : {}) });
|
|
341
|
+
if (!found) {
|
|
342
|
+
return allow.size > 0
|
|
343
|
+
? answer(405, 'method_not_found', `${method} is not allowed on ${full}.`, { allow: [...allow].join(', ') })
|
|
344
|
+
: answer(404, 'not_found', `No route for ${method} ${full}.`);
|
|
345
|
+
}
|
|
346
|
+
if (!found.route.public && !isSameOriginWrite(request, appOrigin))
|
|
347
|
+
return answer(403, 'not_granted', 'Cross-site requests may not change anything here.');
|
|
348
|
+
const declared = source.routes[found.route.index];
|
|
349
|
+
const params = found.params;
|
|
350
|
+
const outcome = await call('routes', (ctx) => declared.handler.call(declared, { request, principal, params }, ctx), answers.route);
|
|
351
|
+
if (outcome.ok)
|
|
352
|
+
return outcome.value;
|
|
353
|
+
if (outcome.reason === 'threw') {
|
|
354
|
+
const chosen = httpErrorOf(outcome.error);
|
|
355
|
+
if (chosen)
|
|
356
|
+
return answer(chosen.status, 'plugin_error', chosen.message);
|
|
357
|
+
}
|
|
358
|
+
if (outcome.reason === 'timeout')
|
|
359
|
+
return answer(504, 'plugin_timeout', `The ${p.name} plugin took too long to answer.`);
|
|
360
|
+
return answer(500, 'plugin_error', `The ${p.name} plugin failed to answer this request.`);
|
|
361
|
+
},
|
|
362
|
+
};
|
|
363
|
+
return harness;
|
|
364
|
+
}
|