@intentic/extension-api 1.431.0 → 1.433.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/README.md +138 -4
- package/dist/api.d.ts +1 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/backend-reach.d.ts +24 -0
- package/dist/backend-reach.d.ts.map +1 -0
- package/dist/backend-reach.js +262 -0
- package/dist/backend-reach.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/runtime.d.ts +12 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +111 -132
- package/dist/runtime.js.map +1 -1
- package/dist/server-reach.d.ts +72 -0
- package/dist/server-reach.d.ts.map +1 -0
- package/dist/server-reach.js +2 -0
- package/dist/server-reach.js.map +1 -0
- package/dist/server.d.ts +190 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/sleep-fake.d.ts +15 -0
- package/dist/sleep-fake.d.ts.map +1 -0
- package/dist/sleep-fake.js +99 -0
- package/dist/sleep-fake.js.map +1 -0
- package/dist/sleep-reach.d.ts +7 -0
- package/dist/sleep-reach.d.ts.map +1 -0
- package/dist/sleep-reach.js +104 -0
- package/dist/sleep-reach.js.map +1 -0
- package/dist/testing.d.ts +82 -9
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +367 -13
- package/dist/testing.js.map +1 -1
- package/dist/turn-reach.d.ts +7 -0
- package/dist/turn-reach.d.ts.map +1 -0
- package/dist/turn-reach.js +140 -0
- package/dist/turn-reach.js.map +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/dist/wire.d.ts +1 -1
- package/dist/wire.d.ts.map +1 -1
- package/dist/wire.js +2 -0
- package/dist/wire.js.map +1 -1
- package/package.json +4 -4
- package/src/api.ts +3 -0
- package/src/backend-reach.integration.test.ts +203 -0
- package/src/backend-reach.ts +365 -0
- package/src/caller.integration.test.ts +108 -0
- package/src/index.ts +1 -0
- package/src/runtime.ts +185 -157
- package/src/server-reach.ts +138 -0
- package/src/server.ts +374 -3
- package/src/sleep-fake.ts +140 -0
- package/src/sleep-reach.integration.test.ts +119 -0
- package/src/sleep-reach.ts +147 -0
- package/src/surface.json +15583 -0
- package/src/testing.ts +601 -23
- package/src/turn-reach.integration.test.ts +166 -0
- package/src/turn-reach.ts +198 -0
- package/src/version.ts +129 -1
- package/src/wire.ts +4 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import { createBackoff, sleep } from "@intentic/base/async";
|
|
2
|
+
import { errorMessage } from "@intentic/base/errors";
|
|
3
|
+
import { parseJsonWith } from "@intentic/base/json";
|
|
4
|
+
import type { ExtensionDeclaredReach } from "@intentic/extension-manifest/permissions";
|
|
5
|
+
import {
|
|
6
|
+
EXTENSION_EVENT_KINDS,
|
|
7
|
+
EXTENSION_EVENTS_HEARTBEAT_MS,
|
|
8
|
+
EXTENSION_EVENTS_KINDS_PARAM,
|
|
9
|
+
type ExtensionActivity,
|
|
10
|
+
extensionActivityUrl,
|
|
11
|
+
ExtensionEventSchema,
|
|
12
|
+
extensionEventsUrl,
|
|
13
|
+
ExtensionExecResultSchema,
|
|
14
|
+
extensionExecUrl,
|
|
15
|
+
type ExtensionIdentitySign,
|
|
16
|
+
ExtensionIdentitySignedSchema,
|
|
17
|
+
extensionIdentitySignUrl,
|
|
18
|
+
extensionIdentityUrl,
|
|
19
|
+
extensionWorkHoldUrl,
|
|
20
|
+
} from "@intentic/sandbox-contract/extension-protocol";
|
|
21
|
+
import { SandboxIdentitySchema } from "@intentic/sandbox-contract/schemas/s2s";
|
|
22
|
+
import type { CiFeedEvent } from "@intentic/sandbox-contract/schemas/ci";
|
|
23
|
+
import type { z } from "zod";
|
|
24
|
+
import type { Disposable } from "./disposable.js";
|
|
25
|
+
import type { ExtensionServerApi } from "./server.js";
|
|
26
|
+
import type { ExecOptions, ExecResult, RunSettled, SandboxActivity } from "./server-reach.js";
|
|
27
|
+
|
|
28
|
+
// What an extension's Node code hears and asks of the daemon besides its typed calls: the event stream (its settings, the
|
|
29
|
+
// workspace's changes and the kinds its manifest declares), work it holds in flight, commands it runs under a workload
|
|
30
|
+
// class, (2026-11-26) rows it writes in the sandbox's activity feed, and (2026-11-28) the sandbox's identity: its document
|
|
31
|
+
// and records signed as it. One implementation for the backend host and every declared process (runtime.ts); each declared reach
|
|
32
|
+
// is refused here before anything is sent, naming the manifest field, and the daemon refuses it again when asked.
|
|
33
|
+
|
|
34
|
+
type DaemonRequest = ExtensionServerApi["daemon"]["request"];
|
|
35
|
+
|
|
36
|
+
// What a listener of each kind is handed: the names that moved for the workspace's and settings' kinds, the frame itself
|
|
37
|
+
// for the kinds an extension declares.
|
|
38
|
+
interface Heard {
|
|
39
|
+
readonly files: readonly string[];
|
|
40
|
+
readonly refs: readonly string[];
|
|
41
|
+
readonly repos: readonly string[];
|
|
42
|
+
readonly settings: readonly string[];
|
|
43
|
+
readonly run: RunSettled;
|
|
44
|
+
readonly activity: SandboxActivity;
|
|
45
|
+
// (2026-11-26) A batch of CI feed frames, one per frame as it is heard; empty after a gap, as the workspace's kinds are.
|
|
46
|
+
readonly ci: readonly CiFeedEvent[];
|
|
47
|
+
}
|
|
48
|
+
type HeardKind = keyof Heard;
|
|
49
|
+
type Listener<K extends HeardKind> = (heard: Heard[K]) => void;
|
|
50
|
+
type Listeners = { readonly [K in HeardKind]: Set<Listener<K>> };
|
|
51
|
+
type Deliver = <K extends HeardKind>(kind: K, heard: Heard[K]) => void;
|
|
52
|
+
|
|
53
|
+
// How long a connection may go without a frame before it is taken for dead: three missed heartbeats.
|
|
54
|
+
const SILENCE_MS = EXTENSION_EVENTS_HEARTBEAT_MS * 3;
|
|
55
|
+
|
|
56
|
+
// Every complete line in `buffer`, and what is left after the last one.
|
|
57
|
+
const splitLines = (buffer: string) => {
|
|
58
|
+
const parts = buffer.split("\n");
|
|
59
|
+
const rest = parts.pop() ?? "";
|
|
60
|
+
return { lines: parts.map((line) => line.trim()).filter((line) => line !== ""), rest };
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// Hands a frame to its kind's listeners; a line this version cannot read (not JSON, or a kind a newer daemon sends) is
|
|
64
|
+
// skipped rather than fatal.
|
|
65
|
+
const deliverLine = (line: string, deliver: Deliver): void => {
|
|
66
|
+
const event = parseJsonWith(line, ExtensionEventSchema);
|
|
67
|
+
switch (event?.kind) {
|
|
68
|
+
case undefined:
|
|
69
|
+
case "heartbeat":
|
|
70
|
+
return;
|
|
71
|
+
case "files":
|
|
72
|
+
deliver("files", event.paths);
|
|
73
|
+
return;
|
|
74
|
+
case "settings":
|
|
75
|
+
deliver("settings", event.keys);
|
|
76
|
+
return;
|
|
77
|
+
case "refs":
|
|
78
|
+
case "repos":
|
|
79
|
+
deliver(event.kind, event.repos);
|
|
80
|
+
return;
|
|
81
|
+
case "run": {
|
|
82
|
+
const { kind: _kind, ...run } = event;
|
|
83
|
+
deliver("run", run);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
case "activity":
|
|
87
|
+
deliver("activity", { live: event.live });
|
|
88
|
+
return;
|
|
89
|
+
case "ci":
|
|
90
|
+
deliver("ci", [event.event]);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
// Reads one ndjson answer to its end, handing each complete line on; ends when the daemon ends it, `outer` aborts, or it
|
|
96
|
+
// falls silent past three heartbeats.
|
|
97
|
+
const readStream = async (open: (signal: AbortSignal) => Promise<Response>, outer: AbortSignal, line: (text: string) => void): Promise<void> => {
|
|
98
|
+
const connection = new AbortController();
|
|
99
|
+
const abort = (): void => connection.abort();
|
|
100
|
+
outer.addEventListener("abort", abort, { once: true });
|
|
101
|
+
let silence = setTimeout(abort, SILENCE_MS);
|
|
102
|
+
try {
|
|
103
|
+
const response = await open(connection.signal);
|
|
104
|
+
if (!response.ok || response.body === null) {
|
|
105
|
+
throw new Error(`the daemon answered ${response.status}${response.ok ? "" : `: ${(await response.text()).slice(0, 300)}`}`);
|
|
106
|
+
}
|
|
107
|
+
const reader = response.body.getReader();
|
|
108
|
+
const decoder = new TextDecoder();
|
|
109
|
+
let buffer = "";
|
|
110
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
|
|
111
|
+
clearTimeout(silence);
|
|
112
|
+
silence = setTimeout(abort, SILENCE_MS);
|
|
113
|
+
const split = splitLines(buffer + decoder.decode(chunk.value, { stream: true }));
|
|
114
|
+
buffer = split.rest;
|
|
115
|
+
for (const each of split.lines) {
|
|
116
|
+
line(each);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
} finally {
|
|
120
|
+
clearTimeout(silence);
|
|
121
|
+
outer.removeEventListener("abort", abort);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
export interface Streaming {
|
|
126
|
+
readonly open: (signal: AbortSignal) => Promise<Response>;
|
|
127
|
+
readonly line: (text: string) => void;
|
|
128
|
+
// Before every connection after the first, since frames may have been missed in between.
|
|
129
|
+
readonly gap: () => void;
|
|
130
|
+
readonly dropped: (why: string) => void;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Keeps one stream open while `signal` stands, connected again with backoff whenever it ends.
|
|
134
|
+
export const keepStreaming = async ({ open, line, gap, dropped }: Streaming, signal: AbortSignal): Promise<void> => {
|
|
135
|
+
let connections = 0;
|
|
136
|
+
const backoff = createBackoff({ floorMs: 1_000, capMs: 30_000, stableMs: SILENCE_MS });
|
|
137
|
+
while (!signal.aborted) {
|
|
138
|
+
if (connections > 0) {
|
|
139
|
+
gap();
|
|
140
|
+
}
|
|
141
|
+
connections += 1;
|
|
142
|
+
const opened = Date.now();
|
|
143
|
+
try {
|
|
144
|
+
await readStream(open, signal, line);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (!signal.aborted) {
|
|
147
|
+
dropped(errorMessage(error));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (signal.aborted) {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
await sleep(backoff.next(Date.now() - opened), { signal, unref: true });
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
// The extension's event stream: opened by the first listener, closed with the last, reconnected with backoff while
|
|
158
|
+
// anything listens. A drop means frames were missed, so a reconnect tells every listener of a workspace, settings or CI
|
|
159
|
+
// kind "anything may have changed" with an empty list, which is what a reader of an empty batch already does; `activity`
|
|
160
|
+
// is told afresh by the new stream itself, and a `run` missed in the gap is the reader's to catch up on.
|
|
161
|
+
const createEventHub = (open: (signal: AbortSignal) => Promise<Response>, log: (message: string) => void) => {
|
|
162
|
+
const listeners: Listeners = { files: new Set(), refs: new Set(), repos: new Set(), settings: new Set(), run: new Set(), activity: new Set(), ci: new Set() };
|
|
163
|
+
let running: AbortController | undefined;
|
|
164
|
+
const count = (): number => Object.values(listeners).reduce((sum, set) => sum + set.size, 0);
|
|
165
|
+
// SAFETY: `listeners[kind]` holds listeners of this very kind; the mapped type cannot say so through an index.
|
|
166
|
+
const setOf = <K extends HeardKind>(kind: K): Set<Listener<K>> => listeners[kind] as Set<Listener<K>>;
|
|
167
|
+
|
|
168
|
+
const deliver: Deliver = (kind, heard) => {
|
|
169
|
+
for (const listener of setOf(kind)) {
|
|
170
|
+
try {
|
|
171
|
+
listener(heard);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
// A throwing listener is its own bug; the stream and every other listener carry on.
|
|
174
|
+
log(`a ${kind} listener threw: ${errorMessage(error)}`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
const streaming: Streaming = {
|
|
180
|
+
open,
|
|
181
|
+
line: (text) => deliverLine(text, deliver),
|
|
182
|
+
gap: () => {
|
|
183
|
+
for (const kind of EXTENSION_EVENT_KINDS) {
|
|
184
|
+
deliver(kind, []);
|
|
185
|
+
}
|
|
186
|
+
deliver("ci", []);
|
|
187
|
+
},
|
|
188
|
+
dropped: (why) => log(`the event stream dropped (${why}); reconnecting`),
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const subscribe = <K extends HeardKind>(kind: K, listener: Listener<K>): Disposable => {
|
|
192
|
+
setOf(kind).add(listener);
|
|
193
|
+
if (running === undefined) {
|
|
194
|
+
running = new AbortController();
|
|
195
|
+
void keepStreaming(streaming, running.signal);
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
dispose: () => {
|
|
199
|
+
setOf(kind).delete(listener);
|
|
200
|
+
if (count() === 0) {
|
|
201
|
+
running?.abort();
|
|
202
|
+
running = undefined;
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
return {
|
|
209
|
+
subscribe,
|
|
210
|
+
close: (): void => {
|
|
211
|
+
for (const set of Object.values(listeners)) {
|
|
212
|
+
set.clear();
|
|
213
|
+
}
|
|
214
|
+
running?.abort();
|
|
215
|
+
running = undefined;
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
// One hold (`api.work.hold`): the hold door's answer kept open, and opened again after a drop, until disposed. Holding is
|
|
221
|
+
// best effort by design: a daemon that refuses it is said once in the log, never thrown at the holder mid-work.
|
|
222
|
+
const holdWork = (request: DaemonRequest, label: string, log: (message: string) => void): Disposable => {
|
|
223
|
+
const held = new AbortController();
|
|
224
|
+
let told = false;
|
|
225
|
+
void keepStreaming(
|
|
226
|
+
{
|
|
227
|
+
open: (signal) => request(extensionWorkHoldUrl(), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ label }), signal }),
|
|
228
|
+
line: () => undefined,
|
|
229
|
+
gap: () => undefined,
|
|
230
|
+
dropped: (why) => {
|
|
231
|
+
if (!told) {
|
|
232
|
+
told = true;
|
|
233
|
+
log(`holding "${label}" failed (${why}); trying again until it is let go`);
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
},
|
|
237
|
+
held.signal,
|
|
238
|
+
);
|
|
239
|
+
return { dispose: () => held.abort() };
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const EXEC_TIMEOUT_MS = 10 * 60_000;
|
|
243
|
+
const EXEC_OUTPUT_BYTES = 1024 * 1024;
|
|
244
|
+
|
|
245
|
+
// One command through the exec door, its answer read by the contract's schema. JSON leaves an absent option out.
|
|
246
|
+
const execThrough = async (request: DaemonRequest, argv: readonly string[], options: ExecOptions): Promise<ExecResult> => {
|
|
247
|
+
const body = JSON.stringify({
|
|
248
|
+
argv,
|
|
249
|
+
class: options.class ?? "command",
|
|
250
|
+
timeoutMs: options.timeoutMs ?? EXEC_TIMEOUT_MS,
|
|
251
|
+
outputBytes: options.outputBytes ?? EXEC_OUTPUT_BYTES,
|
|
252
|
+
cwd: options.cwd,
|
|
253
|
+
env: options.env,
|
|
254
|
+
stdin: options.stdin,
|
|
255
|
+
keep: options.keep,
|
|
256
|
+
label: options.label,
|
|
257
|
+
});
|
|
258
|
+
const answered = await request(extensionExecUrl(), { method: "POST", headers: { "content-type": "application/json" }, body, signal: options.signal ?? null });
|
|
259
|
+
if (!answered.ok) {
|
|
260
|
+
throw new Error(`daemon answered ${answered.status} for POST ${extensionExecUrl()}: ${(await answered.text()).slice(0, 300)}`);
|
|
261
|
+
}
|
|
262
|
+
return ExtensionExecResultSchema.parse(await answered.json());
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
// A door's JSON answer read by its schema, or the daemon's refusal as an error naming the route.
|
|
266
|
+
const answerWith = async <S extends z.ZodType>(schema: S, answered: Response, method: string, url: string): Promise<z.output<S>> => {
|
|
267
|
+
if (!answered.ok) {
|
|
268
|
+
throw new Error(`daemon answered ${answered.status} for ${method} ${url}: ${(await answered.text()).slice(0, 300)}`);
|
|
269
|
+
}
|
|
270
|
+
return schema.parse(await answered.json());
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// A refusal before anything is sent, naming the manifest field that would allow it.
|
|
274
|
+
const undeclared = (id: string, what: string, field: string): Error => new Error(`extension "${id}" ${what}: declare it in ${field} in its manifest`);
|
|
275
|
+
|
|
276
|
+
export interface BackendReach {
|
|
277
|
+
readonly onSettings: (listener: (keys: readonly string[]) => void) => Disposable;
|
|
278
|
+
readonly workspace: ExtensionServerApi["workspace"];
|
|
279
|
+
readonly events: ExtensionServerApi["events"];
|
|
280
|
+
readonly work: ExtensionServerApi["work"];
|
|
281
|
+
readonly exec: ExtensionServerApi["exec"];
|
|
282
|
+
readonly activity: ExtensionServerApi["activity"];
|
|
283
|
+
readonly identity: ExtensionServerApi["identity"];
|
|
284
|
+
// Ends the event stream; holds belong to their holders.
|
|
285
|
+
readonly close: () => void;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* The reach `declared` grants one extension, over `request` (its token on every call). The stream asks for every event
|
|
290
|
+
* kind the manifest declares: the daemon refuses a kind it does not, and one from before them ignores the question.
|
|
291
|
+
*/
|
|
292
|
+
export const createBackendReach = (id: string, request: DaemonRequest, declared: ExtensionDeclaredReach, log: (message: string) => void): BackendReach => {
|
|
293
|
+
const kinds = declared.events.length === 0 ? "" : `?${EXTENSION_EVENTS_KINDS_PARAM}=${declared.events.join(",")}`;
|
|
294
|
+
const hub = createEventHub((signal) => request(`${extensionEventsUrl()}${kinds}`, { signal }), log);
|
|
295
|
+
return {
|
|
296
|
+
onSettings: (listener) => hub.subscribe("settings", listener),
|
|
297
|
+
workspace: {
|
|
298
|
+
onDidChangeFiles: (listener) => hub.subscribe("files", listener),
|
|
299
|
+
onDidChangeRefs: (listener) => hub.subscribe("refs", listener),
|
|
300
|
+
onDidChangeRepos: (listener) => hub.subscribe("repos", listener),
|
|
301
|
+
},
|
|
302
|
+
events: {
|
|
303
|
+
onRunSettled: (listener) => {
|
|
304
|
+
if (!declared.events.includes("run")) {
|
|
305
|
+
throw undeclared(id, "listened for its conversations' runs (`run`) without declaring it", "permissions.events");
|
|
306
|
+
}
|
|
307
|
+
return hub.subscribe("run", listener);
|
|
308
|
+
},
|
|
309
|
+
onActivity: (listener) => {
|
|
310
|
+
if (!declared.events.includes("activity")) {
|
|
311
|
+
throw undeclared(id, "listened for the sandbox's activity (`activity`) without declaring it", "permissions.events");
|
|
312
|
+
}
|
|
313
|
+
return hub.subscribe("activity", listener);
|
|
314
|
+
},
|
|
315
|
+
onCi: (listener) => {
|
|
316
|
+
if (!declared.events.includes("ci")) {
|
|
317
|
+
throw undeclared(id, "listened for the CI feed (`ci`) without declaring it", "permissions.events");
|
|
318
|
+
}
|
|
319
|
+
return hub.subscribe("ci", listener);
|
|
320
|
+
},
|
|
321
|
+
},
|
|
322
|
+
work: {
|
|
323
|
+
hold: (label) => {
|
|
324
|
+
if (!declared.work) {
|
|
325
|
+
throw undeclared(id, `held work ("${label}") without declaring it`, "permissions.work");
|
|
326
|
+
}
|
|
327
|
+
return holdWork(request, label, log);
|
|
328
|
+
},
|
|
329
|
+
},
|
|
330
|
+
exec: async (argv, options = {}) => {
|
|
331
|
+
const workload = options.class ?? "command";
|
|
332
|
+
if (!declared.exec.includes(workload)) {
|
|
333
|
+
throw undeclared(id, `ran a command in the ${workload} class without declaring it`, "permissions.exec");
|
|
334
|
+
}
|
|
335
|
+
return execThrough(request, argv, options);
|
|
336
|
+
},
|
|
337
|
+
activity: {
|
|
338
|
+
append: async (row) => {
|
|
339
|
+
const answered = await request(extensionActivityUrl(), {
|
|
340
|
+
method: "POST",
|
|
341
|
+
headers: { "content-type": "application/json" },
|
|
342
|
+
body: JSON.stringify(row satisfies ExtensionActivity),
|
|
343
|
+
});
|
|
344
|
+
if (!answered.ok) {
|
|
345
|
+
throw new Error(`daemon answered ${answered.status} for POST ${extensionActivityUrl()}: ${(await answered.text()).slice(0, 300)}`);
|
|
346
|
+
}
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
identity: {
|
|
350
|
+
document: async () => answerWith(SandboxIdentitySchema, await request(extensionIdentityUrl()), "GET", extensionIdentityUrl()),
|
|
351
|
+
sign: async (purpose, payload) => {
|
|
352
|
+
if (!declared.identity.includes("sign")) {
|
|
353
|
+
throw undeclared(id, `signed a record ("${purpose}") as the sandbox without declaring it`, `permissions.identity ["sign"]`);
|
|
354
|
+
}
|
|
355
|
+
const answered = await request(extensionIdentitySignUrl(), {
|
|
356
|
+
method: "POST",
|
|
357
|
+
headers: { "content-type": "application/json" },
|
|
358
|
+
body: JSON.stringify({ purpose, payload } satisfies ExtensionIdentitySign),
|
|
359
|
+
});
|
|
360
|
+
return answerWith(ExtensionIdentitySignedSchema, answered, "POST", extensionIdentitySignUrl());
|
|
361
|
+
},
|
|
362
|
+
},
|
|
363
|
+
close: hub.close,
|
|
364
|
+
};
|
|
365
|
+
};
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { ExtensionCallerIdentity } from "@intentic/sandbox-contract/extension-protocol";
|
|
2
|
+
import type { ExtensionServerApi } from "./server.js";
|
|
3
|
+
import { type FakeExtension, fakeExtensionApi } from "./testing.js";
|
|
4
|
+
|
|
5
|
+
// Who a request into a backend comes from (`api.caller`), handed back to the daemon to act as them
|
|
6
|
+
// (`api.daemon.asCaller`), and the public routes a backend serves (`api.publicRoutes.serve`), on the SDK's fake daemon,
|
|
7
|
+
// which believes only the assertions its own proxy minted, as the daemon believes only its own key's.
|
|
8
|
+
|
|
9
|
+
const opened: FakeExtension[] = [];
|
|
10
|
+
const fake = async (options: Parameters<typeof fakeExtensionApi>[0]): Promise<FakeExtension> => {
|
|
11
|
+
const made = await fakeExtensionApi(options);
|
|
12
|
+
opened.push(made);
|
|
13
|
+
return made;
|
|
14
|
+
};
|
|
15
|
+
afterEach(async () => {
|
|
16
|
+
await Promise.all(opened.splice(0).map((each) => each.dispose()));
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const manifest = {
|
|
20
|
+
publisher: "acme",
|
|
21
|
+
name: "fixer",
|
|
22
|
+
permissions: { daemon: ["POST /agent"] },
|
|
23
|
+
contributes: { publicRoutes: [{ path: "hook", methods: ["POST" as const] }, { path: "*/report", methods: ["POST" as const], automation: true as const }] },
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// A backend whose button starts a turn as whoever pressed it, and answers what it knows of them.
|
|
27
|
+
const fixer = {
|
|
28
|
+
activateServer: (api: ExtensionServerApi) => {
|
|
29
|
+
api.routes.mount(async (request) => {
|
|
30
|
+
const caller = api.caller(request);
|
|
31
|
+
if (new URL(request.url).pathname === "/who") {
|
|
32
|
+
return Response.json(caller === undefined ? null : { kind: caller.kind, folders: caller.folders ?? null, app: caller.reaches("app"), web: caller.reaches("app/web"), up: caller.reaches("../app") });
|
|
33
|
+
}
|
|
34
|
+
if (caller === undefined) {
|
|
35
|
+
return Response.json({ error: "nobody vouched for this caller" }, { status: 401 });
|
|
36
|
+
}
|
|
37
|
+
const started = await api.daemon.asCaller(caller).request("/agent", { method: "POST", body: JSON.stringify({ prompt: "fix it", conversationId: "fix-1" }) });
|
|
38
|
+
return new Response(null, { status: started.status });
|
|
39
|
+
});
|
|
40
|
+
api.publicRoutes.serve(async (_request, verified) => Response.json(verified));
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
test("a backend reads who pressed, and the folders their areas hold, by segment", async () => {
|
|
45
|
+
const extension = await fake({ manifest });
|
|
46
|
+
await extension.activate(fixer);
|
|
47
|
+
expect(await (await extension.route("who", undefined, { caller: { kind: "person", email: "i@example.com", tier: "collaborator", areas: ["a"], folders: ["app/web"] } })).json()).toEqual({
|
|
48
|
+
kind: "person",
|
|
49
|
+
folders: ["app/web"],
|
|
50
|
+
app: false,
|
|
51
|
+
web: true,
|
|
52
|
+
up: false,
|
|
53
|
+
});
|
|
54
|
+
expect(await (await extension.route("who", undefined, { caller: { kind: "panel" } })).json()).toEqual({ kind: "panel", folders: null, app: true, web: true, up: false });
|
|
55
|
+
// Past its window, an assertion is no caller at all.
|
|
56
|
+
expect(await (await extension.route("who", undefined, { mintedAgoMs: 120_001 })).json()).toBeNull();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("asCaller carries the person's assertion to the daemon, which believes it only inside its window", async () => {
|
|
60
|
+
const extension = await fake({ manifest, daemon: () => Response.json({ delivered: "started", run: "r1" }) });
|
|
61
|
+
await extension.activate(fixer);
|
|
62
|
+
const intern: ExtensionCallerIdentity = { kind: "person", email: "intern@example.com", tier: "collaborator", areas: ["shop"], folders: ["shop"] };
|
|
63
|
+
|
|
64
|
+
expect((await extension.route("start", { method: "POST" }, { caller: intern })).status).toBe(200);
|
|
65
|
+
// A press answered after its window, handed back to the daemon too late.
|
|
66
|
+
expect((await extension.route("start", { method: "POST" }, { caller: intern, mintedAgoMs: 120_001 })).status).toBe(401);
|
|
67
|
+
expect(extension.calls).toEqual([{ line: "POST /agent", admitted: true, caller: { kind: "person", email: "intern@example.com", tier: "collaborator", areas: ["shop"] } }]);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("an assertion this fake's proxy did not mint is refused by its daemon, as the daemon refuses one not signed with its key", async () => {
|
|
71
|
+
const extension = await fake({ manifest, daemon: () => Response.json({}) });
|
|
72
|
+
await extension.activate({
|
|
73
|
+
activateServer: (api: ExtensionServerApi) => {
|
|
74
|
+
api.routes.mount(async (request) => {
|
|
75
|
+
const caller = api.caller(request);
|
|
76
|
+
if (caller === undefined) {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
// The claim rewritten to name the owner, with the signature it came with.
|
|
80
|
+
const [encoded = "", signature = ""] = caller.assertion.split(".");
|
|
81
|
+
const claim = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
|
|
82
|
+
const promoted = Buffer.from(JSON.stringify({ ...claim, caller: { kind: "person", email: "owner@example.com", tier: "owner" } }), "utf8").toString("base64url");
|
|
83
|
+
const forged = { ...caller, assertion: `${promoted}.${signature}` };
|
|
84
|
+
return new Response(null, { status: (await api.daemon.asCaller(forged).request("/agent", { method: "POST", body: "{}" })).status });
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
expect((await extension.route("start", { method: "POST" }, { caller: { kind: "panel" } })).status).toBe(401);
|
|
89
|
+
expect(extension.calls).toEqual([{ line: "POST /agent", admitted: false }]);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("a public route hears what the door checked, and a path or method no route declares never reaches it", async () => {
|
|
93
|
+
const extension = await fake({ manifest });
|
|
94
|
+
await extension.activate(fixer);
|
|
95
|
+
expect(await (await extension.publicRoute("bugs-1/report", { method: "POST", body: "{}" }, { origin: "https://shop.example" })).json()).toEqual({
|
|
96
|
+
route: "*/report",
|
|
97
|
+
at: expect.any(Number),
|
|
98
|
+
automationId: "bugs-1",
|
|
99
|
+
origin: "https://shop.example",
|
|
100
|
+
});
|
|
101
|
+
expect(await (await extension.publicRoute("hook", { method: "POST" }, { signature: { scheme: "github", deliveryId: "d-1" } })).json()).toEqual({
|
|
102
|
+
route: "hook",
|
|
103
|
+
at: expect.any(Number),
|
|
104
|
+
signature: { scheme: "github", deliveryId: "d-1" },
|
|
105
|
+
});
|
|
106
|
+
await expect(extension.publicRoute("hook", { method: "GET" })).rejects.toThrow('"acme.fixer" declares no public route answering GET /hook');
|
|
107
|
+
await expect(extension.publicRoute("other", { method: "POST" })).rejects.toThrow("declares no public route");
|
|
108
|
+
});
|