@plimsollmark/client 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 +201 -0
- package/README.md +177 -0
- package/dist/client.d.ts +278 -0
- package/dist/client.js +528 -0
- package/dist/errors.d.ts +42 -0
- package/dist/errors.js +132 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/mastra.d.ts +27 -0
- package/dist/mastra.js +30 -0
- package/dist/record.d.ts +78 -0
- package/dist/record.js +250 -0
- package/dist/sandboxes.d.ts +116 -0
- package/dist/sandboxes.js +316 -0
- package/dist/tool.d.ts +31 -0
- package/dist/tool.js +49 -0
- package/dist/trigger.d.ts +17 -0
- package/dist/trigger.js +29 -0
- package/dist/wire.d.ts +187 -0
- package/dist/wire.js +6 -0
- package/package.json +76 -0
package/dist/client.js
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
// A plimsolld client for TypeScript: Connect's JSON protocol over fetch, no
|
|
2
|
+
// protobuf runtime and no dependencies. It keeps the official Go client's
|
|
3
|
+
// promises (package client): it states the protocol number on every request,
|
|
4
|
+
// checks every run record against what it sent and received, checks the
|
|
5
|
+
// isolation evidence against the caller's floor, and tracks a session's chain of
|
|
6
|
+
// records so a call it did not make is caught.
|
|
7
|
+
import { isIP } from "node:net";
|
|
8
|
+
import { checkRecord, requestDigest, sessionFingerprint, softwareRuleAllows, } from "./record.js";
|
|
9
|
+
import { errorFromWire, PlimsollError, sessionEndFromWire } from "./errors.js";
|
|
10
|
+
/** The wire protocol number this client speaks (protocol.Number in Go). */
|
|
11
|
+
export const PROTOCOL = 2;
|
|
12
|
+
const SERVICE = "plimsoll.v1.SandboxService";
|
|
13
|
+
// Above the largest legitimate project response, so a misbehaving daemon cannot
|
|
14
|
+
// make the client buffer without bound (the Go client's maxResponseBytes).
|
|
15
|
+
const MAX_RESPONSE_BYTES = 32 << 20;
|
|
16
|
+
const TIERS = ["none", "process", "container", "kernel", "vm"];
|
|
17
|
+
/** Whether a tier the daemon reported meets a floor. An unknown tier meets nothing. */
|
|
18
|
+
export function meets(actual, floor) {
|
|
19
|
+
const a = TIERS.indexOf(actual);
|
|
20
|
+
return a >= 0 && a >= TIERS.indexOf(floor);
|
|
21
|
+
}
|
|
22
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 6 * 60_000;
|
|
23
|
+
function validateBaseUrl(raw, insecureHttp) {
|
|
24
|
+
if (raw === "" || raw !== raw.trim())
|
|
25
|
+
throw new PlimsollError("invalid_argument", "plimsoll: base URL must be non-empty with no surrounding whitespace");
|
|
26
|
+
let u;
|
|
27
|
+
try {
|
|
28
|
+
u = new URL(raw);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new PlimsollError("invalid_argument", "plimsoll: base URL must be an absolute HTTP or HTTPS URL");
|
|
32
|
+
}
|
|
33
|
+
if (u.protocol !== "http:" && u.protocol !== "https:")
|
|
34
|
+
throw new PlimsollError("invalid_argument", "plimsoll: base URL scheme must be http or https");
|
|
35
|
+
if (u.username || u.password || u.search || raw.includes("?") || raw.includes("#")) {
|
|
36
|
+
throw new PlimsollError("invalid_argument", "plimsoll: userinfo, query and fragment are not permitted in the base URL");
|
|
37
|
+
}
|
|
38
|
+
const host = u.hostname.replace(/^\[|\]$/g, "");
|
|
39
|
+
// A host is loopback by name or as an address, never by a prefix: 127.evil.example is a
|
|
40
|
+
// domain name, and the token must not go to it in cleartext.
|
|
41
|
+
const loopback = host === "localhost" || host === "::1" || (isIP(host) === 4 && host.startsWith("127."));
|
|
42
|
+
if (u.protocol === "http:" && !loopback && !insecureHttp) {
|
|
43
|
+
throw new PlimsollError("invalid_argument", "plimsoll: cleartext HTTP to a non-loopback daemon requires insecureHttp");
|
|
44
|
+
}
|
|
45
|
+
return u.toString().replace(/\/+$/, "");
|
|
46
|
+
}
|
|
47
|
+
function timeoutMs(ms) {
|
|
48
|
+
if (ms === undefined || !(ms > 0))
|
|
49
|
+
return 0;
|
|
50
|
+
return Math.min(Math.max(1, Math.round(ms)), 2 ** 31 - 1);
|
|
51
|
+
}
|
|
52
|
+
function durationMs(ms) {
|
|
53
|
+
if (ms === undefined || !(ms > 0))
|
|
54
|
+
return 0;
|
|
55
|
+
return Math.min(Math.round(ms), 2 ** 32 - 1);
|
|
56
|
+
}
|
|
57
|
+
function validateRule(rule) {
|
|
58
|
+
if (!rule)
|
|
59
|
+
return undefined;
|
|
60
|
+
const ids = rule.identities;
|
|
61
|
+
const ok = (rule.mode === "exact" ? ids.length === 1 : rule.mode === "approved" && ids.length >= 1 && ids.length <= 32) &&
|
|
62
|
+
new Set(ids).size === ids.length &&
|
|
63
|
+
ids.every((id) => id.length > 0 && id.length <= 256 && /^[A-Za-z0-9._:/@+-]+$/.test(id));
|
|
64
|
+
if (!ok) {
|
|
65
|
+
throw new PlimsollError("invalid_argument", "plimsoll: software rule needs exact with one identity or approved with 1 to 32 identities", {
|
|
66
|
+
notDispatched: "request",
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return { mode: rule.mode, identities: [...ids] };
|
|
70
|
+
}
|
|
71
|
+
// The intersection of a session's rule and a call's: neither can be weakened.
|
|
72
|
+
function mergeRules(a, b) {
|
|
73
|
+
if (!a)
|
|
74
|
+
return b;
|
|
75
|
+
if (!b)
|
|
76
|
+
return a;
|
|
77
|
+
const ids = a.identities.filter((id) => b.identities.includes(id));
|
|
78
|
+
if (ids.length === 0) {
|
|
79
|
+
throw new PlimsollError("invalid_argument", "plimsoll: the call's software rule shares no identity with the session's", { notDispatched: "request" });
|
|
80
|
+
}
|
|
81
|
+
return { mode: ids.length === 1 ? "exact" : "approved", identities: ids };
|
|
82
|
+
}
|
|
83
|
+
const num = (v) => Number(v ?? 0);
|
|
84
|
+
const bytes = (s) => new Uint8Array(Buffer.from(s ?? "", "base64"));
|
|
85
|
+
const text = (b) => Buffer.from(b).toString("utf8");
|
|
86
|
+
function adviceFromWire(a) {
|
|
87
|
+
return (a ?? []).map((f) => ({
|
|
88
|
+
pattern: f.pattern ?? "",
|
|
89
|
+
severity: f.severity ?? "",
|
|
90
|
+
remedy: f.remedy ?? "",
|
|
91
|
+
method: f.method ?? "",
|
|
92
|
+
route: f.route ?? "",
|
|
93
|
+
detail: f.detail ?? "",
|
|
94
|
+
suggestedMethod: f.suggestedMethod ?? "",
|
|
95
|
+
suggestedRoute: f.suggestedRoute ?? "",
|
|
96
|
+
extraCalls: f.extraCalls ?? 0,
|
|
97
|
+
addedLatencyMs: num(f.addedLatencyMs),
|
|
98
|
+
bytesMoved: num(f.bytesMoved),
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
function evidence(resp, record) {
|
|
102
|
+
return {
|
|
103
|
+
sandbox: resp.sandbox ?? "",
|
|
104
|
+
isolation: resp.isolation ?? "",
|
|
105
|
+
softwareIdentity: resp.softwareIdentity ?? "",
|
|
106
|
+
environment: resp.environment ?? "",
|
|
107
|
+
durationMs: num(resp.durationMs),
|
|
108
|
+
record,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function javascriptResult(resp, record) {
|
|
112
|
+
const j = resp.javascript ?? {};
|
|
113
|
+
const out = bytes(j.stdout);
|
|
114
|
+
const err = bytes(j.stderr);
|
|
115
|
+
return {
|
|
116
|
+
...evidence(resp, record),
|
|
117
|
+
stdout: text(out),
|
|
118
|
+
stderr: text(err),
|
|
119
|
+
stdoutBytes: out,
|
|
120
|
+
stderrBytes: err,
|
|
121
|
+
exitCode: j.exitCode ?? 0,
|
|
122
|
+
timedOut: j.timedOut ?? false,
|
|
123
|
+
stdoutTruncated: j.stdoutTruncated ?? false,
|
|
124
|
+
stderrTruncated: j.stderrTruncated ?? false,
|
|
125
|
+
advice: adviceFromWire(j.advice),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function outcomeFromWire(v) {
|
|
129
|
+
const names = ["unspecified", "completed", "setup_failed", "timed_out", "protocol_error"];
|
|
130
|
+
if (typeof v === "number")
|
|
131
|
+
return names[v] ?? "unspecified";
|
|
132
|
+
const name = (v ?? "").replace(/^PROJECT_OUTCOME_/, "").toLowerCase();
|
|
133
|
+
return names.includes(name) ? name : "unspecified";
|
|
134
|
+
}
|
|
135
|
+
function projectResult(resp, record) {
|
|
136
|
+
const p = resp.project ?? {};
|
|
137
|
+
return {
|
|
138
|
+
...evidence(resp, record),
|
|
139
|
+
outcome: outcomeFromWire(p.outcome),
|
|
140
|
+
detail: p.outcomeDetail ?? "",
|
|
141
|
+
steps: (p.steps ?? []).map((s) => ({
|
|
142
|
+
command: s.command ?? "",
|
|
143
|
+
stdout: text(bytes(s.stdout)),
|
|
144
|
+
stderr: text(bytes(s.stderr)),
|
|
145
|
+
exitCode: s.exitCode ?? 0,
|
|
146
|
+
timedOut: s.timedOut ?? false,
|
|
147
|
+
durationMs: num(s.durationMs),
|
|
148
|
+
stdoutTruncated: s.stdoutTruncated ?? false,
|
|
149
|
+
stderrTruncated: s.stderrTruncated ?? false,
|
|
150
|
+
})),
|
|
151
|
+
artifacts: (p.artifacts ?? []).map((a) => ({ path: a.path ?? "", content: bytes(a.content) })),
|
|
152
|
+
artifactsTruncated: p.artifactsTruncated ?? false,
|
|
153
|
+
advice: adviceFromWire(p.advice),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function cellResult(resp, record) {
|
|
157
|
+
const c = resp.cell ?? {};
|
|
158
|
+
const out = bytes(c.stdout);
|
|
159
|
+
const err = bytes(c.stderr);
|
|
160
|
+
return {
|
|
161
|
+
...evidence(resp, record),
|
|
162
|
+
stdout: text(out),
|
|
163
|
+
stderr: text(err),
|
|
164
|
+
stdoutBytes: out,
|
|
165
|
+
stderrBytes: err,
|
|
166
|
+
exitCode: c.exitCode ?? 0,
|
|
167
|
+
timedOut: c.timedOut ?? false,
|
|
168
|
+
stdoutTruncated: c.stdoutTruncated ?? false,
|
|
169
|
+
stderrTruncated: c.stderrTruncated ?? false,
|
|
170
|
+
interpreterStarted: c.interpreterStarted ?? false,
|
|
171
|
+
interpreterEnded: c.interpreterEnded ?? false,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function digestPayload(p) {
|
|
175
|
+
if ("javascript" in p)
|
|
176
|
+
return { kind: "javascript", code: p.javascript.code, grantProfile: p.javascript.grantProfile ?? "" };
|
|
177
|
+
if ("cell" in p)
|
|
178
|
+
return { kind: "cell", language: p.cell.language, code: p.cell.code, files: p.cell.files };
|
|
179
|
+
return { kind: "project", grantProfile: p.project.grantProfile ?? "", files: p.project.files, steps: p.project.steps, artifacts: p.project.artifacts };
|
|
180
|
+
}
|
|
181
|
+
export class PlimsollClient {
|
|
182
|
+
base;
|
|
183
|
+
token;
|
|
184
|
+
fetchImpl;
|
|
185
|
+
requestTimeoutMs;
|
|
186
|
+
/** @internal */ jsGrant;
|
|
187
|
+
/** @internal */ projectGrant;
|
|
188
|
+
constructor(opts) {
|
|
189
|
+
this.base = validateBaseUrl(opts.baseUrl, opts.insecureHttp ?? false);
|
|
190
|
+
this.token = opts.token;
|
|
191
|
+
this.fetchImpl = opts.fetch ?? fetch;
|
|
192
|
+
const rt = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
193
|
+
if (typeof rt !== "number" || !(rt > 0) || rt > 2 ** 31 - 1) {
|
|
194
|
+
throw new PlimsollError("invalid_argument", "plimsoll: requestTimeoutMs must be a positive number of milliseconds");
|
|
195
|
+
}
|
|
196
|
+
this.requestTimeoutMs = rt;
|
|
197
|
+
this.jsGrant = opts.javascriptGrantProfile ?? "";
|
|
198
|
+
this.projectGrant = opts.projectGrantProfile ?? "";
|
|
199
|
+
}
|
|
200
|
+
/** @internal One unary Connect call with the JSON codec. */
|
|
201
|
+
async call(method, body, signal) {
|
|
202
|
+
const headers = { "Content-Type": "application/json", "Connect-Protocol-Version": "1" };
|
|
203
|
+
if (this.token)
|
|
204
|
+
headers["Authorization"] = `Bearer ${this.token}`;
|
|
205
|
+
const deadline = AbortSignal.timeout(this.requestTimeoutMs);
|
|
206
|
+
const both = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
207
|
+
// Neither error is marked not-dispatched: the request may have reached the daemon.
|
|
208
|
+
const cut = (e) => {
|
|
209
|
+
if (signal?.aborted)
|
|
210
|
+
return new PlimsollError("canceled", "plimsoll: the call was canceled", { cause: e });
|
|
211
|
+
if (deadline.aborted)
|
|
212
|
+
return new PlimsollError("deadline_exceeded", `plimsoll: ${method} did not finish within ${this.requestTimeoutMs} ms`, { cause: e });
|
|
213
|
+
return undefined;
|
|
214
|
+
};
|
|
215
|
+
let res;
|
|
216
|
+
try {
|
|
217
|
+
// A Connect call is never redirected, and fetch's default follows a 307 or 308 by
|
|
218
|
+
// sending the request again, the code in it included, wherever it points (it
|
|
219
|
+
// drops the token only across origins). So a redirect is the answer, an error.
|
|
220
|
+
res = await this.fetchImpl(`${this.base}/${SERVICE}/${method}`, { method: "POST", headers, body: JSON.stringify(body), signal: both, redirect: "manual" });
|
|
221
|
+
}
|
|
222
|
+
catch (e) {
|
|
223
|
+
throw cut(e) ?? new PlimsollError("unavailable", `plimsoll: ${e.message}`, { cause: e });
|
|
224
|
+
}
|
|
225
|
+
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
|
|
226
|
+
void res.body?.cancel().catch(() => undefined);
|
|
227
|
+
throw new PlimsollError("unknown", `plimsoll: ${method} was answered with a redirect (HTTP ${res.status}), which this client never follows`);
|
|
228
|
+
}
|
|
229
|
+
let raw;
|
|
230
|
+
try {
|
|
231
|
+
raw = await readCapped(res, both);
|
|
232
|
+
}
|
|
233
|
+
catch (e) {
|
|
234
|
+
if (e instanceof PlimsollError)
|
|
235
|
+
throw e;
|
|
236
|
+
throw cut(e) ?? new PlimsollError("unavailable", `plimsoll: reading the answer to ${method}: ${e.message}`, { cause: e });
|
|
237
|
+
}
|
|
238
|
+
let parsed;
|
|
239
|
+
try {
|
|
240
|
+
parsed = raw.length ? JSON.parse(raw) : {};
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
parsed = undefined;
|
|
244
|
+
}
|
|
245
|
+
if (!res.ok)
|
|
246
|
+
throw errorFromWire(res.status, parsed);
|
|
247
|
+
if (parsed === undefined || typeof parsed !== "object")
|
|
248
|
+
throw new PlimsollError("internal", "plimsoll: the daemon's answer is not a JSON message");
|
|
249
|
+
return parsed;
|
|
250
|
+
}
|
|
251
|
+
/** The daemon's own statement of its provider, tier and what it supports. */
|
|
252
|
+
async describe(signal) {
|
|
253
|
+
const m = await this.call("Describe", {}, signal);
|
|
254
|
+
const env = (e) => ({
|
|
255
|
+
identity: e?.identity ?? "",
|
|
256
|
+
softwareIdentity: e?.softwareIdentity ?? "",
|
|
257
|
+
maxTimeoutMs: e?.maxTimeoutMs ?? 0,
|
|
258
|
+
languages: (e?.languages ?? []).filter((l) => l === "javascript" || l === "python"),
|
|
259
|
+
});
|
|
260
|
+
return {
|
|
261
|
+
sandbox: m.sandbox ?? "",
|
|
262
|
+
isolation: m.isolation ?? "",
|
|
263
|
+
protocol: m.protocol ?? 0,
|
|
264
|
+
supportsProject: m.supportsProject ?? false,
|
|
265
|
+
supportsModule: m.supportsModule ?? false,
|
|
266
|
+
supportsJavaScriptGrants: m.supportsJavascriptGrants ?? false,
|
|
267
|
+
supportsProjectGrants: m.supportsProjectGrants ?? false,
|
|
268
|
+
supportsSessions: m.supportsSessions ?? false,
|
|
269
|
+
sessionLifetimeMs: m.sessionLifetimeMs ?? 0,
|
|
270
|
+
sessionIdleTimeoutMs: m.sessionIdleTimeoutMs ?? 0,
|
|
271
|
+
environments: {
|
|
272
|
+
javascript: env(m.javascriptEnvironment),
|
|
273
|
+
project: env(m.projectEnvironment),
|
|
274
|
+
module: env(m.moduleEnvironment),
|
|
275
|
+
policy: m.policy ?? "",
|
|
276
|
+
},
|
|
277
|
+
resources: {
|
|
278
|
+
memoryMb: m.resources?.memoryMb ?? 0,
|
|
279
|
+
cpus: m.resources?.cpus ?? 0,
|
|
280
|
+
pids: m.resources?.pids ?? 0,
|
|
281
|
+
diskMb: m.resources?.diskMb ?? 0,
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
/** Runs a JavaScript snippet in a fresh sandbox. */
|
|
286
|
+
async runJavaScript(code, opts = {}) {
|
|
287
|
+
const resp = await this.exchange("Run", this.envelope(opts, validateRule(opts.software)), { javascript: { code, grantProfile: this.jsGrant || undefined } }, opts);
|
|
288
|
+
return finish(resp.run, resp.record, javascriptResult, "javascript", opts.minimumIsolation);
|
|
289
|
+
}
|
|
290
|
+
/** Writes a multi-file project into a fresh sandbox and runs its steps in order. */
|
|
291
|
+
async runProject(req, opts = {}) {
|
|
292
|
+
const resp = await this.exchange("Run", this.envelope(opts, validateRule(opts.software)), projectPayload(req, this.projectGrant), opts);
|
|
293
|
+
return finish(resp.run, resp.record, projectResult, "project", opts.minimumIsolation);
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Opens a session: one sandbox kept for many calls, files persisting, and of
|
|
297
|
+
* processes only the interpreters runCell keeps. Only on a daemon whose Describe
|
|
298
|
+
* states supportsSessions.
|
|
299
|
+
*/
|
|
300
|
+
async openSession(opts = {}) {
|
|
301
|
+
const rule = validateRule(opts.software);
|
|
302
|
+
const m = await this.call("OpenSession", {
|
|
303
|
+
protocol: PROTOCOL,
|
|
304
|
+
minimumIsolation: opts.minimumIsolation,
|
|
305
|
+
traceId: opts.traceId,
|
|
306
|
+
lifetimeMs: durationMs(opts.lifetimeMs) || undefined,
|
|
307
|
+
idleTimeoutMs: durationMs(opts.idleTimeoutMs) || undefined,
|
|
308
|
+
softwareRule: rule,
|
|
309
|
+
}, opts.signal);
|
|
310
|
+
const s = new Session(this, m, rule);
|
|
311
|
+
if (s.fingerprint !== sessionFingerprint(m.sessionId ?? "")) {
|
|
312
|
+
throw new PlimsollError("data_loss", "plimsoll: the daemon's session fingerprint does not match its session ID");
|
|
313
|
+
}
|
|
314
|
+
if (opts.minimumIsolation && !meets(s.isolation, opts.minimumIsolation)) {
|
|
315
|
+
await s.close().catch(() => undefined);
|
|
316
|
+
throw new PlimsollError("data_loss", `plimsoll: the session opened at ${s.isolation}, below the requested ${opts.minimumIsolation}`);
|
|
317
|
+
}
|
|
318
|
+
if (!softwareRuleAllows(rule, m.softwareIdentity ?? "")) {
|
|
319
|
+
await s.close().catch(() => undefined);
|
|
320
|
+
throw new PlimsollError("data_loss", "plimsoll: the session's selected software is outside the requested rule");
|
|
321
|
+
}
|
|
322
|
+
return s;
|
|
323
|
+
}
|
|
324
|
+
/** @internal */
|
|
325
|
+
envelope(opts, rule) {
|
|
326
|
+
return {
|
|
327
|
+
protocol: PROTOCOL,
|
|
328
|
+
minimumIsolation: opts.minimumIsolation,
|
|
329
|
+
traceId: opts.traceId,
|
|
330
|
+
timeoutMs: timeoutMs(opts.timeoutMs) || undefined,
|
|
331
|
+
softwareRule: rule,
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
// Sends one Run and checks its record.
|
|
335
|
+
async exchange(method, env, payload, opts) {
|
|
336
|
+
const resp = await this.call(method, { ...env, ...payload }, opts.signal);
|
|
337
|
+
const checked = checkRecord(requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: env.softwareRule, payload: digestPayload(payload) }), env.protocol, env.softwareRule, resp);
|
|
338
|
+
if ("problem" in checked)
|
|
339
|
+
throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { result: resp });
|
|
340
|
+
const r = checked.record;
|
|
341
|
+
if (r.session !== "" || r.sequence !== 0n || r.previousSha256 !== "") {
|
|
342
|
+
throw new PlimsollError("data_loss", "plimsoll: a single run's record carries session fields", { result: resp });
|
|
343
|
+
}
|
|
344
|
+
return { run: resp, record: r };
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
/** @internal */
|
|
348
|
+
export function projectPayload(req, grantProfile) {
|
|
349
|
+
return {
|
|
350
|
+
project: {
|
|
351
|
+
files: req.files.map((f) => ({ path: f.path, content: f.content })),
|
|
352
|
+
steps: [...req.steps],
|
|
353
|
+
artifacts: [...(req.artifacts ?? [])],
|
|
354
|
+
grantProfile: grantProfile || undefined,
|
|
355
|
+
},
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
// Maps a checked response and applies the two checks that follow the record:
|
|
359
|
+
// the result is of the request's kind, and the tier meets the floor.
|
|
360
|
+
function finish(resp, record, map, kind, floor) {
|
|
361
|
+
const kinds = ["javascript", "project", "module", "cell"].filter((k) => resp[k] !== undefined && resp[k] !== null);
|
|
362
|
+
if (kinds.length > 1)
|
|
363
|
+
throw new PlimsollError("data_loss", `plimsoll: the answer holds ${kinds.length} results; a run has one`, { result: resp });
|
|
364
|
+
if (!resp[kind])
|
|
365
|
+
throw new PlimsollError("data_loss", "plimsoll: the daemon's result is not of the request's kind", { result: resp });
|
|
366
|
+
const out = map(resp, record);
|
|
367
|
+
if (floor && !meets(out.isolation, floor)) {
|
|
368
|
+
throw new PlimsollError("data_loss", `plimsoll: result isolation ${out.isolation} is below the requested ${floor}; execution may have occurred`, { result: out });
|
|
369
|
+
}
|
|
370
|
+
return out;
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* An open session. Calls are serialized here as they are on the daemon, so the
|
|
374
|
+
* chain this client tracks follows the daemon's; a record that does not continue
|
|
375
|
+
* it means someone else holding the session ID made a call.
|
|
376
|
+
*/
|
|
377
|
+
export class Session {
|
|
378
|
+
/** The SHA-256 of the session ID, as the session's records carry it. */
|
|
379
|
+
fingerprint;
|
|
380
|
+
/** The tier the daemon measured when the session opened. */
|
|
381
|
+
isolation;
|
|
382
|
+
sandbox;
|
|
383
|
+
expiresAtMs;
|
|
384
|
+
idleTimeoutMs;
|
|
385
|
+
// The session ID is a capability: it goes to the daemon and nowhere else.
|
|
386
|
+
#id;
|
|
387
|
+
#client;
|
|
388
|
+
#rule;
|
|
389
|
+
#calls = 0n;
|
|
390
|
+
#last = "";
|
|
391
|
+
#end;
|
|
392
|
+
#queue = Promise.resolve();
|
|
393
|
+
/** @internal */
|
|
394
|
+
constructor(client, m, rule) {
|
|
395
|
+
this.#client = client;
|
|
396
|
+
this.#id = m.sessionId ?? "";
|
|
397
|
+
this.#rule = rule;
|
|
398
|
+
this.fingerprint = m.session ?? "";
|
|
399
|
+
this.isolation = m.isolation ?? "";
|
|
400
|
+
this.sandbox = m.sandbox ?? "";
|
|
401
|
+
this.expiresAtMs = num(m.expiresUnixMs);
|
|
402
|
+
this.idleTimeoutMs = m.idleTimeoutMs ?? 0;
|
|
403
|
+
}
|
|
404
|
+
/** The session's end once a response reported it, else undefined. */
|
|
405
|
+
get ended() {
|
|
406
|
+
return this.#end;
|
|
407
|
+
}
|
|
408
|
+
/** The number of calls this client has seen executed, and the last record's digest. */
|
|
409
|
+
get chain() {
|
|
410
|
+
return { calls: this.#calls, lastRecordSha256: this.#last };
|
|
411
|
+
}
|
|
412
|
+
async runJavaScript(code, opts = {}) {
|
|
413
|
+
const run = await this.#call({ javascript: { code, grantProfile: this.#client.jsGrant || undefined } }, opts);
|
|
414
|
+
return finish(run.run, run.record, javascriptResult, "javascript", opts.minimumIsolation);
|
|
415
|
+
}
|
|
416
|
+
/** Runs a project in the session; its files persist for later calls. */
|
|
417
|
+
async runProject(req, opts = {}) {
|
|
418
|
+
const run = await this.#call(projectPayload(req, this.#client.projectGrant), opts);
|
|
419
|
+
return finish(run.run, run.record, projectResult, "project", opts.minimumIsolation);
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Runs code in the session's interpreter for req.language, which keeps what
|
|
423
|
+
* earlier cells defined unless the result says a fresh one started. req.files are
|
|
424
|
+
* written into the session's work directory, the interpreter's working directory,
|
|
425
|
+
* before the code runs. A cell carries no grant.
|
|
426
|
+
*/
|
|
427
|
+
async runCell(req, opts = {}) {
|
|
428
|
+
if (req.language !== "javascript" && req.language !== "python") {
|
|
429
|
+
throw new PlimsollError("invalid_argument", `plimsoll: unknown cell language ${JSON.stringify(req.language)}`, { notDispatched: "request" });
|
|
430
|
+
}
|
|
431
|
+
const files = (req.files ?? []).map((f) => ({ path: f.path, content: f.content }));
|
|
432
|
+
const run = await this.#call({ cell: { language: req.language, code: req.code, files } }, opts);
|
|
433
|
+
return finish(run.run, run.record, cellResult, "cell", opts.minimumIsolation);
|
|
434
|
+
}
|
|
435
|
+
#serial(f) {
|
|
436
|
+
const next = this.#queue.then(f, f);
|
|
437
|
+
this.#queue = next.catch(() => undefined);
|
|
438
|
+
return next;
|
|
439
|
+
}
|
|
440
|
+
#call(payload, opts) {
|
|
441
|
+
const rule = mergeRules(this.#rule, validateRule(opts.software));
|
|
442
|
+
return this.#serial(async () => {
|
|
443
|
+
const env = this.#client.envelope(opts, rule);
|
|
444
|
+
let m;
|
|
445
|
+
try {
|
|
446
|
+
m = await this.#client.call("SessionRun", { ...env, sessionId: this.#id, ...payload }, opts.signal);
|
|
447
|
+
}
|
|
448
|
+
catch (e) {
|
|
449
|
+
if (e instanceof PlimsollError && e.sessionEnded)
|
|
450
|
+
this.#end = e.sessionEnded;
|
|
451
|
+
throw e;
|
|
452
|
+
}
|
|
453
|
+
const run = m.run;
|
|
454
|
+
if (!run)
|
|
455
|
+
throw new PlimsollError("data_loss", "plimsoll: the session call's answer carries no run");
|
|
456
|
+
const end = sessionEndFromWire(m.ended);
|
|
457
|
+
if (end !== "open")
|
|
458
|
+
this.#end = { reason: end, detail: m.endDetail ?? "" };
|
|
459
|
+
const checked = checkRecord(requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: rule, payload: digestPayload(payload) }), env.protocol, rule, run);
|
|
460
|
+
if ("problem" in checked)
|
|
461
|
+
throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { result: run });
|
|
462
|
+
const r = checked.record;
|
|
463
|
+
if (r.session !== this.fingerprint || r.sequence !== this.#calls + 1n || r.previousSha256 !== this.#last) {
|
|
464
|
+
throw new PlimsollError("data_loss", `plimsoll: the session's chain is broken: call ${r.sequence} after "${r.previousSha256}", this client's last was call ${this.#calls}, "${this.#last}"`, { result: run });
|
|
465
|
+
}
|
|
466
|
+
this.#calls = r.sequence;
|
|
467
|
+
this.#last = r.sha256;
|
|
468
|
+
return { run, record: r };
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Ends the session (or collects one that ended by itself) and checks the
|
|
473
|
+
* daemon's count of executed calls against the chain this client saw.
|
|
474
|
+
*/
|
|
475
|
+
close(signal) {
|
|
476
|
+
return this.#serial(async () => {
|
|
477
|
+
const m = await this.#client.call("CloseSession", { protocol: PROTOCOL, sessionId: this.#id }, signal);
|
|
478
|
+
const sum = {
|
|
479
|
+
session: m.session ?? "",
|
|
480
|
+
calls: BigInt(m.calls ?? 0),
|
|
481
|
+
lastRecordSha256: m.lastRecordSha256 ?? "",
|
|
482
|
+
end: sessionEndFromWire(m.ended),
|
|
483
|
+
};
|
|
484
|
+
this.#end ??= { reason: sum.end, detail: "" };
|
|
485
|
+
if (sum.session !== this.fingerprint || sum.calls !== this.#calls || sum.lastRecordSha256 !== this.#last) {
|
|
486
|
+
throw new PlimsollError("data_loss", `plimsoll: the daemon counts ${sum.calls} calls ending "${sum.lastRecordSha256}", this client saw ${this.#calls} ending "${this.#last}"`, { result: sum });
|
|
487
|
+
}
|
|
488
|
+
return sum;
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
// Reads the answer under the call's signal itself, since a fetch implementation
|
|
493
|
+
// need not tie its body to the signal it was given.
|
|
494
|
+
async function readCapped(res, signal) {
|
|
495
|
+
if (!res.body)
|
|
496
|
+
return "";
|
|
497
|
+
const reader = res.body.getReader();
|
|
498
|
+
let onAbort = () => { };
|
|
499
|
+
const aborted = new Promise((_, reject) => {
|
|
500
|
+
onAbort = () => reject(signal.reason);
|
|
501
|
+
if (signal.aborted)
|
|
502
|
+
onAbort();
|
|
503
|
+
else
|
|
504
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
505
|
+
});
|
|
506
|
+
const chunks = [];
|
|
507
|
+
let n = 0;
|
|
508
|
+
try {
|
|
509
|
+
for (;;) {
|
|
510
|
+
const { done, value } = await Promise.race([reader.read(), aborted]);
|
|
511
|
+
if (done)
|
|
512
|
+
break;
|
|
513
|
+
n += value.length;
|
|
514
|
+
if (n > MAX_RESPONSE_BYTES) {
|
|
515
|
+
throw new PlimsollError("resource_exhausted", `plimsoll: the daemon's answer exceeds ${MAX_RESPONSE_BYTES} bytes`);
|
|
516
|
+
}
|
|
517
|
+
chunks.push(value);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
catch (e) {
|
|
521
|
+
void reader.cancel().catch(() => undefined);
|
|
522
|
+
throw e;
|
|
523
|
+
}
|
|
524
|
+
finally {
|
|
525
|
+
signal.removeEventListener("abort", onAbort);
|
|
526
|
+
}
|
|
527
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
528
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { WireError } from "./wire.ts";
|
|
2
|
+
/** Why a request was refused before any code ran (plimsoll.v1.NotDispatchedReason). */
|
|
3
|
+
export type Refusal = "request" | "permission" | "protocol" | "unsupported" | "isolation" | "capacity" | "environment" | "unknown";
|
|
4
|
+
/** Why a session ended (plimsoll.v1.SessionEnd), "open" while it has not. */
|
|
5
|
+
export type SessionEnd = "open" | "closed" | "expired" | "disk_exceeded" | "main_process_ended" | "boundary_failed" | "sandbox_changed" | "shutdown";
|
|
6
|
+
/**
|
|
7
|
+
* Connect's status codes, plus the two this client raises itself:
|
|
8
|
+
* "data_loss" for an answer that does not check (the run may have executed),
|
|
9
|
+
* and "invalid_argument" for a request refused before it was sent.
|
|
10
|
+
*/
|
|
11
|
+
export type Code = "canceled" | "unknown" | "invalid_argument" | "deadline_exceeded" | "not_found" | "already_exists" | "permission_denied" | "resource_exhausted" | "failed_precondition" | "aborted" | "out_of_range" | "unimplemented" | "internal" | "unavailable" | "data_loss" | "unauthenticated";
|
|
12
|
+
export declare class PlimsollError extends Error {
|
|
13
|
+
readonly code: Code;
|
|
14
|
+
/**
|
|
15
|
+
* Set when the daemon stated that nothing ran. Undefined means execution may
|
|
16
|
+
* have occurred, whatever the code.
|
|
17
|
+
*/
|
|
18
|
+
readonly notDispatched: Refusal | undefined;
|
|
19
|
+
/** Set when a session call was refused because its session had ended. */
|
|
20
|
+
readonly sessionEnded: {
|
|
21
|
+
reason: SessionEnd;
|
|
22
|
+
detail: string;
|
|
23
|
+
} | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* The result the daemon returned, on a "data_loss" error raised after it
|
|
26
|
+
* answered: the record or the isolation evidence did not check, the run may
|
|
27
|
+
* have executed, and this is what came back.
|
|
28
|
+
*/
|
|
29
|
+
readonly result: unknown;
|
|
30
|
+
constructor(code: Code, message: string, opts?: {
|
|
31
|
+
notDispatched?: Refusal;
|
|
32
|
+
sessionEnded?: {
|
|
33
|
+
reason: SessionEnd;
|
|
34
|
+
detail: string;
|
|
35
|
+
};
|
|
36
|
+
result?: unknown;
|
|
37
|
+
cause?: unknown;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export declare function sessionEndFromWire(v: string | number | undefined): SessionEnd;
|
|
41
|
+
/** The error a Connect error body describes, with its plimsoll details restored. */
|
|
42
|
+
export declare function errorFromWire(httpStatus: number, body: WireError | undefined): PlimsollError;
|