@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/src/index.d.ts ADDED
@@ -0,0 +1,832 @@
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 declare const PLUGIN_API_VERSION: 1;
36
+ /** A value or a promise of it: every hook may be `async` or not. */
37
+ export type Awaitable<T> = T | Promise<T>;
38
+ /** A person's role on an artifact, highest first: `owner` > `editor` > `commenter` > `viewer`. */
39
+ export type ArtifactRole = 'owner' | 'editor' | 'commenter' | 'viewer';
40
+ /** A role the owner can share (every role but `owner`). */
41
+ export type ShareRole = 'editor' | 'commenter' | 'viewer';
42
+ /** An artifact's "general access": only the people it is shared with, anyone with a link, or anyone. */
43
+ export type GeneralAccess = 'restricted' | 'link' | 'public';
44
+ /**
45
+ * Who someone is, as a sign-in method says: what `auth.authenticate`, `auth.signIn.finish` and `auth.identity`
46
+ * answer. The host turns it into an account (found by `subject`, or linked by a verified e-mail address, or created
47
+ * when the site's sign-up policy allows) and a session. The provider of an identity a plugin returns is
48
+ * `plugin:<id>`.
49
+ */
50
+ export interface Identity {
51
+ /** The stable id of the person in your system. Never reuse one for somebody else. At most 256 characters. */
52
+ subject: string;
53
+ email?: string;
54
+ /**
55
+ * Whether your system vouches that the person controls `email`. Only a verified address links accounts or
56
+ * matches e-mail and domain shares, so say `true` only when it is.
57
+ */
58
+ emailVerified?: boolean;
59
+ name?: string;
60
+ /** An image URL. */
61
+ avatar?: string;
62
+ /** Group names in your system. The host stores them as `<provider>:<group>`, which is how a share names a group. */
63
+ groups?: string[];
64
+ }
65
+ /** A signed-in person. */
66
+ export interface UserPrincipal {
67
+ kind: 'user';
68
+ /** The host's user id. */
69
+ id: string;
70
+ name: string;
71
+ email?: string;
72
+ emailVerified?: boolean;
73
+ avatar?: string;
74
+ /** Groups as the host stores them: `<provider>:<group>` each (`plugin:<id>:<group>` for a plugin's). */
75
+ groups?: string[];
76
+ /** `admin` for the site's administrators. */
77
+ siteRole: 'admin' | 'member';
78
+ }
79
+ /** Someone who joined one artifact through its share link, without signing in. */
80
+ export interface GuestPrincipal {
81
+ kind: 'guest';
82
+ id: string;
83
+ /** The name they typed. */
84
+ name: string;
85
+ /** The artifact whose link they joined. */
86
+ artifact: string;
87
+ }
88
+ /** An agent (a coding assistant, a script) acting for a user with a token the user issued. */
89
+ export interface AgentPrincipal {
90
+ kind: 'agent';
91
+ /** The token's id. */
92
+ id: string;
93
+ /** The label the user gave the token. */
94
+ label: string;
95
+ /** The agent app, when it said (`claude-code`, `codex`, …). */
96
+ harness?: string;
97
+ /** The person the agent acts for. */
98
+ user: UserPrincipal;
99
+ }
100
+ /** Nobody signed in. */
101
+ export interface AnonymousPrincipal {
102
+ kind: 'anonymous';
103
+ }
104
+ /** Who is asking. Check `kind` first; new kinds may be added, so handle an unknown one as "no opinion". */
105
+ export type Principal = UserPrincipal | GuestPrincipal | AgentPrincipal | AnonymousPrincipal;
106
+ /** An artifact, as hooks see it. */
107
+ export interface ArtifactInfo {
108
+ id: string;
109
+ /** Its type: `slides`, `design`, `whiteboard`, `sheets`, `docs`, … */
110
+ type: string;
111
+ title: string;
112
+ /** The owner's user id. */
113
+ owner: string;
114
+ generalAccess: GeneralAccess;
115
+ /** ISO-8601 times. */
116
+ createdAt: string;
117
+ updatedAt: string;
118
+ /** When it went to the trash, or null. */
119
+ trashedAt: string | null;
120
+ }
121
+ /** One artifact of `ctx.host.artifacts.list`. */
122
+ export interface ArtifactSummary {
123
+ id: string;
124
+ title: string;
125
+ type: string;
126
+ /** The owner's user id. */
127
+ owner: string;
128
+ /** ISO-8601. */
129
+ updatedAt: string;
130
+ }
131
+ /** `ctx.host.artifacts.list`'s options. */
132
+ export interface ArtifactListOptions {
133
+ /** Only this user's artifacts (a user id). */
134
+ owner?: string;
135
+ /** At most this many (default 50, at most 200). */
136
+ limit?: number;
137
+ /** The page after this one: the `next` of the page before. */
138
+ after?: string;
139
+ }
140
+ /** A page of `ctx.host.artifacts.list`: `next` is null on the last page. */
141
+ export interface ArtifactList {
142
+ artifacts: ArtifactSummary[];
143
+ next: string | null;
144
+ }
145
+ /** A user of the site, as `ctx.host.users` answers. */
146
+ export interface UserInfo {
147
+ id: string;
148
+ name: string;
149
+ /** Lower case. */
150
+ email: string | null;
151
+ emailVerified: boolean;
152
+ avatar: string | null;
153
+ siteRole: 'admin' | 'member';
154
+ createdAt: string;
155
+ /** Whether an admin disabled the account. */
156
+ disabled: boolean;
157
+ }
158
+ /** Who did something, in events. `system` is the host itself (the trash's upkeep, a plugin: `id` `plugin:<id>`). */
159
+ export interface Actor {
160
+ kind: 'user' | 'agent' | 'guest' | 'anonymous' | 'system';
161
+ /** The user, agent token or guest id; null for `anonymous` and the host. */
162
+ id: string | null;
163
+ /** A name to show, when there is one. */
164
+ name?: string;
165
+ }
166
+ /** The artifact an event is about. */
167
+ export interface ArtifactRef {
168
+ id: string;
169
+ type: string;
170
+ title: string;
171
+ /** The owner's user id. */
172
+ owner: string;
173
+ }
174
+ /** What a sharing change asks for (each part only when it changes). */
175
+ export interface ShareChanges {
176
+ access?: GeneralAccess;
177
+ /** People, addresses, domains and groups given a role (`role: null`: removed). */
178
+ grants?: Array<{
179
+ subjectKind: 'user' | 'email' | 'domain' | 'group';
180
+ subject: string;
181
+ role: ShareRole | null;
182
+ }>;
183
+ /** Share links turned on or off, or given a new address. */
184
+ links?: Array<{
185
+ role: ShareRole;
186
+ enabled?: boolean;
187
+ reset?: boolean;
188
+ }>;
189
+ /** Link guests given another role (`role: null`: removed). */
190
+ guests?: Array<{
191
+ id: string;
192
+ role: ShareRole | null;
193
+ }>;
194
+ settings?: {
195
+ viewersCanExport?: boolean;
196
+ editorsCanAskAgent?: boolean;
197
+ };
198
+ }
199
+ /**
200
+ * The events a plugin can listen to (`on: {'share.invited': handler}`), each with what it carries. Every payload
201
+ * also has `event` (its name) and `at` (an ISO-8601 time). Handlers run after the fact, in the background: they
202
+ * cannot stop anything (that is {@link GuardInput | guard}'s job), and an error in one is logged and ignored.
203
+ */
204
+ export interface PluginEventMap {
205
+ /** A person's account was created at their first sign-in. */
206
+ 'user.created': {
207
+ user: {
208
+ id: string;
209
+ name: string;
210
+ email: string | null;
211
+ };
212
+ provider: string;
213
+ };
214
+ /** A person signed in (`provider`: `github`, `oidc:<id>`, `plugin:<id>`, …). */
215
+ 'user.signed_in': {
216
+ user: {
217
+ id: string;
218
+ name: string;
219
+ email: string | null;
220
+ };
221
+ provider: string;
222
+ };
223
+ /**
224
+ * An artifact was made: from an archive uploaded in the Library (`import`), published by a linked computer (`link`),
225
+ * or by an agent's `create` (`mcp`). The host's Library has no "New" of its own: artifacts start on a computer or
226
+ * with an agent.
227
+ */
228
+ 'artifact.created': {
229
+ artifact: ArtifactRef;
230
+ by: Actor;
231
+ via: 'import' | 'link' | 'mcp';
232
+ };
233
+ /** An artifact was renamed (`changes.title`) or its files changed (`changes.files`, paths in the artifact). */
234
+ 'artifact.changed': {
235
+ artifact: ArtifactRef;
236
+ by: Actor;
237
+ changes: {
238
+ title?: string;
239
+ files?: string[];
240
+ };
241
+ };
242
+ /** An artifact went to the trash. */
243
+ 'artifact.trashed': {
244
+ artifact: ArtifactRef;
245
+ by: Actor;
246
+ };
247
+ /** An artifact came back from the trash. */
248
+ 'artifact.restored': {
249
+ artifact: ArtifactRef;
250
+ by: Actor;
251
+ };
252
+ /** An artifact was deleted for good (`reason`: `owner` deleted it from the trash, the trash `expired`). */
253
+ 'artifact.deleted': {
254
+ artifact: ArtifactRef;
255
+ by: Actor;
256
+ reason: 'owner' | 'expired' | (string & {});
257
+ };
258
+ /** Who may open an artifact changed. */
259
+ 'share.changed': {
260
+ artifact: ArtifactRef;
261
+ by: Actor;
262
+ changes: ShareChanges;
263
+ };
264
+ /**
265
+ * Someone was given a role on an artifact by name or address (one event per person). `url` opens the artifact.
266
+ * The host sends no e-mail itself: this is where a plugin does.
267
+ */
268
+ 'share.invited': {
269
+ artifact: ArtifactRef;
270
+ by: Actor;
271
+ invitee: {
272
+ email?: string;
273
+ userId?: string;
274
+ name?: string;
275
+ };
276
+ role: ShareRole;
277
+ url: string;
278
+ };
279
+ /** Someone asked the owner's agent to do something on an artifact (the Ask pane). */
280
+ 'agent.requested': {
281
+ artifact: ArtifactRef;
282
+ by: Actor;
283
+ owner: string;
284
+ text: string;
285
+ label?: string;
286
+ };
287
+ /** Every entry written to the host's audit log (`action` such as `share.change`, `auth.sign_in`). */
288
+ audit: {
289
+ action: string;
290
+ actor: Actor;
291
+ artifact: string | null;
292
+ detail: unknown;
293
+ };
294
+ }
295
+ /** An event's name. */
296
+ export type PluginEventName = keyof PluginEventMap;
297
+ /** What an event handler receives: the event's fields, its name and when it happened. */
298
+ export type PluginEvent<E extends PluginEventName = PluginEventName> = E extends PluginEventName ? PluginEventMap[E] & {
299
+ event: E;
300
+ at: string;
301
+ } : never;
302
+ /**
303
+ * The actions `guard` is asked about before the host does them, each with its `detail`. New actions may be added:
304
+ * answer nothing for an action you do not know.
305
+ */
306
+ export interface GuardDetails {
307
+ /**
308
+ * A new artifact, once its type is known: an archive uploaded in the Library, after unpacking (`import`, which
309
+ * `artifact.import` asked about first); a linked computer's first publish of an id (`link`, after `link.publish`);
310
+ * an agent's `create` (`mcp`). There is no host "New".
311
+ */
312
+ 'artifact.create': {
313
+ type: string;
314
+ title: string;
315
+ via: 'import' | 'link' | 'mcp';
316
+ };
317
+ /**
318
+ * An archive uploaded in the Library, asked before it is unpacked: so the type is not known yet (`type: null`) and
319
+ * `artifact.create` follows with it. A linked computer's publish is `link.publish`, not this.
320
+ */
321
+ 'artifact.import': {
322
+ type: null;
323
+ bytes: number;
324
+ via: 'library';
325
+ };
326
+ /** To the trash (`permanent: false`) or deleted for good (`permanent: true`). */
327
+ 'artifact.delete': {
328
+ permanent: boolean;
329
+ };
330
+ /** A download of the artifact (`format`: `zip`, or an export format such as `pdf`, `pptx`, `png`). */
331
+ 'artifact.export': {
332
+ format: string;
333
+ };
334
+ /** A change of who may open the artifact. */
335
+ 'share.change': {
336
+ changes: ShareChanges;
337
+ };
338
+ /** A local computer links to the host (the device sign-in). */
339
+ 'link.connect': {
340
+ client: {
341
+ name: string;
342
+ harness?: string;
343
+ version?: string;
344
+ };
345
+ };
346
+ /** A linked computer publishes or replaces an artifact. */
347
+ 'link.publish': {
348
+ type: string;
349
+ bytes: number;
350
+ replaces: boolean;
351
+ };
352
+ /** An MCP client (an agent app) is given access to the person's artifacts. */
353
+ 'mcp.connect': {
354
+ client: {
355
+ id: string;
356
+ name: string;
357
+ };
358
+ };
359
+ /** A request to the owner's agent from the Ask pane. */
360
+ 'agent.ask': {
361
+ text: string;
362
+ label?: string;
363
+ };
364
+ }
365
+ /** A guarded action's name. */
366
+ export type GuardAction = keyof GuardDetails;
367
+ /** What `guard` receives: the action, who asks, the artifact when there is one, and the action's detail. */
368
+ export type GuardInput = {
369
+ [A in GuardAction]: {
370
+ action: A;
371
+ principal: Principal;
372
+ artifact?: ArtifactInfo;
373
+ detail: GuardDetails[A];
374
+ };
375
+ }[GuardAction];
376
+ /** Nothing to let the action happen; `{deny}` to refuse it with a sentence the person sees. */
377
+ export type GuardResult = void | undefined | {
378
+ deny: string;
379
+ };
380
+ /** `auth.authenticate`'s input. The request carries no body here: decide from its headers and cookies. */
381
+ export interface AuthenticateInput {
382
+ request: Request;
383
+ }
384
+ /** `auth.signIn.start`'s input. */
385
+ export interface SignInStartInput {
386
+ request: Request;
387
+ /** The path on the host to return to afterwards (pass it through your round trip, or give it back from `finish`). */
388
+ returnTo: string;
389
+ /** Where your sign-in must come back to: the host calls `finish` there. */
390
+ callbackUrl: string;
391
+ }
392
+ /** `auth.signIn.finish`'s input: the request that arrived at `callbackUrl`. */
393
+ export interface SignInFinishInput {
394
+ request: Request;
395
+ }
396
+ /** `auth.signIn.finish`'s answer. `returnTo` must be a path on the host; anything else goes to `/`. */
397
+ export interface SignInResult {
398
+ identity: Identity;
399
+ returnTo?: string;
400
+ }
401
+ /** `auth.identity`'s input: who a sign-in method (`provider`) says someone is, possibly changed by earlier plugins. */
402
+ export interface IdentityInput {
403
+ identity: Identity;
404
+ /** `owner-key`, `github`, `oidc:<id>`, `cloudflare-access`, `plugin:<id>`, … */
405
+ provider: string;
406
+ }
407
+ /**
408
+ * `auth.identity`'s answer: a changed identity (more groups, another name; `subject` must stay), `{reject}` to refuse
409
+ * the sign-in with a sentence the person sees, or nothing to leave it as it is.
410
+ */
411
+ export type IdentityResult = Identity | {
412
+ reject: string;
413
+ } | void | undefined;
414
+ /** `auth.signOutUrl`'s input. */
415
+ export interface SignOutInput {
416
+ principal: UserPrincipal;
417
+ }
418
+ /** `authz.role`'s input. */
419
+ export interface RoleInput {
420
+ principal: Principal;
421
+ artifact: ArtifactInfo;
422
+ /** What the host worked out from its own shares, or what an earlier plugin answered (null: no access). */
423
+ role: ArtifactRole | null;
424
+ }
425
+ /** `authz.role`'s answer: a role to replace `role`, `null` for no access, nothing for no opinion. */
426
+ export type RoleResult = ArtifactRole | null | void | undefined;
427
+ /** `authz.artifacts`'s input. */
428
+ export interface ArtifactsInput {
429
+ principal: Principal;
430
+ }
431
+ /** What `wake.deliver` receives: a request meant for the owner's agent. */
432
+ export interface WakeInput {
433
+ artifact: ArtifactInfo;
434
+ owner: UserInfo;
435
+ payload: WakePayload;
436
+ /** Who asked, and their role on the artifact. */
437
+ from: {
438
+ name: string;
439
+ role: ArtifactRole;
440
+ userId?: string;
441
+ };
442
+ }
443
+ /**
444
+ * A request to an agent (the Ask pane's text). Only requests are offered to `wake.deliver`: a wake that carries
445
+ * comment threads (comments sent to the agent) always goes to the owner's outbox, because the agent answers those
446
+ * inside the artifact's comment threads from the owner's computer, which a delivery elsewhere could not reply to.
447
+ */
448
+ export interface WakePayload {
449
+ kind: 'wake';
450
+ requests: Array<{
451
+ id: string;
452
+ text: string;
453
+ sentAt: string;
454
+ label?: string;
455
+ }>;
456
+ }
457
+ /** `{delivered: true}` when the plugin delivered it; nothing to let it go to the owner's outbox as usual. */
458
+ export type WakeResult = {
459
+ delivered: true;
460
+ } | void | undefined;
461
+ /** What a route handler receives. */
462
+ export interface RouteInput {
463
+ /** The request, body included. */
464
+ request: Request;
465
+ /** Who is asking (by the host's session cookie); `anonymous` for a webhook from another server. */
466
+ principal: Principal;
467
+ /** The `:name` parts of the route's path (and `*` for a trailing `*`). */
468
+ params: Record<string, string>;
469
+ }
470
+ /** A route's method (`*` for any). */
471
+ export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
472
+ /**
473
+ * An HTTP route, mounted at `/plugins/<id><path>` on the site. `path` starts with `/`; a segment `:name` matches one
474
+ * path segment into `params.name`; a final `*` matches the rest. A write (not GET, HEAD or OPTIONS) is accepted only
475
+ * from the site's own pages unless `public: true` (for a webhook from another server, which must then check its own
476
+ * signature: see {@link verifyHmacSha256}).
477
+ */
478
+ export interface PluginRoute<Config = Record<string, unknown>> {
479
+ method: HttpMethod | '*';
480
+ path: string;
481
+ public?: boolean;
482
+ handler(input: RouteInput, ctx: PluginContext<Config>): Awaitable<Response>;
483
+ }
484
+ /** A link the host shows: in the account menu, or on the home page. `href` is an `https:`/`http:` URL or a path. */
485
+ export interface PluginUiLink {
486
+ label: string;
487
+ href: string;
488
+ where: 'account-menu' | 'home';
489
+ }
490
+ /** Declarative additions to the host's pages. */
491
+ export interface PluginUi {
492
+ links?: PluginUiLink[];
493
+ /** The site's name and logo instead of Open Artifact's (the first plugin that sets one wins). */
494
+ brand?: {
495
+ name?: string;
496
+ logoUrl?: string;
497
+ };
498
+ }
499
+ /**
500
+ * A small durable key-value store private to the plugin (other plugins cannot see its keys). Values are anything
501
+ * JSON can carry. Limits: keys up to 512 bytes, values up to 64 KiB of JSON, 10,000 keys per plugin. Meant for
502
+ * caches, retry queues and small state, not for files.
503
+ */
504
+ export interface PluginKv {
505
+ /** The value, or null when there is none (or it expired). */
506
+ get<T = unknown>(key: string): Promise<T | null>;
507
+ /** Stores a value; `ttlSeconds` makes it expire. */
508
+ set(key: string, value: unknown, options?: {
509
+ ttlSeconds?: number;
510
+ }): Promise<void>;
511
+ delete(key: string): Promise<void>;
512
+ /** Entries in key order: those starting with `prefix`, after the key `after`, at most `limit` (default 100, at most 1000). */
513
+ list<T = unknown>(options?: {
514
+ prefix?: string;
515
+ after?: string;
516
+ limit?: number;
517
+ }): Promise<Array<{
518
+ key: string;
519
+ value: T;
520
+ expiresAt: string | null;
521
+ }>>;
522
+ }
523
+ /** What a plugin can ask of the host. */
524
+ export interface PluginHost {
525
+ /** The plugin API version the host runs this plugin with. */
526
+ apiVersion: number;
527
+ /** The host's version (`0.14.0`). */
528
+ version: string;
529
+ /** The site's address, e.g. `https://artifacts.example.com`. */
530
+ appOrigin: string;
531
+ /**
532
+ * Whether this host has a feature: a hook (`authz.role`), an event (`on.share.invited`), a guard action
533
+ * (`guard.agent.ask`) or a context member (`ctx.kv`).
534
+ */
535
+ supports(name: string): boolean;
536
+ users: {
537
+ get(id: string): Promise<UserInfo | null>;
538
+ findByEmail(email: string): Promise<UserInfo | null>;
539
+ };
540
+ artifacts: {
541
+ get(id: string): Promise<ArtifactInfo | null>;
542
+ /**
543
+ * The site's artifacts (not those in the trash), in id order, a page at a time: `owner` (a user id) for one
544
+ * person's, `limit` (default 50, at most 200 a call) and `after` (the `next` of the page before). Meant for small
545
+ * sites: a plugin that walks every page of a large site is slow on every request it does so; keep the answer
546
+ * (`ctx.kv` with a TTL) rather than listing again.
547
+ */
548
+ list(options?: ArtifactListOptions): Promise<ArtifactList>;
549
+ };
550
+ access: {
551
+ /** Forgets cached roles (of one artifact, or all) so the next request asks `authz.role` again. */
552
+ invalidate(artifactId?: string): Promise<void>;
553
+ };
554
+ /** Writes an entry to the host's audit log, as this plugin. `action` is short, e.g. `invite.sent`. */
555
+ audit(action: string, detail?: unknown): Promise<void>;
556
+ }
557
+ /** The second argument of every hook. The host may add members; a plugin ignores what it does not know. */
558
+ export interface PluginContext<Config = Record<string, unknown>> {
559
+ plugin: {
560
+ id: string;
561
+ };
562
+ /** The operator's settings, checked against the plugin's `config` schema, with defaults filled in. */
563
+ config: Readonly<Config>;
564
+ /** One line to the host's log, prefixed with the plugin's id. Secret settings are blanked out of it. */
565
+ log(message: string, fields?: Record<string, unknown>): void;
566
+ /** `fetch`, stopped when the hook's time runs out (pass your own `signal` to stop it sooner). */
567
+ fetch: typeof fetch;
568
+ kv: PluginKv;
569
+ /** The host's clock. */
570
+ now(): Date;
571
+ /** Aborted when the hook's time limit runs out. */
572
+ signal: AbortSignal;
573
+ host: PluginHost;
574
+ }
575
+ /**
576
+ * A setting's type. `secret` is a string the host never logs or shows. `map` is an object of strings by name
577
+ * (`{"staff": "editor"}`). `json` is any JSON value; the host checks only that it is JSON, so check its shape in the
578
+ * plugin's `validate`. Given as `{"env": "NAME"}`, a `map` or `json` setting reads the variable as JSON text.
579
+ */
580
+ export type ConfigFieldType = 'string' | 'number' | 'boolean' | 'string[]' | 'secret' | 'map' | 'json';
581
+ /**
582
+ * One setting a plugin declares. The operator may give any value as `{"env": "NAME"}` to read it from an environment
583
+ * variable (a Worker secret on Cloudflare), which is how secrets stay out of the configuration file.
584
+ */
585
+ export interface ConfigField {
586
+ readonly type: ConfigFieldType;
587
+ /** The operator must set it (a `default` makes that unnecessary). */
588
+ readonly required?: boolean;
589
+ readonly default?: string | number | boolean | readonly string[] | {
590
+ readonly [name: string]: string;
591
+ } | JsonValue;
592
+ /** One line for the operator (shown by `plugin check` and in error messages). */
593
+ readonly description?: string;
594
+ }
595
+ /** A plugin's settings, by name. */
596
+ export type ConfigSchema = {
597
+ readonly [name: string]: ConfigField;
598
+ };
599
+ /** The value type of a field. */
600
+ export type ConfigValue<F extends ConfigField> = F['type'] extends 'number' ? number : F['type'] extends 'boolean' ? boolean : F['type'] extends 'string[]' ? string[] : F['type'] extends 'map' ? Record<string, string> : F['type'] extends 'json' ? JsonValue : string;
601
+ /** A JSON value (what a `json` setting holds). */
602
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
603
+ [key: string]: JsonValue;
604
+ };
605
+ type AlwaysSet<F extends ConfigField> = F extends {
606
+ readonly required: true;
607
+ } ? true : F extends {
608
+ readonly default: unknown;
609
+ } ? true : false;
610
+ /** The config object a schema gives: required settings and those with a default are always there, others may be absent. */
611
+ export type ConfigOf<S extends ConfigSchema> = {
612
+ [K in keyof S as AlwaysSet<S[K]> extends true ? K : never]: ConfigValue<S[K]>;
613
+ } & {
614
+ [K in keyof S as AlwaysSet<S[K]> extends true ? never : K]?: ConfigValue<S[K]>;
615
+ };
616
+ /**
617
+ * One entry of the operator's plugin list (`OA_PLUGINS`, or `plugins.json` on the Node host):
618
+ * `[{"use": "@acme/oa-plugin", "config": {"url": "https://…", "secret": {"env": "ACME_SECRET"}}}]`.
619
+ */
620
+ export interface PluginEntry {
621
+ /** A package name or a path to the module (relative to the configuration file). */
622
+ use: string;
623
+ /** The plugin's settings. */
624
+ config?: Record<string, unknown>;
625
+ /** False to keep it listed but off. Default true. */
626
+ enabled?: boolean;
627
+ /** When the plugin cannot load or its settings are wrong, start without it (logged) instead of refusing to start. */
628
+ optional?: boolean;
629
+ /**
630
+ * Each hook call's time limit, ms (default 5000, at most 60000). It stops the host waiting; it cannot stop a
631
+ * plugin stuck in synchronous code.
632
+ */
633
+ timeoutMs?: number;
634
+ /** Overrides the plugin's own `authz.cacheSeconds`: how long role answers may be reused (0 to 86400). */
635
+ cacheSeconds?: number;
636
+ }
637
+ /** Sign-in hooks. */
638
+ export interface PluginAuth<Config = Record<string, unknown>> {
639
+ /**
640
+ * Who a request comes from, by itself: a header an upstream proxy sets, your app's cookie or JWT. The host makes a
641
+ * session from the answer, and asks again on every later request of that session (unless `recheck` is false): the
642
+ * same subject keeps it, another identity ends it and signs that one in, and `null` or nothing ends it (not this
643
+ * plugin's to say means no one, here). Throw when you could not decide (your upstream is down): that request is
644
+ * anonymous, but the session is kept for the next one.
645
+ */
646
+ authenticate?(input: AuthenticateInput, ctx: PluginContext<Config>): Awaitable<Identity | null | void | undefined>;
647
+ /**
648
+ * Whether the sessions `authenticate` makes are asked again on each request (default true). Set false only for an
649
+ * upstream that cannot answer on every request (it proves who someone is once, on a sign-in redirect, say): the
650
+ * session then lasts its 30 days, or until sign-out, whatever the upstream says later.
651
+ */
652
+ recheck?: boolean;
653
+ /** An interactive sign-in, shown as a button (`label`) on the sign-in page. */
654
+ signIn?: {
655
+ label: string;
656
+ /** Starts it: usually a redirect to your sign-in page that comes back to `callbackUrl`. */
657
+ start(input: SignInStartInput, ctx: PluginContext<Config>): Awaitable<Response>;
658
+ /** Completes it at `callbackUrl`: who signed in. Throw to refuse. */
659
+ finish(input: SignInFinishInput, ctx: PluginContext<Config>): Awaitable<SignInResult>;
660
+ };
661
+ /** After any sign-in method (built in or a plugin's): add groups, change the name, or refuse. */
662
+ identity?(input: IdentityInput, ctx: PluginContext<Config>): Awaitable<IdentityResult>;
663
+ /** Where to send someone after the host signs them out (to end your system's session too). */
664
+ signOutUrl?(input: SignOutInput, ctx: PluginContext<Config>): Awaitable<string | void | undefined>;
665
+ }
666
+ /** Permission hooks. */
667
+ export interface PluginAuthz<Config = Record<string, unknown>> {
668
+ /** A person's role on an artifact (see {@link RoleInput} and {@link RoleResult}). Plugins run in the list's order. */
669
+ role?(input: RoleInput, ctx: PluginContext<Config>): Awaitable<RoleResult>;
670
+ /** How long the host may reuse this plugin's role answers, seconds (default 30; 0: ask every time). */
671
+ cacheSeconds?: number;
672
+ /** Artifact ids this person can see beyond the host's own shares (for the home list; each is checked with `role`). */
673
+ artifacts?(input: ArtifactsInput, ctx: PluginContext<Config>): Awaitable<string[] | void | undefined>;
674
+ }
675
+ /** Event handlers, by event name. */
676
+ export type PluginEventHandlers<Config = Record<string, unknown>> = {
677
+ [E in PluginEventName]?: (event: PluginEvent<E>, ctx: PluginContext<Config>) => Awaitable<void>;
678
+ };
679
+ /** A host plugin. Every hook is optional. */
680
+ export interface HostPlugin<Config = Record<string, unknown>> {
681
+ /** Lower-case letters, digits and `-` (e.g. `acme-sso`). Unique on the site; part of its routes and its provider id. */
682
+ id: string;
683
+ /** The plugin API version it was written for: {@link PLUGIN_API_VERSION}. */
684
+ apiVersion: number;
685
+ /** A name for people (default: the id). */
686
+ name?: string;
687
+ /** The plugin's own version. */
688
+ version?: string;
689
+ description?: string;
690
+ /** The settings it takes. */
691
+ config?: ConfigSchema;
692
+ /**
693
+ * Checks the settings beyond their types, once at start-up after the host's own check (a setting needed only with
694
+ * another, the shape of a `json` setting). Return or throw a sentence (or several) to refuse them: the host then
695
+ * stops with a configuration error naming the plugin (or starts without it when the entry is `optional`).
696
+ */
697
+ validate?(config: Config): string | readonly string[] | void | undefined;
698
+ auth?: PluginAuth<Config>;
699
+ authz?: PluginAuthz<Config>;
700
+ /** A veto before an action happens (see {@link GuardAction}). Plugins run in order; the first `{deny}` wins. */
701
+ guard?(input: GuardInput, ctx: PluginContext<Config>): Awaitable<GuardResult>;
702
+ on?: PluginEventHandlers<Config>;
703
+ wake?: {
704
+ /** Delivers a request meant for the owner's agent elsewhere (a cloud agent runner). */
705
+ deliver?(input: WakeInput, ctx: PluginContext<Config>): Awaitable<WakeResult>;
706
+ };
707
+ routes?: ReadonlyArray<PluginRoute<Config>>;
708
+ ui?: PluginUi;
709
+ }
710
+ /** A plugin as {@link definePlugin} takes it: `config` is a schema, and the hooks' `ctx.config` follows from it. */
711
+ export type PluginDefinition<S extends ConfigSchema = ConfigSchema> = Omit<HostPlugin<ConfigOf<S>>, 'config'> & {
712
+ config?: S;
713
+ };
714
+ /**
715
+ * Returns the plugin as it is. It only gives your editor the types: with it, `ctx.config` in every hook has the
716
+ * settings your `config` schema declares.
717
+ *
718
+ * ```ts
719
+ * export default definePlugin({
720
+ * id: 'hello', apiVersion: 1,
721
+ * config: { greeting: { type: 'string', default: 'Hello' } },
722
+ * on: { 'user.signed_in': (e, ctx) => ctx.log(`${ctx.config.greeting}, ${e.user.name}`) },
723
+ * });
724
+ * ```
725
+ */
726
+ export declare function definePlugin<const S extends ConfigSchema = Record<never, never>>(plugin: PluginDefinition<S>): PluginDefinition<S>;
727
+ /**
728
+ * An error a route handler throws to answer with a status: `throw new HttpError(403, 'Bad signature.')` answers
729
+ * `403 {"code": "plugin_error", "message": "Bad signature."}`. Any other error answers a generic 500 (and is logged).
730
+ */
731
+ export declare class HttpError extends Error {
732
+ readonly status: number;
733
+ constructor(status: number, message: string);
734
+ }
735
+ /** A JSON answer (`Content-Type: application/json`, `Cache-Control: no-store` unless `init` sets them). */
736
+ export declare function json(value: unknown, init?: ResponseInit): Response;
737
+ /** The largest body {@link readJson} and {@link readBody} read by default: 1 MiB. */
738
+ export declare const DEFAULT_MAX_BODY_BYTES: number;
739
+ /** A request's whole body as bytes, refusing more than `maxBytes` (an {@link HttpError} 413). */
740
+ export declare function readBody(request: Request, maxBytes?: number): Promise<Uint8Array>;
741
+ /** A request's body as text (UTF-8): what a signature is checked over. */
742
+ export declare function readText(request: Request, maxBytes?: number): Promise<string>;
743
+ /** A request's body as JSON (an {@link HttpError} 400 when it is not JSON, 413 past `maxBytes`). */
744
+ export declare function readJson<T = unknown>(request: Request, maxBytes?: number): Promise<T>;
745
+ /**
746
+ * Whether two secrets are equal, taking the same time whatever their content (so the time an answer takes does not
747
+ * tell an attacker how much of a guess was right). Use it instead of `===` for every secret and signature.
748
+ */
749
+ export declare function timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
750
+ /** How a signature is written: hex (`a1b2…`), base64, or base64url. */
751
+ export type SignatureEncoding = 'hex' | 'base64' | 'base64url';
752
+ /** The HMAC-SHA256 of `body` under `secret`, written in `encoding` (default hex): to sign what a plugin sends. */
753
+ export declare function signHmacSha256(input: {
754
+ secret: string | Uint8Array;
755
+ body: string | Uint8Array;
756
+ encoding?: SignatureEncoding;
757
+ }): Promise<string>;
758
+ /**
759
+ * Whether `signature` is the HMAC-SHA256 of `body` under `secret` (compared in constant time). `body` must be the
760
+ * exact bytes received ({@link readText}), not re-serialized JSON. A `prefix` such as `sha256=` is removed from the
761
+ * signature first when present. Hex is compared without regard to case.
762
+ */
763
+ export declare function verifyHmacSha256(input: {
764
+ secret: string | Uint8Array;
765
+ body: string | Uint8Array;
766
+ signature: string | null | undefined;
767
+ encoding?: SignatureEncoding;
768
+ prefix?: string;
769
+ }): Promise<boolean>;
770
+ /** The algorithms {@link verifyJwt} takes. `none` and every other algorithm are refused. */
771
+ export type JwtAlgorithm = 'RS256' | 'ES256' | 'HS256';
772
+ /** A JSON Web Key, as a JWKS publishes it (the fields {@link verifyJwt} reads). */
773
+ export interface Jwk {
774
+ kty?: string;
775
+ kid?: string;
776
+ alg?: string;
777
+ use?: string;
778
+ crv?: string;
779
+ n?: string;
780
+ e?: string;
781
+ x?: string;
782
+ y?: string;
783
+ /** A symmetric key (`kty: 'oct'`), base64url. */
784
+ k?: string;
785
+ }
786
+ /** What {@link verifyJwt} checks a token against. */
787
+ export interface VerifyJwtOptions {
788
+ token: string;
789
+ /** Where the signing keys are published (fetched with the `fetch` you pass, kept for 10 minutes). */
790
+ jwksUrl?: string;
791
+ /** Or one key: a public JWK (RS256, ES256), a symmetric JWK, or a shared secret string (HS256). */
792
+ key?: Jwk | string;
793
+ /** The `iss` the token must carry. */
794
+ issuer?: string;
795
+ /** The `aud` the token must carry (one of them, when a list). */
796
+ audience?: string | string[];
797
+ /** The algorithms accepted (default: all three, each only with a key of its kind). */
798
+ algorithms?: JwtAlgorithm[];
799
+ /** Seconds of clock difference tolerated on `exp` and `nbf` (default 60). */
800
+ clockToleranceSeconds?: number;
801
+ /** Whether a token without `exp` is refused (default true: a token that never expires is rarely meant). */
802
+ requireExpiry?: boolean;
803
+ /** The clock (default: now). */
804
+ now?: Date;
805
+ }
806
+ /**
807
+ * {@link verifyJwt}'s answer: the claims, or why the token was refused (for your log, not for the person).
808
+ * `unavailable`: it could not be checked at all (the signing keys could not be fetched), which says nothing about the
809
+ * token: an `auth.authenticate` should throw then, so the host keeps the person's session for the next request
810
+ * instead of ending it.
811
+ */
812
+ export type VerifyJwtResult = {
813
+ valid: true;
814
+ claims: Record<string, unknown>;
815
+ header: {
816
+ alg: string;
817
+ kid?: string;
818
+ typ?: string;
819
+ };
820
+ } | {
821
+ valid: false;
822
+ reason: string;
823
+ unavailable?: true;
824
+ };
825
+ /**
826
+ * Verifies a compact JWT (JWS): its signature (RS256 and ES256 with public keys, HS256 with a shared secret; never
827
+ * `none`, and never an algorithm the key is not for), then `exp`, `nbf`, `iss` and `aud`. Keys come from `key` or
828
+ * from `jwksUrl` (by the token's `kid`; an unknown `kid` refetches the set once). Pass `ctx.fetch` as `fetcher`.
829
+ * Never throws for a bad token: the answer says why.
830
+ */
831
+ export declare function verifyJwt(options: VerifyJwtOptions, fetcher?: typeof fetch): Promise<VerifyJwtResult>;
832
+ export {};