@capybara-hq/plugin-sdk 0.1.0-rc.6 → 0.1.0-rc.61
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 +1 -1
- package/agent-docs/agent-templates.md +14 -2
- package/agent-docs/concepts.md +14 -5
- package/agent-docs/connector-templates.md +7 -1
- package/agent-docs/extension-points/channel.md +1 -1
- package/agent-docs/extension-points/context.md +15 -0
- package/agent-docs/extension-points/device-provider.md +15 -0
- package/agent-docs/extension-points/file-preview.md +2 -0
- package/agent-docs/extension-points/model-provider.md +3 -1
- package/agent-docs/extension-points/object-store.md +2 -0
- package/agent-docs/extension-points/push-provider.md +17 -0
- package/agent-docs/extensions.md +29 -3
- package/agent-docs/plugin-format.md +52 -2
- package/agent-docs/setup.md +54 -0
- package/dist/agent-template.d.ts +15 -6
- package/dist/agent-template.js +32 -13
- package/dist/avatar-presets.d.ts +8 -0
- package/dist/avatar-presets.js +17 -0
- package/dist/bootstrap.d.ts +109 -1
- package/dist/bootstrap.js +185 -2
- package/dist/cards.d.ts +67 -13
- package/dist/cards.js +91 -21
- package/dist/channel.d.ts +148 -48
- package/dist/channel.js +10 -5
- package/dist/client-css.d.ts +36 -0
- package/dist/client-css.js +326 -0
- package/dist/client-section.d.ts +35 -0
- package/dist/client-section.js +133 -0
- package/dist/config-ui.d.ts +22 -0
- package/dist/config-ui.js +64 -4
- package/dist/connector-auth.d.ts +15 -2
- package/dist/connector-auth.js +97 -8
- package/dist/connector.d.ts +74 -32
- package/dist/context.d.ts +40 -0
- package/dist/context.js +2 -0
- package/dist/ctx.d.ts +132 -29
- package/dist/define-extension.d.ts +26 -12
- package/dist/define-extension.js +12 -5
- package/dist/device-denied-paths.d.ts +18 -0
- package/dist/device-denied-paths.js +84 -0
- package/dist/device-operation.d.ts +333 -0
- package/dist/device-operation.js +312 -0
- package/dist/device-protocol.d.ts +285 -50
- package/dist/device-protocol.js +755 -90
- package/dist/device-provider.d.ts +503 -0
- package/dist/device-provider.js +302 -0
- package/dist/dial-in.d.ts +176 -0
- package/dist/dial-in.js +115 -0
- package/dist/extension-point.d.ts +2 -0
- package/dist/extension-point.js +6 -2
- package/dist/file-preview.d.ts +23 -6
- package/dist/git-hosts.d.ts +53 -0
- package/dist/git-hosts.js +98 -0
- package/dist/hooks.d.ts +125 -20
- package/dist/hooks.js +5 -0
- package/dist/http-access.d.ts +62 -0
- package/dist/http-access.js +12 -0
- package/dist/identity.d.ts +38 -9
- package/dist/identity.js +21 -1
- package/dist/index.d.ts +29 -3
- package/dist/index.js +29 -3
- package/dist/marketplace.d.ts +26 -0
- package/dist/marketplace.js +43 -1
- package/dist/model-params.d.ts +41 -22
- package/dist/model-params.js +28 -15
- package/dist/model.d.ts +206 -71
- package/dist/model.js +152 -19
- package/dist/net.d.ts +52 -0
- package/dist/net.js +34 -0
- package/dist/network-classes.d.ts +98 -0
- package/dist/network-classes.js +291 -0
- package/dist/permissions.d.ts +54 -22
- package/dist/permissions.js +119 -43
- package/dist/plugin-manifest.d.ts +45 -5
- package/dist/plugin-manifest.js +174 -6
- package/dist/plugin-package.d.ts +82 -38
- package/dist/plugin-package.js +61 -29
- package/dist/push.d.ts +75 -0
- package/dist/push.js +87 -0
- package/dist/sandbox-linux-runtime-source.d.ts +1 -0
- package/dist/sandbox-linux-runtime-source.js +2318 -0
- package/dist/sandbox-native-runtime-source.d.ts +10 -0
- package/dist/sandbox-native-runtime-source.js +476 -0
- package/dist/sandbox-runtime-source.d.ts +19 -0
- package/dist/sandbox-runtime-source.js +28 -0
- package/dist/sandbox-write-denies.d.ts +139 -0
- package/dist/sandbox-write-denies.js +869 -0
- package/dist/secret.d.ts +4 -1
- package/dist/secret.js +4 -1
- package/dist/setup-check.d.ts +128 -0
- package/dist/setup-check.js +142 -0
- package/dist/setup-guide-parse.d.ts +121 -0
- package/dist/setup-guide-parse.js +356 -0
- package/dist/setup-guide-render.d.ts +45 -0
- package/dist/setup-guide-render.js +351 -0
- package/dist/setup-guide.d.ts +108 -0
- package/dist/setup-guide.js +367 -0
- package/dist/shell-capabilities.d.ts +211 -0
- package/dist/shell-capabilities.js +44 -0
- package/dist/shell-environment.d.ts +57 -0
- package/dist/shell-environment.js +21 -0
- package/dist/skill.d.ts +27 -17
- package/dist/skill.js +40 -26
- package/dist/storage.d.ts +52 -25
- package/dist/svg-viewbox.d.ts +10 -0
- package/dist/svg-viewbox.js +24 -0
- package/dist/theme-assets.d.ts +55 -0
- package/dist/theme-assets.js +489 -0
- package/dist/theme-readability.d.ts +37 -0
- package/dist/theme-readability.js +145 -0
- package/dist/theme-tokens.generated.d.ts +299 -0
- package/dist/theme-tokens.generated.js +184 -0
- package/dist/theme.d.ts +190 -0
- package/dist/theme.js +471 -0
- package/dist/tool.d.ts +99 -26
- package/dist/tool.js +29 -9
- package/dist/ui-parts.d.ts +23 -0
- package/dist/ui-parts.js +385 -0
- package/dist/ui-resolve.d.ts +35 -0
- package/dist/ui-resolve.js +42 -0
- package/dist/ui-slots.d.ts +65 -0
- package/dist/ui-slots.js +261 -0
- package/dist/ui.d.ts +212 -76
- package/dist/ui.js +101 -27
- package/dist/url.d.ts +4 -1
- package/dist/url.js +4 -1
- package/package.json +13 -1
- package/schemas/bootstrap-extra.v1.schema.json +186 -0
- package/schemas/bootstrap.v1.schema.json +20 -0
- package/schemas/connector-template.v1.schema.json +35 -0
- package/schemas/marketplace.v1.schema.json +14 -0
- package/schemas/plugin.v1.schema.json +122 -3
- package/schemas/theme.v1.schema.json +302 -0
- package/agent-docs/extension-points/sandbox.md +0 -15
- package/dist/sandbox.d.ts +0 -254
- package/dist/sandbox.js +0 -153
package/dist/device-protocol.js
CHANGED
|
@@ -1,21 +1,39 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* (a connected machine that serves as
|
|
2
|
+
* The device protocol: the WebSocket frames between the kernel and a `capybara-device` program
|
|
3
|
+
* (a connected machine that serves as a device). Pure types and hand-written guards.
|
|
4
|
+
*
|
|
5
|
+
* The bodies of the dial-in envelope are parsed by `parseDeviceFrame` (second half of this file);
|
|
6
|
+
* the per-operation argument and result guards of the first half are its value guards.
|
|
4
7
|
*/
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
];
|
|
18
|
-
/**
|
|
8
|
+
import { parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationRef, parseSandboxOperationScope, parseSandboxPreparationScope, } from "./device-operation.js";
|
|
9
|
+
import { isDeviceProjectName, MAX_DEVICE_LIST_ENTRIES, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_RESULTS, validateAllowHost, validateSandboxPathShape, } from "./device-provider.js";
|
|
10
|
+
/** The major version of {@link DEVICE_DIAL_IN_PROTOCOL}. */
|
|
11
|
+
export const DEVICE_PROTOCOL_VERSION = 6;
|
|
12
|
+
/**
|
|
13
|
+
* The dial-in protocol `capybara-device` speaks (`<name>/<major>`, see `DIAL_IN_PROTOCOL_RE`): the
|
|
14
|
+
* value of the `X-Capybara-Device-Protocol` header, of the hello envelope's `protocol` and of the
|
|
15
|
+
* sign-in's `protocol`. The provider serving its devices declares it as `permissions.dialIn`.
|
|
16
|
+
* The kernel checks only the envelope (`DialInMachineFrame`); the bodies the envelope carries are
|
|
17
|
+
* this module's ({@link parseDeviceFrame}).
|
|
18
|
+
*/
|
|
19
|
+
export const DEVICE_DIAL_IN_PROTOCOL = `capybara-device/${DEVICE_PROTOCOL_VERSION}`;
|
|
20
|
+
const DEVICE_FEATURES = ["networkReport", "projects"];
|
|
21
|
+
/** The most project directories a policy summary's `sharedProjectRoots` lists. */
|
|
22
|
+
export const MAX_DEVICE_SHARED_PROJECT_ROOTS = 256;
|
|
23
|
+
/** The most blocked hosts an exec result reports; the parser cuts longer lists. */
|
|
24
|
+
export const MAX_NETWORK_BLOCKED_HOSTS = 20;
|
|
25
|
+
/** The most hosts an exec's `grants` may carry. */
|
|
26
|
+
const MAX_POLICY_HOSTS = 100;
|
|
27
|
+
/**
|
|
28
|
+
* The identity of a host's OS boot or of a program run: 1 to 128 characters of letters, digits,
|
|
29
|
+
* `.`, `_`, `:` and `-`.
|
|
30
|
+
*/
|
|
31
|
+
export const DEVICE_BOOT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
32
|
+
/** Whether `v` is a well-formed boot or program-run identity ({@link DEVICE_BOOT_ID_RE}). */
|
|
33
|
+
export function isDeviceBootId(v) {
|
|
34
|
+
return typeof v === "string" && DEVICE_BOOT_ID_RE.test(v);
|
|
35
|
+
}
|
|
36
|
+
/** A frame that is not valid device protocol (or came from the wrong side). */
|
|
19
37
|
export class DeviceProtocolError extends Error {
|
|
20
38
|
constructor(message) {
|
|
21
39
|
super(message);
|
|
@@ -55,27 +73,42 @@ function bool(o, k) {
|
|
|
55
73
|
throw new DeviceProtocolError(`field "${k}" must be a boolean`);
|
|
56
74
|
return v;
|
|
57
75
|
}
|
|
58
|
-
function strArray(o, k) {
|
|
76
|
+
function strArray(o, k, label = k) {
|
|
59
77
|
const v = o[k];
|
|
60
78
|
if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) {
|
|
61
|
-
throw new DeviceProtocolError(`field "${
|
|
79
|
+
throw new DeviceProtocolError(`field "${label}" must be an array of strings`);
|
|
62
80
|
}
|
|
63
81
|
return v;
|
|
64
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* The exec `limits`: resources and the outer network (no mode: protocol 4 removed it). Unknown
|
|
85
|
+
* keys are refused, so a stale `mode` (or any field the device would ignore) is never accepted.
|
|
86
|
+
*/
|
|
65
87
|
function parseLimits(v) {
|
|
66
|
-
const o =
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
88
|
+
const o = strictRecord(v, ["cpu", "memoryMb", "diskMb", "network"], 'field "limits"');
|
|
89
|
+
const network = strictRecord(o.network, ["kind", "hosts"], 'field "network"');
|
|
90
|
+
const kind = oneOf(network, "kind", ["open-public", "allowlist"]);
|
|
91
|
+
const hosts = strArray(network, "hosts", "network.hosts");
|
|
92
|
+
for (const h of hosts) {
|
|
93
|
+
const problems = validateAllowHost(h);
|
|
94
|
+
if (problems.length > 0) {
|
|
95
|
+
throw new DeviceProtocolError(`invalid network host "${h}": ${problems.join("; ")}`);
|
|
96
|
+
}
|
|
70
97
|
}
|
|
71
98
|
return {
|
|
72
99
|
cpu: num(o, "cpu"),
|
|
73
100
|
memoryMb: num(o, "memoryMb"),
|
|
74
101
|
diskMb: num(o, "diskMb"),
|
|
75
|
-
|
|
76
|
-
allowHosts: strArray(o, "allowHosts"),
|
|
102
|
+
network: { kind, hosts },
|
|
77
103
|
};
|
|
78
104
|
}
|
|
105
|
+
function oneOf(o, k, values) {
|
|
106
|
+
const v = str(o, k);
|
|
107
|
+
if (!values.includes(v)) {
|
|
108
|
+
throw new DeviceProtocolError(`unknown ${k} "${v}"`);
|
|
109
|
+
}
|
|
110
|
+
return v;
|
|
111
|
+
}
|
|
79
112
|
function num(o, k) {
|
|
80
113
|
const v = o[k];
|
|
81
114
|
if (typeof v !== "number" || !Number.isFinite(v)) {
|
|
@@ -104,57 +137,143 @@ function parseRoots(v) {
|
|
|
104
137
|
}
|
|
105
138
|
return roots;
|
|
106
139
|
}
|
|
107
|
-
function
|
|
108
|
-
const
|
|
109
|
-
if (
|
|
110
|
-
throw new DeviceProtocolError(`
|
|
111
|
-
const mode = str(o, "mode");
|
|
112
|
-
if (mode !== "os" && mode !== "docker") {
|
|
113
|
-
throw new DeviceProtocolError(`unsupported mode "${mode}"`);
|
|
140
|
+
function hostArray(o, k) {
|
|
141
|
+
const v = strArray(o, k);
|
|
142
|
+
if (v.length > MAX_POLICY_HOSTS) {
|
|
143
|
+
throw new DeviceProtocolError(`field "${k}" must have at most ${MAX_POLICY_HOSTS} entries`);
|
|
114
144
|
}
|
|
115
|
-
|
|
116
|
-
|
|
145
|
+
return v;
|
|
146
|
+
}
|
|
147
|
+
/** A bounded array field of a result or summary, refused when it is longer than `max`. */
|
|
148
|
+
function boundedArray(v, label, max, what) {
|
|
149
|
+
if (!Array.isArray(v)) {
|
|
150
|
+
throw new DeviceProtocolError(`field "${label}" must be an array of ${what}`);
|
|
117
151
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
os,
|
|
123
|
-
arch: str(o, "arch"),
|
|
124
|
-
mode,
|
|
125
|
-
roots: parseRoots(o.roots),
|
|
126
|
-
sessionIsolation: o.sessionIsolation,
|
|
127
|
-
};
|
|
152
|
+
if (v.length > max) {
|
|
153
|
+
throw new DeviceProtocolError(`field "${label}" must have at most ${max} entries`);
|
|
154
|
+
}
|
|
155
|
+
return v;
|
|
128
156
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
if (
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
157
|
+
/** A project name field (see {@link isDeviceProjectName}), named by `what` in the message. */
|
|
158
|
+
function projectName(v, what) {
|
|
159
|
+
if (!isDeviceProjectName(v)) {
|
|
160
|
+
throw new DeviceProtocolError(`${what} must be a non-empty name of at most ${MAX_DEVICE_PROJECT_NAME_LENGTH} UTF-16 code units, not "." or "..", without "/", control characters or leading or trailing whitespace`);
|
|
161
|
+
}
|
|
162
|
+
return v;
|
|
163
|
+
}
|
|
164
|
+
/** An absolute path field ({@link validateSandboxPathShape}), named by `what` in the message. */
|
|
165
|
+
function absolutePath(v, what) {
|
|
166
|
+
if (typeof v !== "string")
|
|
167
|
+
throw new DeviceProtocolError(`${what} must be a string`);
|
|
168
|
+
const problems = validateSandboxPathShape(v);
|
|
169
|
+
if (problems.length > 0)
|
|
170
|
+
throw new DeviceProtocolError(`${what}: ${problems.join("; ")}`);
|
|
171
|
+
return v;
|
|
172
|
+
}
|
|
173
|
+
/** A `list` result: null, or at most {@link MAX_DEVICE_LIST_ENTRIES} named entries. */
|
|
174
|
+
function parseListResult(result) {
|
|
175
|
+
if (result === null)
|
|
176
|
+
return null;
|
|
177
|
+
const r = obj(result, "list result");
|
|
178
|
+
const entries = boundedArray(r.entries, "entries", MAX_DEVICE_LIST_ENTRIES, "entries").map((e, i) => {
|
|
179
|
+
const what = `field "entries[${i}]"`;
|
|
180
|
+
if (!isRecord(e))
|
|
181
|
+
throw new DeviceProtocolError(`${what} must be an object`);
|
|
182
|
+
const name = e.name;
|
|
183
|
+
if (typeof name !== "string" ||
|
|
184
|
+
name === "" ||
|
|
185
|
+
name === "." ||
|
|
186
|
+
name === ".." ||
|
|
187
|
+
name.includes("/")) {
|
|
188
|
+
throw new DeviceProtocolError(`${what}.name must be a non-empty string without "/", other than "." and ".."`);
|
|
189
|
+
}
|
|
190
|
+
return { name, isDir: bool(e, "isDir") };
|
|
191
|
+
});
|
|
192
|
+
return { entries, truncated: bool(r, "truncated") };
|
|
193
|
+
}
|
|
194
|
+
/** A `scan` result: at most {@link MAX_DEVICE_SCAN_RESULTS} candidates. */
|
|
195
|
+
function parseScanResult(v) {
|
|
196
|
+
const label = "scan result";
|
|
197
|
+
return boundedArray(v, label, MAX_DEVICE_SCAN_RESULTS, "candidates").map((e, i) => {
|
|
198
|
+
const what = `field "${label}[${i}]"`;
|
|
199
|
+
if (!isRecord(e))
|
|
200
|
+
throw new DeviceProtocolError(`${what} must be an object`);
|
|
201
|
+
return {
|
|
202
|
+
path: absolutePath(e.path, `${what}.path`),
|
|
203
|
+
suggestedName: projectName(e.suggestedName, `${what}.suggestedName`),
|
|
204
|
+
};
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
function parsePolicySummary(v) {
|
|
208
|
+
const o = obj(v, 'field "policy"');
|
|
209
|
+
const shared = sharedProjectRoots(o.sharedProjectRoots);
|
|
150
210
|
return {
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
op: op,
|
|
154
|
-
args,
|
|
155
|
-
deadlineMs: posInt(o, "deadlineMs"),
|
|
211
|
+
allowedDomains: strArray(o, "allowedDomains"),
|
|
212
|
+
...(shared !== undefined && { sharedProjectRoots: shared }),
|
|
156
213
|
};
|
|
157
214
|
}
|
|
215
|
+
/**
|
|
216
|
+
* A summary's `sharedProjectRoots`: at most {@link MAX_DEVICE_SHARED_PROJECT_ROOTS} absolute paths.
|
|
217
|
+
* Undefined when absent or malformed (an optional field: only it is dropped).
|
|
218
|
+
*/
|
|
219
|
+
function sharedProjectRoots(v) {
|
|
220
|
+
if (!Array.isArray(v) || v.length > MAX_DEVICE_SHARED_PROJECT_ROOTS)
|
|
221
|
+
return undefined;
|
|
222
|
+
if (!v.every((p) => typeof p === "string" && validateSandboxPathShape(p).length === 0))
|
|
223
|
+
return undefined;
|
|
224
|
+
return [...v];
|
|
225
|
+
}
|
|
226
|
+
/** Optional hello fields: malformed values are ignored so old and new peers interoperate. */
|
|
227
|
+
function optionalHelloFields(o) {
|
|
228
|
+
const out = {};
|
|
229
|
+
if (Array.isArray(o.features)) {
|
|
230
|
+
out.features = DEVICE_FEATURES.filter((f) => o.features.includes(f));
|
|
231
|
+
}
|
|
232
|
+
if (typeof o.home === "string" && validateSandboxPathShape(o.home).length === 0) {
|
|
233
|
+
out.home = o.home;
|
|
234
|
+
}
|
|
235
|
+
return { ...out, ...optionalPolicy(o.policy) };
|
|
236
|
+
}
|
|
237
|
+
/** A summary field that is dropped when absent or unreadable. */
|
|
238
|
+
function optionalPolicy(v) {
|
|
239
|
+
if (v === undefined)
|
|
240
|
+
return {};
|
|
241
|
+
try {
|
|
242
|
+
return { policy: parsePolicySummary(v) };
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
// an unreadable summary is the same as none: the kernel learns the policy later
|
|
246
|
+
return {};
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const BLOCK_LAYERS = ["device", "org", "address", "unknown"];
|
|
250
|
+
/**
|
|
251
|
+
* The valid entries of an exec result's `network.blocked`: a host that fails
|
|
252
|
+
* {@link validateAllowHost} is kept only with layer `address`; anything malformed is dropped;
|
|
253
|
+
* at most {@link MAX_NETWORK_BLOCKED_HOSTS}. Undefined when the field is not a report at all.
|
|
254
|
+
*/
|
|
255
|
+
function parseNetworkReport(v) {
|
|
256
|
+
if (!isRecord(v) || !Array.isArray(v.blocked))
|
|
257
|
+
return undefined;
|
|
258
|
+
const blocked = [];
|
|
259
|
+
for (const e of v.blocked) {
|
|
260
|
+
if (blocked.length >= MAX_NETWORK_BLOCKED_HOSTS)
|
|
261
|
+
break;
|
|
262
|
+
if (!isRecord(e))
|
|
263
|
+
continue;
|
|
264
|
+
const { host, port, layer } = e;
|
|
265
|
+
if (typeof host !== "string" || host === "" || host.length > 255)
|
|
266
|
+
continue;
|
|
267
|
+
if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)
|
|
268
|
+
continue;
|
|
269
|
+
if (!BLOCK_LAYERS.includes(layer))
|
|
270
|
+
continue;
|
|
271
|
+
if (layer !== "address" && validateAllowHost(host).length > 0)
|
|
272
|
+
continue;
|
|
273
|
+
blocked.push({ host, port, layer: layer });
|
|
274
|
+
}
|
|
275
|
+
return { blocked };
|
|
276
|
+
}
|
|
158
277
|
function validateArgs(op, a) {
|
|
159
278
|
switch (op) {
|
|
160
279
|
case "exec": {
|
|
@@ -165,7 +284,20 @@ function validateArgs(op, a) {
|
|
|
165
284
|
const actor = obj(a.actor, 'field "actor"');
|
|
166
285
|
str(actor, "accountId");
|
|
167
286
|
str(actor, "conversationId");
|
|
287
|
+
if (actor.runId !== undefined)
|
|
288
|
+
str(actor, "runId");
|
|
168
289
|
parseLimits(a.limits);
|
|
290
|
+
if (a.grants !== undefined) {
|
|
291
|
+
const g = obj(a.grants, 'field "grants"');
|
|
292
|
+
hostArray(g, "hosts");
|
|
293
|
+
const src = obj(g.source, 'field "grants.source"');
|
|
294
|
+
const kind = str(src, "kind");
|
|
295
|
+
if (kind !== "run" && kind !== "task") {
|
|
296
|
+
throw new DeviceProtocolError(`unknown grant source kind "${kind}"`);
|
|
297
|
+
}
|
|
298
|
+
nonEmptyStr(src, "id");
|
|
299
|
+
nonEmptyStr(src, "accountId");
|
|
300
|
+
}
|
|
169
301
|
if (a.cwd !== undefined)
|
|
170
302
|
str(a, "cwd");
|
|
171
303
|
if (a.env !== undefined) {
|
|
@@ -205,6 +337,17 @@ function validateArgs(op, a) {
|
|
|
205
337
|
}
|
|
206
338
|
return;
|
|
207
339
|
}
|
|
340
|
+
case "list": {
|
|
341
|
+
absolutePath(a.path, 'field "path"');
|
|
342
|
+
const limit = posInt(a, "limit");
|
|
343
|
+
if (limit > MAX_DEVICE_LIST_ENTRIES) {
|
|
344
|
+
throw new DeviceProtocolError(`field "limit" must be at most ${MAX_DEVICE_LIST_ENTRIES}`);
|
|
345
|
+
}
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
case "scan":
|
|
349
|
+
absolutePath(a.base, 'field "base"');
|
|
350
|
+
return;
|
|
208
351
|
}
|
|
209
352
|
}
|
|
210
353
|
export function parseOpResult(op, result) {
|
|
@@ -215,13 +358,18 @@ export function parseOpResult(op, result) {
|
|
|
215
358
|
if (exitCode !== null && (typeof exitCode !== "number" || !Number.isFinite(exitCode))) {
|
|
216
359
|
throw new DeviceProtocolError('field "exitCode" must be a number or null');
|
|
217
360
|
}
|
|
218
|
-
|
|
361
|
+
const out = {
|
|
219
362
|
exitCode: exitCode,
|
|
220
363
|
stdout: str(r, "stdout"),
|
|
221
364
|
stderr: str(r, "stderr"),
|
|
222
365
|
truncated: bool(r, "truncated"),
|
|
223
366
|
timedOut: bool(r, "timedOut"),
|
|
224
367
|
};
|
|
368
|
+
// an optional report: a malformed one is dropped, never failing the command's result
|
|
369
|
+
const network = parseNetworkReport(r.network);
|
|
370
|
+
if (network)
|
|
371
|
+
out.network = network;
|
|
372
|
+
return out;
|
|
225
373
|
}
|
|
226
374
|
case "readFile": {
|
|
227
375
|
if (result === null)
|
|
@@ -237,40 +385,557 @@ export function parseOpResult(op, result) {
|
|
|
237
385
|
}
|
|
238
386
|
case "create":
|
|
239
387
|
return { roots: parseRoots(obj(result, "create result").roots) };
|
|
388
|
+
case "list":
|
|
389
|
+
return parseListResult(result);
|
|
390
|
+
case "scan":
|
|
391
|
+
return parseScanResult(result);
|
|
240
392
|
default:
|
|
241
393
|
if (result !== null)
|
|
242
394
|
throw new DeviceProtocolError(`${op} result must be null`);
|
|
243
395
|
return null;
|
|
244
396
|
}
|
|
245
397
|
}
|
|
398
|
+
const object = (value) => {
|
|
399
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
400
|
+
throw new DeviceProtocolError("Expected an object");
|
|
401
|
+
return value;
|
|
402
|
+
};
|
|
403
|
+
function keys(value, allowed) {
|
|
404
|
+
for (const key of Object.keys(value))
|
|
405
|
+
if (!allowed.includes(key))
|
|
406
|
+
throw new DeviceProtocolError(`Unknown field ${key}`);
|
|
407
|
+
}
|
|
408
|
+
function string(value, max = 128) {
|
|
409
|
+
if (typeof value !== "string" || !value.length || value.length > max)
|
|
410
|
+
throw new DeviceProtocolError("Expected a bounded nonempty string");
|
|
411
|
+
return value;
|
|
412
|
+
}
|
|
413
|
+
function integer(value, min = 0, max = Number.MAX_SAFE_INTEGER) {
|
|
414
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)
|
|
415
|
+
throw new DeviceProtocolError("Expected a bounded integer");
|
|
416
|
+
return value;
|
|
417
|
+
}
|
|
418
|
+
function path(value) {
|
|
419
|
+
if (typeof value !== "string" || validateSandboxPathShape(value).length)
|
|
420
|
+
throw new DeviceProtocolError("Expected an absolute filesystem path");
|
|
421
|
+
}
|
|
422
|
+
function freeze(value) {
|
|
423
|
+
if (value !== null && typeof value === "object") {
|
|
424
|
+
for (const v of Object.values(value))
|
|
425
|
+
freeze(v);
|
|
426
|
+
Object.freeze(value);
|
|
427
|
+
}
|
|
428
|
+
return value;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* A strict copy of a wire object for the protocol shapes: a plain object of own data properties
|
|
432
|
+
* only (no accessor is ever invoked, so a value cannot change between check and use), each key in
|
|
433
|
+
* `allowed`. Nested values are copied by the caller's own checks.
|
|
434
|
+
*/
|
|
435
|
+
function strictRecord(value, allowed, what) {
|
|
436
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
437
|
+
throw new DeviceProtocolError(`Invalid ${what}: expected an object`);
|
|
438
|
+
const proto = Object.getPrototypeOf(value);
|
|
439
|
+
if (proto !== Object.prototype && proto !== null)
|
|
440
|
+
throw new DeviceProtocolError(`Invalid ${what}: expected a plain object`);
|
|
441
|
+
const out = Object.create(null);
|
|
442
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
443
|
+
if (typeof key !== "string" || !allowed.includes(key))
|
|
444
|
+
throw new DeviceProtocolError(`Invalid ${what}: unknown field ${String(key)}`);
|
|
445
|
+
const d = Object.getOwnPropertyDescriptor(value, key);
|
|
446
|
+
if (!d || !("value" in d))
|
|
447
|
+
throw new DeviceProtocolError(`Invalid ${what}: accessor fields are not allowed`);
|
|
448
|
+
if (d.value !== undefined)
|
|
449
|
+
out[key] = d.value;
|
|
450
|
+
}
|
|
451
|
+
return out;
|
|
452
|
+
}
|
|
453
|
+
function strictHosts(value, what) {
|
|
454
|
+
if (!Array.isArray(value))
|
|
455
|
+
throw new DeviceProtocolError(`Invalid ${what}: expected at most 100 hosts`);
|
|
456
|
+
// one read of the length: a proxy or a getter cannot grow the list between check and copy
|
|
457
|
+
const length = value.length;
|
|
458
|
+
if (length > 100)
|
|
459
|
+
throw new DeviceProtocolError(`Invalid ${what}: expected at most 100 hosts`);
|
|
460
|
+
const hosts = [];
|
|
461
|
+
for (let i = 0; i < length; i++) {
|
|
462
|
+
const d = Object.getOwnPropertyDescriptor(value, i);
|
|
463
|
+
const h = d && "value" in d ? d.value : undefined;
|
|
464
|
+
if (typeof h !== "string" || validateAllowHost(h).length)
|
|
465
|
+
throw new DeviceProtocolError(`Invalid ${what}: expected hostnames or *.domain patterns`);
|
|
466
|
+
hosts.push(h);
|
|
467
|
+
}
|
|
468
|
+
return hosts;
|
|
469
|
+
}
|
|
470
|
+
function strictBoolean(o, key, what) {
|
|
471
|
+
const v = o[key];
|
|
472
|
+
if (typeof v !== "boolean")
|
|
473
|
+
throw new DeviceProtocolError(`Invalid ${what}: ${key} must be a boolean`);
|
|
474
|
+
return v;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Strictly parses a runtime permission report, version 2 (the protocol 4 `permissionSupport`, also
|
|
478
|
+
* the shape a cloud provider reports), and returns a frozen copy; throws {@link DeviceProtocolError}.
|
|
479
|
+
* Restricted support is all four claims or `null`; per-operation hosts need the allowlist; an
|
|
480
|
+
* operation boundary without restricted support claims no sandbox network at all. An
|
|
481
|
+
* instance boundary is the whole instance: it claims no restricted per-operation scope, no
|
|
482
|
+
* outside-sandbox escalation and no per-operation hosts (a host joins the device's list instead).
|
|
483
|
+
*/
|
|
484
|
+
export function parseSandboxPermissionSupport(value) {
|
|
485
|
+
const what = "runtime permission report";
|
|
486
|
+
const o = strictRecord(value, [
|
|
487
|
+
"version",
|
|
488
|
+
"boundary",
|
|
489
|
+
"restricted",
|
|
490
|
+
"network",
|
|
491
|
+
"outsideSandbox",
|
|
492
|
+
"background",
|
|
493
|
+
"unavailableReason",
|
|
494
|
+
"limitedBy",
|
|
495
|
+
], what);
|
|
496
|
+
if (o.version !== 2)
|
|
497
|
+
throw new DeviceProtocolError(`Invalid ${what}: expected version 2`);
|
|
498
|
+
if (o.boundary !== "operation" && o.boundary !== "instance")
|
|
499
|
+
throw new DeviceProtocolError(`Invalid ${what}: boundary must be operation or instance`);
|
|
500
|
+
let restricted = null;
|
|
501
|
+
if (o.restricted !== null) {
|
|
502
|
+
const claims = ["filesystem", "network", "native", "concurrentScopes"];
|
|
503
|
+
const r = strictRecord(o.restricted, claims, `${what} restricted claims`);
|
|
504
|
+
if (claims.some((k) => r[k] !== true))
|
|
505
|
+
throw new DeviceProtocolError(`Invalid ${what}: restricted support needs all four claims`);
|
|
506
|
+
restricted = { filesystem: true, network: true, native: true, concurrentScopes: true };
|
|
507
|
+
}
|
|
508
|
+
const n = strictRecord(o.network, ["openPublic", "allowlist", "perOperationHosts"], `${what} network`);
|
|
509
|
+
const network = {
|
|
510
|
+
openPublic: strictBoolean(n, "openPublic", what),
|
|
511
|
+
allowlist: strictBoolean(n, "allowlist", what),
|
|
512
|
+
perOperationHosts: strictBoolean(n, "perOperationHosts", what),
|
|
513
|
+
};
|
|
514
|
+
if (o.boundary === "operation" &&
|
|
515
|
+
restricted === null &&
|
|
516
|
+
(network.openPublic || network.allowlist || network.perOperationHosts))
|
|
517
|
+
throw new DeviceProtocolError(`Invalid ${what}: without restricted support an operation boundary has no sandbox network`);
|
|
518
|
+
if (network.perOperationHosts && !network.allowlist)
|
|
519
|
+
throw new DeviceProtocolError(`Invalid ${what}: per-operation hosts need the allowlist`);
|
|
520
|
+
const outsideSandbox = strictBoolean(o, "outsideSandbox", what);
|
|
521
|
+
const background = strictBoolean(o, "background", what);
|
|
522
|
+
if (o.boundary === "instance" &&
|
|
523
|
+
(restricted !== null || outsideSandbox || network.perOperationHosts))
|
|
524
|
+
throw new DeviceProtocolError(`Invalid ${what}: an instance boundary claims no restricted scope, outside escalation or per-operation hosts`);
|
|
525
|
+
if (o.unavailableReason !== undefined)
|
|
526
|
+
string(o.unavailableReason, 4096);
|
|
527
|
+
let limitedBy;
|
|
528
|
+
if (o.limitedBy !== undefined) {
|
|
529
|
+
const l = strictRecord(o.limitedBy, ["outsideSandbox", "openPublic"], `${what} limitedBy`);
|
|
530
|
+
limitedBy = {};
|
|
531
|
+
for (const [key, open] of [
|
|
532
|
+
["outsideSandbox", outsideSandbox],
|
|
533
|
+
["openPublic", network.openPublic],
|
|
534
|
+
]) {
|
|
535
|
+
if (l[key] === undefined)
|
|
536
|
+
continue;
|
|
537
|
+
if (l[key] !== "owner")
|
|
538
|
+
throw new DeviceProtocolError(`Invalid ${what}: limitedBy.${key} must be owner`);
|
|
539
|
+
if (open)
|
|
540
|
+
throw new DeviceProtocolError(`Invalid ${what}: limitedBy.${key} names who keeps a closed crossing closed, but it is open`);
|
|
541
|
+
limitedBy[key] = "owner";
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
return freeze({
|
|
545
|
+
version: 2,
|
|
546
|
+
boundary: o.boundary,
|
|
547
|
+
restricted,
|
|
548
|
+
network,
|
|
549
|
+
outsideSandbox,
|
|
550
|
+
background,
|
|
551
|
+
...(o.unavailableReason !== undefined
|
|
552
|
+
? { unavailableReason: o.unavailableReason }
|
|
553
|
+
: {}),
|
|
554
|
+
...(limitedBy !== undefined && Object.keys(limitedBy).length > 0 ? { limitedBy } : {}),
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Strictly parses one authenticated owner-ceiling report of protocol 6 and returns a frozen copy;
|
|
559
|
+
* throws {@link DeviceProtocolError}. Unknown fields (the protocol 3 `fullAccess` and
|
|
560
|
+
* `restrictedAllowedDomains` among them) are refused.
|
|
561
|
+
*/
|
|
562
|
+
export function parseOwnerCeilingReport(value) {
|
|
563
|
+
const what = "owner ceiling report";
|
|
564
|
+
const o = strictRecord(value, [
|
|
565
|
+
"version",
|
|
566
|
+
"sequence",
|
|
567
|
+
"revision",
|
|
568
|
+
"outsideSandbox",
|
|
569
|
+
"network",
|
|
570
|
+
"allowedDomains",
|
|
571
|
+
"projectReach",
|
|
572
|
+
], what);
|
|
573
|
+
if (o.version !== 3)
|
|
574
|
+
throw new DeviceProtocolError(`Invalid ${what}: expected version 3`);
|
|
575
|
+
if (o.network !== "open" && o.network !== "allowlist")
|
|
576
|
+
throw new DeviceProtocolError(`Invalid ${what}: network must be open or allowlist`);
|
|
577
|
+
if (o.projectReach !== "machine" && o.projectReach !== "paths" && o.projectReach !== "workspace")
|
|
578
|
+
throw new DeviceProtocolError(`Invalid ${what}: project reach must be machine, paths or workspace`);
|
|
579
|
+
return freeze({
|
|
580
|
+
version: 3,
|
|
581
|
+
sequence: integer(o.sequence),
|
|
582
|
+
revision: string(o.revision, 512),
|
|
583
|
+
outsideSandbox: strictBoolean(o, "outsideSandbox", what),
|
|
584
|
+
network: o.network,
|
|
585
|
+
allowedDomains: strictHosts(o.allowedDomains, `${what} allowedDomains`),
|
|
586
|
+
projectReach: o.projectReach,
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
const GENERATION = /^[0-9]{1,16}$/;
|
|
590
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
591
|
+
function generation(value) {
|
|
592
|
+
if (typeof value !== "string" || !GENERATION.test(value))
|
|
593
|
+
throw new DeviceProtocolError("Expected an instance generation");
|
|
594
|
+
return value;
|
|
595
|
+
}
|
|
596
|
+
function bindRequest(a) {
|
|
597
|
+
string(a.instanceId);
|
|
598
|
+
generation(a.instanceGeneration);
|
|
599
|
+
if (typeof a.bindingId !== "string" || !UUID.test(a.bindingId))
|
|
600
|
+
throw new DeviceProtocolError("Expected a binding id");
|
|
601
|
+
if (a.expectedPreviousGeneration !== null) {
|
|
602
|
+
generation(a.expectedPreviousGeneration);
|
|
603
|
+
if (BigInt(a.expectedPreviousGeneration) >= BigInt(a.instanceGeneration))
|
|
604
|
+
throw new DeviceProtocolError("Previous generation must precede the bound generation");
|
|
605
|
+
}
|
|
606
|
+
return a;
|
|
607
|
+
}
|
|
608
|
+
function identity(value) {
|
|
609
|
+
const o = object(value);
|
|
610
|
+
keys(o, ["runtimeHash", "helperHash", "imageFingerprint", "instanceGeneration"]);
|
|
611
|
+
for (const key of ["runtimeHash", "helperHash", "imageFingerprint"])
|
|
612
|
+
if (typeof o[key] !== "string" || !/^[a-f0-9]{64}$/.test(o[key]))
|
|
613
|
+
throw new DeviceProtocolError("Incomplete runtime identity");
|
|
614
|
+
string(o.instanceGeneration);
|
|
615
|
+
return o;
|
|
616
|
+
}
|
|
617
|
+
const natives = ["exec", "readFile", "writeFile", "stat", "list", "scan"];
|
|
618
|
+
/** The machine lifecycle operations, checked by the protocol 2 argument guards. */
|
|
619
|
+
const lifecycle = ["create", "stop"];
|
|
620
|
+
function requestBody(value) {
|
|
621
|
+
const o = object(value);
|
|
622
|
+
keys(o, ["op", "args"]);
|
|
623
|
+
const op = string(o.op), a = object(o.args);
|
|
624
|
+
if (lifecycle.includes(op)) {
|
|
625
|
+
validateArgs(op, a);
|
|
626
|
+
return freeze({ op: op, args: a });
|
|
627
|
+
}
|
|
628
|
+
if (op === "bindInstance") {
|
|
629
|
+
keys(a, ["instanceId", "instanceGeneration", "bindingId", "expectedPreviousGeneration"]);
|
|
630
|
+
bindRequest(a);
|
|
631
|
+
}
|
|
632
|
+
else if (op === "revokeOperation") {
|
|
633
|
+
keys(a, ["ref"]);
|
|
634
|
+
a.ref = parseSandboxOperationRef(a.ref);
|
|
635
|
+
}
|
|
636
|
+
else if (["backgroundStatus", "backgroundTail", "backgroundReadOutput", "backgroundStop"].includes(op)) {
|
|
637
|
+
keys(a, [
|
|
638
|
+
"ref",
|
|
639
|
+
...(op === "backgroundReadOutput" ? ["offset", "maxBytes"] : []),
|
|
640
|
+
...(op === "backgroundTail" ? ["maxBytes"] : op === "backgroundStop" ? ["graceMs"] : []),
|
|
641
|
+
]);
|
|
642
|
+
a.ref = parseSandboxExecutionRef(a.ref);
|
|
643
|
+
if (op === "backgroundTail" || op === "backgroundReadOutput")
|
|
644
|
+
integer(a.maxBytes, 0, 65536);
|
|
645
|
+
if (op === "backgroundReadOutput")
|
|
646
|
+
integer(a.offset);
|
|
647
|
+
if (op === "backgroundStop")
|
|
648
|
+
integer(a.graceMs, 0, 60000);
|
|
649
|
+
}
|
|
650
|
+
else {
|
|
651
|
+
const preparation = op.startsWith("prepare"), browsing = op.startsWith("browse"), background = op === "backgroundStart";
|
|
652
|
+
const method = background ? "exec" : preparation ? op.slice(7) : browsing ? op.slice(6) : op;
|
|
653
|
+
const native = method[0]?.toLowerCase() + method.slice(1);
|
|
654
|
+
if (!natives.includes(native) ||
|
|
655
|
+
(preparation && !["readFile", "writeFile", "stat"].includes(native)) ||
|
|
656
|
+
(browsing && !["stat", "list", "scan"].includes(native)))
|
|
657
|
+
throw new DeviceProtocolError("Unknown operation");
|
|
658
|
+
a.scope = preparation
|
|
659
|
+
? parseSandboxPreparationScope(a.scope)
|
|
660
|
+
: browsing
|
|
661
|
+
? parseSandboxBrowseScope(a.scope)
|
|
662
|
+
: parseSandboxOperationScope(a.scope);
|
|
663
|
+
const fields = native === "exec"
|
|
664
|
+
? ["command", "cwd", "env", "timeoutMs", "maxOutputBytes", "limits", "grants"]
|
|
665
|
+
: native === "readFile"
|
|
666
|
+
? ["path", "maxBytes"]
|
|
667
|
+
: native === "writeFile"
|
|
668
|
+
? ["path", "dataB64"]
|
|
669
|
+
: native === "stat"
|
|
670
|
+
? ["path"]
|
|
671
|
+
: native === "list"
|
|
672
|
+
? ["path", "limit"]
|
|
673
|
+
: ["base"];
|
|
674
|
+
keys(a, ["scope", ...fields, ...(background ? ["taskId", "outputPath", "retainUntilMs"] : [])]);
|
|
675
|
+
if (native !== "exec")
|
|
676
|
+
path(a[native === "scan" ? "base" : "path"]);
|
|
677
|
+
const validated = { ...a };
|
|
678
|
+
delete validated.scope;
|
|
679
|
+
if (native === "exec") {
|
|
680
|
+
const scope = parseSandboxOperationScope(a.scope);
|
|
681
|
+
validated.tag = scope.tag;
|
|
682
|
+
validated.actor = scope.actor;
|
|
683
|
+
if (background) {
|
|
684
|
+
string(a.taskId);
|
|
685
|
+
path(a.outputPath);
|
|
686
|
+
integer(a.retainUntilMs, scope.admitBeforeMs);
|
|
687
|
+
delete validated.taskId;
|
|
688
|
+
delete validated.outputPath;
|
|
689
|
+
delete validated.retainUntilMs;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
// Reuse the legacy pure value guards on the native fields.
|
|
693
|
+
validateArgs(native, validated);
|
|
694
|
+
if (native === "writeFile" && (typeof a.dataB64 !== "string" || !isBase64(a.dataB64)))
|
|
695
|
+
throw new DeviceProtocolError("Invalid base64 payload");
|
|
696
|
+
}
|
|
697
|
+
return freeze({ op: op, args: a });
|
|
698
|
+
}
|
|
246
699
|
/**
|
|
247
|
-
*
|
|
248
|
-
*
|
|
249
|
-
*
|
|
700
|
+
* Padded standard base64: whole quartets of `A-Z a-z 0-9 + /`, the last one possibly ending in
|
|
701
|
+
* `=` or `==`. One linear pass: a regex with a repeated group exhausts the engine's backtracking
|
|
702
|
+
* stack on payloads of a few megabytes.
|
|
250
703
|
*/
|
|
251
|
-
|
|
252
|
-
|
|
704
|
+
function isBase64(value) {
|
|
705
|
+
if (value.length % 4 !== 0)
|
|
706
|
+
return false;
|
|
707
|
+
const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
|
|
708
|
+
for (let i = 0; i < value.length - padding; i++) {
|
|
709
|
+
const c = value.charCodeAt(i);
|
|
710
|
+
if (!((c >= 65 && c <= 90) ||
|
|
711
|
+
(c >= 97 && c <= 122) ||
|
|
712
|
+
(c >= 48 && c <= 57) ||
|
|
713
|
+
c === 43 ||
|
|
714
|
+
c === 47))
|
|
715
|
+
return false;
|
|
716
|
+
}
|
|
717
|
+
return true;
|
|
718
|
+
}
|
|
719
|
+
const RESPONSE_KINDS = [
|
|
720
|
+
"gone",
|
|
721
|
+
"fs_gone",
|
|
722
|
+
"policy",
|
|
723
|
+
"error",
|
|
724
|
+
"denied",
|
|
725
|
+
"unsupported",
|
|
726
|
+
"unsettled",
|
|
727
|
+
"unknown",
|
|
728
|
+
"invalid",
|
|
729
|
+
"project_refused",
|
|
730
|
+
];
|
|
731
|
+
const PROJECT_REFUSALS = ["other-connection", "outside-reach", "denied"];
|
|
732
|
+
function helloBody(value) {
|
|
733
|
+
const o = object(value);
|
|
734
|
+
keys(o, [
|
|
735
|
+
"mode",
|
|
736
|
+
"roots",
|
|
737
|
+
"sessionIsolation",
|
|
738
|
+
"features",
|
|
739
|
+
"policy",
|
|
740
|
+
"home",
|
|
741
|
+
"permissionSupport",
|
|
742
|
+
"ownerCeiling",
|
|
743
|
+
"instanceGeneration",
|
|
744
|
+
"runtimeIdentity",
|
|
745
|
+
]);
|
|
746
|
+
const mode = o.mode;
|
|
747
|
+
if (mode !== "os" && mode !== "docker")
|
|
748
|
+
throw new DeviceProtocolError("Unsupported mode");
|
|
749
|
+
if (typeof o.sessionIsolation !== "boolean")
|
|
750
|
+
throw new DeviceProtocolError('field "sessionIsolation" must be a boolean');
|
|
751
|
+
const permissionSupport = parseSandboxPermissionSupport(o.permissionSupport);
|
|
752
|
+
if (o.instanceGeneration === null &&
|
|
753
|
+
(o.runtimeIdentity !== undefined ||
|
|
754
|
+
permissionSupport.restricted !== null ||
|
|
755
|
+
permissionSupport.outsideSandbox ||
|
|
756
|
+
permissionSupport.network.openPublic ||
|
|
757
|
+
permissionSupport.network.allowlist ||
|
|
758
|
+
permissionSupport.network.perOperationHosts ||
|
|
759
|
+
permissionSupport.background ||
|
|
760
|
+
!permissionSupport.unavailableReason))
|
|
761
|
+
throw new DeviceProtocolError("Unbound hello cannot advertise runtime capability");
|
|
762
|
+
let runtimeIdentity;
|
|
763
|
+
if (o.runtimeIdentity !== undefined) {
|
|
764
|
+
runtimeIdentity = identity(o.runtimeIdentity);
|
|
765
|
+
if (runtimeIdentity.instanceGeneration !== string(o.instanceGeneration))
|
|
766
|
+
throw new DeviceProtocolError("Runtime identity generation mismatch");
|
|
767
|
+
}
|
|
768
|
+
const optional = optionalHelloFields({ features: o.features, policy: o.policy, home: o.home });
|
|
769
|
+
return freeze({
|
|
770
|
+
mode,
|
|
771
|
+
roots: parseRoots(o.roots),
|
|
772
|
+
sessionIsolation: o.sessionIsolation,
|
|
773
|
+
...(optional.features && { features: optional.features }),
|
|
774
|
+
...(optional.policy && { policy: optional.policy }),
|
|
775
|
+
...(optional.home !== undefined && { home: optional.home }),
|
|
776
|
+
permissionSupport,
|
|
777
|
+
ownerCeiling: parseOwnerCeilingReport(o.ownerCeiling),
|
|
778
|
+
instanceGeneration: o.instanceGeneration === null ? null : string(o.instanceGeneration),
|
|
779
|
+
...(runtimeIdentity && { runtimeIdentity }),
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
function responseBody(value) {
|
|
783
|
+
const o = object(value);
|
|
784
|
+
if (o.ok === true) {
|
|
785
|
+
keys(o, ["ok", "result"]);
|
|
786
|
+
return freeze({ ok: true, result: o.result });
|
|
787
|
+
}
|
|
788
|
+
if (o.ok !== false)
|
|
789
|
+
throw new DeviceProtocolError('field "ok" must be a boolean');
|
|
790
|
+
keys(o, ["ok", "error"]);
|
|
791
|
+
const e = object(o.error);
|
|
792
|
+
keys(e, e.kind === "project_refused" ? ["kind", "message", "refusal"] : ["kind", "message"]);
|
|
793
|
+
if (!RESPONSE_KINDS.includes(String(e.kind)))
|
|
794
|
+
throw new DeviceProtocolError("Unknown outcome kind");
|
|
795
|
+
let refusal;
|
|
796
|
+
if (e.kind === "project_refused") {
|
|
797
|
+
if (!PROJECT_REFUSALS.includes(String(e.refusal)))
|
|
798
|
+
throw new DeviceProtocolError("A project_refused outcome needs a known refusal");
|
|
799
|
+
refusal = e.refusal;
|
|
800
|
+
}
|
|
801
|
+
return freeze({
|
|
802
|
+
ok: false,
|
|
803
|
+
error: {
|
|
804
|
+
kind: e.kind,
|
|
805
|
+
message: string(e.message, 8192),
|
|
806
|
+
...(refusal && { refusal }),
|
|
807
|
+
},
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
function eventBody(value) {
|
|
811
|
+
const o = object(value);
|
|
812
|
+
if (o.type !== "policy")
|
|
813
|
+
throw new DeviceProtocolError("Unknown event type");
|
|
814
|
+
keys(o, ["type", "policy", "ownerCeiling"]);
|
|
815
|
+
return freeze({
|
|
816
|
+
type: "policy",
|
|
817
|
+
...optionalPolicy(o.policy),
|
|
818
|
+
ownerCeiling: parseOwnerCeilingReport(o.ownerCeiling),
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
export function parseDeviceFrame(body, kind) {
|
|
822
|
+
// a JSON snapshot: plain data only (no accessor runs twice, no prototype), never aliasing the
|
|
823
|
+
// caller's objects, which the parsed copy freezes
|
|
824
|
+
let copy;
|
|
253
825
|
try {
|
|
254
|
-
|
|
826
|
+
copy = JSON.parse(JSON.stringify(body));
|
|
255
827
|
}
|
|
256
828
|
catch {
|
|
257
|
-
throw new DeviceProtocolError("
|
|
829
|
+
throw new DeviceProtocolError("Body is not JSON data");
|
|
258
830
|
}
|
|
259
|
-
|
|
260
|
-
throw new DeviceProtocolError("frame must be a JSON object");
|
|
261
|
-
const type = o.type;
|
|
262
|
-
switch (type) {
|
|
831
|
+
switch (kind) {
|
|
263
832
|
case "hello":
|
|
264
|
-
|
|
265
|
-
if (from !== "device")
|
|
266
|
-
throw new DeviceProtocolError(`"${type}" must come from the device`);
|
|
267
|
-
return type === "hello" ? parseHello(o) : parseRes(o);
|
|
833
|
+
return helloBody(copy);
|
|
268
834
|
case "req":
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
835
|
+
return requestBody(copy);
|
|
836
|
+
case "res":
|
|
837
|
+
return responseBody(copy);
|
|
838
|
+
case "event":
|
|
839
|
+
return eventBody(copy);
|
|
273
840
|
default:
|
|
274
|
-
throw new DeviceProtocolError(`
|
|
841
|
+
throw new DeviceProtocolError(`Unknown body kind ${String(kind)}`);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
export function parseOperationResult(op, result, request) {
|
|
845
|
+
if (op === "bindInstance") {
|
|
846
|
+
if (!request || !("bindingId" in request))
|
|
847
|
+
throw new DeviceProtocolError("Binding validation requires the exact request");
|
|
848
|
+
const o = object(result);
|
|
849
|
+
keys(o, [
|
|
850
|
+
"instanceId",
|
|
851
|
+
"instanceGeneration",
|
|
852
|
+
"bindingId",
|
|
853
|
+
"runtimeIdentity",
|
|
854
|
+
"permissionSupport",
|
|
855
|
+
"ownerCeiling",
|
|
856
|
+
]);
|
|
857
|
+
const runtimeIdentity = identity(o.runtimeIdentity);
|
|
858
|
+
if (o.instanceId !== request.instanceId ||
|
|
859
|
+
o.instanceGeneration !== request.instanceGeneration ||
|
|
860
|
+
o.bindingId !== request.bindingId ||
|
|
861
|
+
runtimeIdentity.instanceGeneration !== request.instanceGeneration)
|
|
862
|
+
throw new DeviceProtocolError("Binding answer belongs to another instance generation");
|
|
863
|
+
return freeze({
|
|
864
|
+
instanceId: request.instanceId,
|
|
865
|
+
instanceGeneration: request.instanceGeneration,
|
|
866
|
+
bindingId: request.bindingId,
|
|
867
|
+
runtimeIdentity,
|
|
868
|
+
permissionSupport: parseSandboxPermissionSupport(o.permissionSupport),
|
|
869
|
+
ownerCeiling: parseOwnerCeilingReport(o.ownerCeiling),
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
if (op === "backgroundReadOutput") {
|
|
873
|
+
if (!request || !("offset" in request))
|
|
874
|
+
throw new DeviceProtocolError("Output validation requires the exact request bounds");
|
|
875
|
+
const offset = integer(request.offset), maxBytes = integer(request.maxBytes, 0, 65536);
|
|
876
|
+
const o = object(result);
|
|
877
|
+
if ("unavailable" in o) {
|
|
878
|
+
keys(o, ["unavailable"]);
|
|
879
|
+
if (o.unavailable !== "lost" && o.unavailable !== "expired")
|
|
880
|
+
throw new DeviceProtocolError("Invalid output outcome");
|
|
881
|
+
return freeze(o);
|
|
882
|
+
}
|
|
883
|
+
keys(o, ["dataB64", "offset", "nextOffset", "totalBytes"]);
|
|
884
|
+
const total = integer(o.totalBytes), next = integer(o.nextOffset);
|
|
885
|
+
if (integer(o.offset) !== offset ||
|
|
886
|
+
typeof o.dataB64 !== "string" ||
|
|
887
|
+
o.dataB64.length > 87384 ||
|
|
888
|
+
!isBase64(o.dataB64))
|
|
889
|
+
throw new DeviceProtocolError("Invalid output range or base64");
|
|
890
|
+
const decoded = atob(o.dataB64);
|
|
891
|
+
if (btoa(decoded) !== o.dataB64 ||
|
|
892
|
+
decoded.length !== Math.min(maxBytes, Math.max(total - offset, 0)) ||
|
|
893
|
+
!Number.isSafeInteger(offset + decoded.length) ||
|
|
894
|
+
next !== offset + decoded.length)
|
|
895
|
+
throw new DeviceProtocolError("Inconsistent output range; retry from the same offset");
|
|
896
|
+
return freeze(o);
|
|
897
|
+
}
|
|
898
|
+
if (op === "backgroundStart")
|
|
899
|
+
return parseSandboxExecutionRef(result);
|
|
900
|
+
if (op === "backgroundStatus") {
|
|
901
|
+
const o = object(result);
|
|
902
|
+
keys(o, ["state", "exitCode", "timedOut"]);
|
|
903
|
+
if (o.state === "running" || o.state === "lost")
|
|
904
|
+
return freeze({ state: o.state });
|
|
905
|
+
if (o.state !== "exited" ||
|
|
906
|
+
(o.exitCode !== null && !Number.isInteger(o.exitCode)) ||
|
|
907
|
+
typeof o.timedOut !== "boolean")
|
|
908
|
+
throw new DeviceProtocolError("Invalid execution status");
|
|
909
|
+
return freeze(o);
|
|
910
|
+
}
|
|
911
|
+
if (op === "backgroundTail") {
|
|
912
|
+
if (result && typeof result === "object" && "unavailable" in result) {
|
|
913
|
+
const o = object(result);
|
|
914
|
+
keys(o, ["unavailable"]);
|
|
915
|
+
if (o.unavailable !== "lost" && o.unavailable !== "expired")
|
|
916
|
+
throw new DeviceProtocolError("Invalid output outcome");
|
|
917
|
+
return freeze(o);
|
|
918
|
+
}
|
|
919
|
+
return parseOpResult("readFile", result);
|
|
920
|
+
}
|
|
921
|
+
if (op === "backgroundStop") {
|
|
922
|
+
const o = object(result);
|
|
923
|
+
keys(o, ["outcome", "exitCode", "timedOut"]);
|
|
924
|
+
if (!["already-exited", "stopped", "cancel-pending", "lost"].includes(String(o.outcome)))
|
|
925
|
+
throw new DeviceProtocolError("Invalid stop outcome");
|
|
926
|
+
if (o.outcome === "already-exited" &&
|
|
927
|
+
((o.exitCode !== null && !Number.isInteger(o.exitCode)) || typeof o.timedOut !== "boolean"))
|
|
928
|
+
throw new DeviceProtocolError("Invalid stopped execution status");
|
|
929
|
+
return freeze(o);
|
|
930
|
+
}
|
|
931
|
+
if (op === "revokeOperation") {
|
|
932
|
+
if (result !== null)
|
|
933
|
+
throw new DeviceProtocolError("Revoke result must be null");
|
|
934
|
+
return null;
|
|
275
935
|
}
|
|
936
|
+
const raw = op.startsWith("prepare") ? op.slice(7) : op.startsWith("browse") ? op.slice(6) : op;
|
|
937
|
+
const native = raw.charAt(0).toLowerCase() + raw.slice(1);
|
|
938
|
+
if (!natives.includes(native) && !lifecycle.includes(native))
|
|
939
|
+
throw new DeviceProtocolError(`Unknown operation ${op}`);
|
|
940
|
+
return parseOpResult(native, result);
|
|
276
941
|
}
|