@capybara-hq/plugin-sdk 0.1.0-rc.35 → 0.1.0-rc.36
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/dist/device-denied-paths.d.ts +14 -0
- package/dist/device-denied-paths.js +41 -0
- package/dist/device-protocol.d.ts +140 -20
- package/dist/device-protocol.js +419 -14
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -3
- package/dist/sandbox-operation.d.ts +4 -0
- package/package.json +1 -1
- package/dist/device-protocol-v3.d.ts +0 -117
- package/dist/device-protocol-v3.js +0 -409
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paths a local device never opens to restricted work (Request approval, Approve for me), relative
|
|
3
|
+
* to `~` (spec §13.6, extended by ruling R19): SSH keys, cloud CLI credentials, container and
|
|
4
|
+
* Kubernetes credentials, netrc, GnuPG, git / npm / PyPI tokens, the macOS keychains, and the
|
|
5
|
+
* browser profile directories. One source for the device, which denies them (and its own state
|
|
6
|
+
* directory), and the kernel, which never proposes an approval for a path under one. Full access
|
|
7
|
+
* and auto mode run as the owner and do not apply them: the command review does.
|
|
8
|
+
*/
|
|
9
|
+
export declare const DEVICE_DENIED_SECRET_PATHS: readonly string[];
|
|
10
|
+
/**
|
|
11
|
+
* The device program's default state directory (`$XDG_CONFIG_HOME/capybara-device` when that is
|
|
12
|
+
* set), relative to `~`: denied to restricted work like the secret paths.
|
|
13
|
+
*/
|
|
14
|
+
export declare const DEVICE_DEFAULT_STATE_PATH = "~/.config/capybara-device";
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paths a local device never opens to restricted work (Request approval, Approve for me), relative
|
|
3
|
+
* to `~` (spec §13.6, extended by ruling R19): SSH keys, cloud CLI credentials, container and
|
|
4
|
+
* Kubernetes credentials, netrc, GnuPG, git / npm / PyPI tokens, the macOS keychains, and the
|
|
5
|
+
* browser profile directories. One source for the device, which denies them (and its own state
|
|
6
|
+
* directory), and the kernel, which never proposes an approval for a path under one. Full access
|
|
7
|
+
* and auto mode run as the owner and do not apply them: the command review does.
|
|
8
|
+
*/
|
|
9
|
+
export const DEVICE_DENIED_SECRET_PATHS = Object.freeze([
|
|
10
|
+
"~/.ssh",
|
|
11
|
+
"~/.aws",
|
|
12
|
+
"~/.config/gcloud",
|
|
13
|
+
"~/.azure",
|
|
14
|
+
"~/.kube",
|
|
15
|
+
"~/.docker/config.json",
|
|
16
|
+
"~/.netrc",
|
|
17
|
+
"~/.gnupg",
|
|
18
|
+
"~/Library/Application Support/Google/Chrome",
|
|
19
|
+
"~/Library/Application Support/Firefox",
|
|
20
|
+
"~/.mozilla",
|
|
21
|
+
"~/.config/google-chrome",
|
|
22
|
+
"~/.config/chromium",
|
|
23
|
+
// Ruling R19: more credential stores and browser data.
|
|
24
|
+
"~/.config/gh",
|
|
25
|
+
"~/.git-credentials",
|
|
26
|
+
"~/.npmrc",
|
|
27
|
+
"~/.pypirc",
|
|
28
|
+
"~/Library/Keychains",
|
|
29
|
+
"~/Library/Cookies",
|
|
30
|
+
"~/Library/Safari",
|
|
31
|
+
"~/Library/Application Support/BraveSoftware",
|
|
32
|
+
"~/Library/Application Support/Microsoft Edge",
|
|
33
|
+
"~/Library/Application Support/Arc",
|
|
34
|
+
"~/.config/BraveSoftware",
|
|
35
|
+
"~/.config/microsoft-edge",
|
|
36
|
+
]);
|
|
37
|
+
/**
|
|
38
|
+
* The device program's default state directory (`$XDG_CONFIG_HOME/capybara-device` when that is
|
|
39
|
+
* set), relative to `~`: denied to restricted work like the secret paths.
|
|
40
|
+
*/
|
|
41
|
+
export const DEVICE_DEFAULT_STATE_PATH = "~/.config/capybara-device";
|
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* The device protocol: the WebSocket frames between the kernel and a `capybara-device` program
|
|
3
3
|
* (a connected machine that serves as a device). Pure types and hand-written guards.
|
|
4
|
+
*
|
|
5
|
+
* Protocol 3 (the scope-bearing operations, `parseDeviceFrame`) is defined in the second half of
|
|
6
|
+
* this file. Protocol 2's frames keep a `Legacy` prefix where a protocol 3 name replaced them
|
|
7
|
+
* (`LegacyDeviceHello`, `parseLegacyDeviceFrame`, ...); protocol 3 reuses their value guards, and
|
|
8
|
+
* they go with the legacy device surface.
|
|
4
9
|
*/
|
|
5
10
|
import { type ExecResult, type SandboxActor, type SandboxLimits, type SandboxRoots } from "./sandbox.js";
|
|
11
|
+
import { type SandboxPermissionSupport } from "./sandbox-operation.js";
|
|
6
12
|
/** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
|
|
7
|
-
export declare const DEVICE_PROTOCOL_VERSION =
|
|
13
|
+
export declare const DEVICE_PROTOCOL_VERSION = 3;
|
|
14
|
+
/**
|
|
15
|
+
* Protocol 2's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
|
|
16
|
+
* on the header, a protocol close on the hello). Kept only for the legacy device surface.
|
|
17
|
+
*/
|
|
18
|
+
export declare const LEGACY_DEVICE_PROTOCOL_VERSION = 2;
|
|
8
19
|
/** The operations the kernel asks a device to run. */
|
|
9
20
|
export type DeviceOp = "create" | "exec" | "readFile" | "writeFile" | "stat" | "killTagged" | "killAll" | "stop" | "policy" | "policyStatus" | "list" | "scan";
|
|
10
21
|
/**
|
|
@@ -42,14 +53,6 @@ export interface DeviceProjectCandidate {
|
|
|
42
53
|
* choice cut to `mode`, never by a ceiling it saw on an earlier command.
|
|
43
54
|
*/
|
|
44
55
|
export type DeviceRequestCeiling = Pick<SandboxLimits, "mode">;
|
|
45
|
-
/**
|
|
46
|
-
* The first line of the kernel's background task launch command (`Bash` `run_in_background`), a
|
|
47
|
-
* shell comment. A device kills what a foreground exec leaves running once the exec ends; an exec
|
|
48
|
-
* whose command starts with this line detaches a task on purpose, and its processes are left alone.
|
|
49
|
-
*/
|
|
50
|
-
export declare const BACKGROUND_LAUNCH_LINE = "# capybara: background task launch";
|
|
51
|
-
/** Whether an exec's command is a background task launch ({@link BACKGROUND_LAUNCH_LINE}). */
|
|
52
|
-
export declare function isBackgroundLaunch(command: string): boolean;
|
|
53
56
|
/** The most blocked hosts an exec result reports; the parser cuts longer lists. */
|
|
54
57
|
export declare const MAX_NETWORK_BLOCKED_HOSTS = 20;
|
|
55
58
|
/** The longest `opId` a `policy` / `policyStatus` op may carry. */
|
|
@@ -67,7 +70,7 @@ export interface DevicePolicyOpReport {
|
|
|
67
70
|
outcome: DevicePolicyOpOutcome;
|
|
68
71
|
}
|
|
69
72
|
/** First frame from the device after the WebSocket opens. */
|
|
70
|
-
export interface
|
|
73
|
+
export interface LegacyDeviceHello {
|
|
71
74
|
type: "hello";
|
|
72
75
|
protocol: number;
|
|
73
76
|
programVersion: string;
|
|
@@ -101,7 +104,7 @@ export interface DeviceHello {
|
|
|
101
104
|
}
|
|
102
105
|
/** A hello's `bootId`: 1 to 128 characters of letters, digits, `.`, `_`, `:` and `-`. */
|
|
103
106
|
export declare const DEVICE_BOOT_ID_RE: RegExp;
|
|
104
|
-
/** Whether `v` is a well-formed {@link
|
|
107
|
+
/** Whether `v` is a well-formed {@link LegacyDeviceHello.bootId}. */
|
|
105
108
|
export declare function isDeviceBootId(v: unknown): v is string;
|
|
106
109
|
/** Error kinds a device reports for a failed request. */
|
|
107
110
|
export type DeviceErrorKind = "gone" | "fs_gone" | "policy" | "error";
|
|
@@ -139,11 +142,11 @@ export interface KernelCancel {
|
|
|
139
142
|
* this connection. `policy` is absent when the frame's summary was unreadable; the kernel then
|
|
140
143
|
* learns the policy later, as for the hello.
|
|
141
144
|
*/
|
|
142
|
-
export interface
|
|
145
|
+
export interface LegacyDevicePolicyChanged {
|
|
143
146
|
type: "policy";
|
|
144
147
|
policy?: DeviceLocalPolicySummary;
|
|
145
148
|
}
|
|
146
|
-
export type
|
|
149
|
+
export type LegacyDeviceFrame = LegacyDeviceHello | DeviceRes | LegacyDevicePolicyChanged | KernelReq | KernelCancel;
|
|
147
150
|
export interface DeviceExecArgs {
|
|
148
151
|
command: string;
|
|
149
152
|
cwd?: string;
|
|
@@ -211,7 +214,7 @@ export interface DeviceStopArgs {
|
|
|
211
214
|
* (`"sandbox"`), never off (turning auto mode on is decided on the machine), and `add` extends the
|
|
212
215
|
* sandbox-mode allowlist only. Narrowing is always accepted.
|
|
213
216
|
*/
|
|
214
|
-
export interface
|
|
217
|
+
export interface LegacyDevicePolicyArgs {
|
|
215
218
|
/**
|
|
216
219
|
* The kernel's id of this change (non-empty, no `:`, at most {@link MAX_POLICY_OP_ID_LENGTH}
|
|
217
220
|
* characters): the device logs the op's outcome under it, for `policyStatus` and the hello's
|
|
@@ -233,7 +236,7 @@ export interface DevicePolicyArgs {
|
|
|
233
236
|
};
|
|
234
237
|
}
|
|
235
238
|
/** The policy as the device wrote it. */
|
|
236
|
-
export interface
|
|
239
|
+
export interface LegacyDevicePolicyResult {
|
|
237
240
|
policy: DeviceLocalPolicySummary;
|
|
238
241
|
}
|
|
239
242
|
/** Asks what became of the `policy` op with this id. Read-only on the device. */
|
|
@@ -245,7 +248,7 @@ export interface DevicePolicyStatusArgs {
|
|
|
245
248
|
* the id is not in its log (never received, or dropped from the log since). `policy` is the
|
|
246
249
|
* device's summary now; `message` the refusal's.
|
|
247
250
|
*/
|
|
248
|
-
export interface
|
|
251
|
+
export interface LegacyDevicePolicyStatus {
|
|
249
252
|
outcome: DevicePolicyOpOutcome | "unknown";
|
|
250
253
|
policy?: DeviceLocalPolicySummary;
|
|
251
254
|
message?: string;
|
|
@@ -314,8 +317,8 @@ export interface DeviceOpResults {
|
|
|
314
317
|
killTagged: null;
|
|
315
318
|
killAll: null;
|
|
316
319
|
stop: null;
|
|
317
|
-
policy:
|
|
318
|
-
policyStatus:
|
|
320
|
+
policy: LegacyDevicePolicyResult;
|
|
321
|
+
policyStatus: LegacyDevicePolicyStatus;
|
|
319
322
|
list: DeviceListResult;
|
|
320
323
|
scan: DeviceScanResult;
|
|
321
324
|
}
|
|
@@ -327,4 +330,121 @@ export declare function parseOpResult<Op extends DeviceOp>(op: Op, result: unkno
|
|
|
327
330
|
* kernel `req` and `cancel`. Throws {@link DeviceProtocolError} on bad JSON, an unknown `type`,
|
|
328
331
|
* missing fields or a frame of the wrong direction.
|
|
329
332
|
*/
|
|
330
|
-
export declare function
|
|
333
|
+
export declare function parseLegacyDeviceFrame(raw: string, from: "device" | "kernel"): LegacyDeviceFrame;
|
|
334
|
+
/**
|
|
335
|
+
* The operations the kernel asks a protocol 3 device to run: every user operation carries its
|
|
336
|
+
* admitted scope; there is no broad kill (`killTagged` / `killAll`).
|
|
337
|
+
*/
|
|
338
|
+
export type DeviceOperation = Exclude<DeviceOp, "killTagged" | "killAll"> | "prepareReadFile" | "prepareWriteFile" | "prepareStat" | "browseStat" | "browseList" | "browseScan" | "backgroundStart" | "backgroundStatus" | "backgroundTail" | "backgroundReadOutput" | "backgroundStop" | "revokeOperation" | "bindInstance";
|
|
339
|
+
export interface DeviceOwnerCeiling {
|
|
340
|
+
readonly version: 2;
|
|
341
|
+
readonly sequence: number;
|
|
342
|
+
readonly restrictedProjectReach: "workspace" | "os-user";
|
|
343
|
+
readonly revision: string;
|
|
344
|
+
readonly fullAccess: boolean;
|
|
345
|
+
readonly restrictedAllowedDomains: readonly string[];
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* The only owner-ceiling change the kernel may ask of a machine (B2): narrowing. Widening is decided
|
|
349
|
+
* on the machine by its owner (`capybara-device ceiling set`), never over the wire.
|
|
350
|
+
*/
|
|
351
|
+
export interface DeviceOwnerCeilingNarrowing {
|
|
352
|
+
readonly fullAccess?: false;
|
|
353
|
+
readonly restrictedProjectReach?: "workspace";
|
|
354
|
+
}
|
|
355
|
+
/** A staged `policy` op: the protocol 2 change plus an optional owner-ceiling narrowing. */
|
|
356
|
+
export interface DevicePolicyArgs extends LegacyDevicePolicyArgs {
|
|
357
|
+
ownerCeiling?: DeviceOwnerCeilingNarrowing;
|
|
358
|
+
}
|
|
359
|
+
/** A staged `policy` answer: the policy as written and the owner report issued for it. */
|
|
360
|
+
export interface DevicePolicyResult {
|
|
361
|
+
policy: DeviceLocalPolicySummary;
|
|
362
|
+
ownerCeiling: DeviceOwnerCeiling;
|
|
363
|
+
}
|
|
364
|
+
/** A staged `policyStatus` answer: an `applied` outcome carries the current owner report. */
|
|
365
|
+
export interface DevicePolicyStatus extends LegacyDevicePolicyStatus {
|
|
366
|
+
ownerCeiling?: DeviceOwnerCeiling;
|
|
367
|
+
}
|
|
368
|
+
/** The device pushed a policy change: the owner report for the newly observed revision. */
|
|
369
|
+
export interface DevicePolicyChanged {
|
|
370
|
+
type: "policy";
|
|
371
|
+
policy?: DeviceLocalPolicySummary;
|
|
372
|
+
ownerCeiling: DeviceOwnerCeiling;
|
|
373
|
+
}
|
|
374
|
+
export interface DeviceHello extends LegacyDeviceHello {
|
|
375
|
+
protocol: 3;
|
|
376
|
+
permissionSupport: SandboxPermissionSupport;
|
|
377
|
+
ownerCeiling: DeviceOwnerCeiling;
|
|
378
|
+
instanceGeneration: string | null;
|
|
379
|
+
transport: {
|
|
380
|
+
maxFrameBytes: number;
|
|
381
|
+
};
|
|
382
|
+
/** Absent until the program can attest actual installed runtime/helper/environment bytes. */
|
|
383
|
+
runtimeIdentity?: DeviceRuntimeIdentity;
|
|
384
|
+
}
|
|
385
|
+
/** A verified installed runtime/helper/environment identity bound to one instance generation. */
|
|
386
|
+
export interface DeviceRuntimeIdentity {
|
|
387
|
+
runtimeHash: string;
|
|
388
|
+
helperHash: string;
|
|
389
|
+
imageFingerprint: string;
|
|
390
|
+
instanceGeneration: string;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Private lifecycle request (permission runtime cutover B4): binds the kernel's committed instance
|
|
394
|
+
* generation to the device after commit. It carries no path, policy or manifest.
|
|
395
|
+
*/
|
|
396
|
+
export interface BindInstanceRequest {
|
|
397
|
+
instanceId: string;
|
|
398
|
+
instanceGeneration: string;
|
|
399
|
+
bindingId: string;
|
|
400
|
+
expectedPreviousGeneration: string | null;
|
|
401
|
+
}
|
|
402
|
+
export interface BindInstanceResult {
|
|
403
|
+
instanceId: string;
|
|
404
|
+
instanceGeneration: string;
|
|
405
|
+
bindingId: string;
|
|
406
|
+
runtimeIdentity: DeviceRuntimeIdentity;
|
|
407
|
+
permissionSupport: SandboxPermissionSupport;
|
|
408
|
+
ownerCeiling: DeviceOwnerCeiling;
|
|
409
|
+
}
|
|
410
|
+
export interface KernelReady {
|
|
411
|
+
type: "ready";
|
|
412
|
+
connectionId: string;
|
|
413
|
+
maxFrameBytes: number;
|
|
414
|
+
}
|
|
415
|
+
export interface BackgroundReadOutputRequest {
|
|
416
|
+
offset: number;
|
|
417
|
+
maxBytes: number;
|
|
418
|
+
}
|
|
419
|
+
export type BackgroundReadOutputResult = {
|
|
420
|
+
dataB64: string;
|
|
421
|
+
offset: number;
|
|
422
|
+
nextOffset: number;
|
|
423
|
+
totalBytes: number;
|
|
424
|
+
} | {
|
|
425
|
+
unavailable: "lost" | "expired";
|
|
426
|
+
};
|
|
427
|
+
export interface KernelRequest {
|
|
428
|
+
type: "req";
|
|
429
|
+
id: string;
|
|
430
|
+
op: DeviceOperation;
|
|
431
|
+
args: Readonly<Record<string, unknown>>;
|
|
432
|
+
deadlineMs: number;
|
|
433
|
+
}
|
|
434
|
+
export type DeviceResponse = Exclude<DeviceRes, {
|
|
435
|
+
ok: false;
|
|
436
|
+
}> | {
|
|
437
|
+
type: "res";
|
|
438
|
+
id: string;
|
|
439
|
+
ok: false;
|
|
440
|
+
error: {
|
|
441
|
+
kind: "gone" | "fs_gone" | "policy" | "error" | "denied" | "unsupported" | "unknown";
|
|
442
|
+
message: string;
|
|
443
|
+
};
|
|
444
|
+
};
|
|
445
|
+
export type DeviceFrame = DeviceHello | KernelReady | KernelRequest | KernelCancel | DeviceResponse | DevicePolicyChanged;
|
|
446
|
+
/** Strictly parses one authenticated owner-ceiling report (B2); throws {@link DeviceProtocolError}. */
|
|
447
|
+
export declare function parseOwnerCeilingReport(value: unknown): DeviceOwnerCeiling;
|
|
448
|
+
/** Strictly parses one protocol 3 frame; throws {@link DeviceProtocolError}. */
|
|
449
|
+
export declare function parseDeviceFrame(raw: string, from: "device" | "kernel", maxFrameBytes?: number): DeviceFrame;
|
|
450
|
+
export declare function parseOperationResult(op: DeviceOperation, result: unknown, request?: BackgroundReadOutputRequest | BindInstanceRequest): unknown;
|
package/dist/device-protocol.js
CHANGED
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* The device protocol: the WebSocket frames between the kernel and a `capybara-device` program
|
|
3
3
|
* (a connected machine that serves as a device). Pure types and hand-written guards.
|
|
4
|
+
*
|
|
5
|
+
* Protocol 3 (the scope-bearing operations, `parseDeviceFrame`) is defined in the second half of
|
|
6
|
+
* this file. Protocol 2's frames keep a `Legacy` prefix where a protocol 3 name replaced them
|
|
7
|
+
* (`LegacyDeviceHello`, `parseLegacyDeviceFrame`, ...); protocol 3 reuses their value guards, and
|
|
8
|
+
* they go with the legacy device surface.
|
|
4
9
|
*/
|
|
5
10
|
import { isDeviceProjectName, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_RESULTS, validateAllowHost, validateSandboxPathShape, } from "./sandbox.js";
|
|
11
|
+
import { parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationRef, parseSandboxOperationScope, parseSandboxPreparationScope, } from "./sandbox-operation.js";
|
|
6
12
|
/** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
|
|
7
|
-
export const DEVICE_PROTOCOL_VERSION =
|
|
13
|
+
export const DEVICE_PROTOCOL_VERSION = 3;
|
|
14
|
+
/**
|
|
15
|
+
* Protocol 2's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
|
|
16
|
+
* on the header, a protocol close on the hello). Kept only for the legacy device surface.
|
|
17
|
+
*/
|
|
18
|
+
export const LEGACY_DEVICE_PROTOCOL_VERSION = 2;
|
|
8
19
|
const DEVICE_OPS = [
|
|
9
20
|
"create",
|
|
10
21
|
"exec",
|
|
@@ -28,16 +39,6 @@ const DEVICE_FEATURES = [
|
|
|
28
39
|
];
|
|
29
40
|
/** The most entries a `list` op may ask for and its result may carry. */
|
|
30
41
|
export const MAX_DEVICE_LIST_ENTRIES = 1000;
|
|
31
|
-
/**
|
|
32
|
-
* The first line of the kernel's background task launch command (`Bash` `run_in_background`), a
|
|
33
|
-
* shell comment. A device kills what a foreground exec leaves running once the exec ends; an exec
|
|
34
|
-
* whose command starts with this line detaches a task on purpose, and its processes are left alone.
|
|
35
|
-
*/
|
|
36
|
-
export const BACKGROUND_LAUNCH_LINE = "# capybara: background task launch";
|
|
37
|
-
/** Whether an exec's command is a background task launch ({@link BACKGROUND_LAUNCH_LINE}). */
|
|
38
|
-
export function isBackgroundLaunch(command) {
|
|
39
|
-
return command === BACKGROUND_LAUNCH_LINE || command.startsWith(`${BACKGROUND_LAUNCH_LINE}\n`);
|
|
40
|
-
}
|
|
41
42
|
/** The most blocked hosts an exec result reports; the parser cuts longer lists. */
|
|
42
43
|
export const MAX_NETWORK_BLOCKED_HOSTS = 20;
|
|
43
44
|
/** The most hosts a `policy` op's `add` / `remove` or an exec's `grants` may carry. */
|
|
@@ -48,7 +49,7 @@ export const MAX_POLICY_OP_ID_LENGTH = 128;
|
|
|
48
49
|
export const MAX_RECENT_POLICY_OPS = 100;
|
|
49
50
|
/** A hello's `bootId`: 1 to 128 characters of letters, digits, `.`, `_`, `:` and `-`. */
|
|
50
51
|
export const DEVICE_BOOT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
51
|
-
/** Whether `v` is a well-formed {@link
|
|
52
|
+
/** Whether `v` is a well-formed {@link LegacyDeviceHello.bootId}. */
|
|
52
53
|
export function isDeviceBootId(v) {
|
|
53
54
|
return typeof v === "string" && DEVICE_BOOT_ID_RE.test(v);
|
|
54
55
|
}
|
|
@@ -536,7 +537,7 @@ export function parseOpResult(op, result) {
|
|
|
536
537
|
* kernel `req` and `cancel`. Throws {@link DeviceProtocolError} on bad JSON, an unknown `type`,
|
|
537
538
|
* missing fields or a frame of the wrong direction.
|
|
538
539
|
*/
|
|
539
|
-
export function
|
|
540
|
+
export function parseLegacyDeviceFrame(raw, from) {
|
|
540
541
|
let o;
|
|
541
542
|
try {
|
|
542
543
|
o = JSON.parse(raw);
|
|
@@ -565,3 +566,407 @@ export function parseDeviceFrame(raw, from) {
|
|
|
565
566
|
throw new DeviceProtocolError(`unknown frame type "${String(type)}"`);
|
|
566
567
|
}
|
|
567
568
|
}
|
|
569
|
+
const object = (value) => {
|
|
570
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
571
|
+
throw new DeviceProtocolError("Expected an object");
|
|
572
|
+
return value;
|
|
573
|
+
};
|
|
574
|
+
function keys(value, allowed) {
|
|
575
|
+
for (const key of Object.keys(value))
|
|
576
|
+
if (!allowed.includes(key))
|
|
577
|
+
throw new DeviceProtocolError(`Unknown field ${key}`);
|
|
578
|
+
}
|
|
579
|
+
function string(value, max = 128) {
|
|
580
|
+
if (typeof value !== "string" || !value.length || value.length > max)
|
|
581
|
+
throw new DeviceProtocolError("Expected a bounded nonempty string");
|
|
582
|
+
return value;
|
|
583
|
+
}
|
|
584
|
+
function integer(value, min = 0, max = Number.MAX_SAFE_INTEGER) {
|
|
585
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)
|
|
586
|
+
throw new DeviceProtocolError("Expected a bounded integer");
|
|
587
|
+
return value;
|
|
588
|
+
}
|
|
589
|
+
function path(value) {
|
|
590
|
+
if (typeof value !== "string" || validateSandboxPathShape(value).length)
|
|
591
|
+
throw new DeviceProtocolError("Expected an absolute filesystem path");
|
|
592
|
+
}
|
|
593
|
+
function freeze(value) {
|
|
594
|
+
if (value !== null && typeof value === "object") {
|
|
595
|
+
for (const v of Object.values(value))
|
|
596
|
+
freeze(v);
|
|
597
|
+
Object.freeze(value);
|
|
598
|
+
}
|
|
599
|
+
return value;
|
|
600
|
+
}
|
|
601
|
+
function support(value) {
|
|
602
|
+
const o = object(value);
|
|
603
|
+
keys(o, ["version", "restricted", "fullAccess", "background", "unavailableReason"]);
|
|
604
|
+
if (o.version !== 1 || typeof o.fullAccess !== "boolean" || typeof o.background !== "boolean")
|
|
605
|
+
throw new DeviceProtocolError("Invalid runtime permission report");
|
|
606
|
+
if (o.restricted !== null) {
|
|
607
|
+
const r = object(o.restricted);
|
|
608
|
+
keys(r, ["filesystem", "network", "native", "concurrentScopes"]);
|
|
609
|
+
for (const k of ["filesystem", "network", "native", "concurrentScopes"])
|
|
610
|
+
if (r[k] !== true)
|
|
611
|
+
throw new DeviceProtocolError("Incomplete restricted runtime report");
|
|
612
|
+
}
|
|
613
|
+
if (o.unavailableReason !== undefined)
|
|
614
|
+
string(o.unavailableReason, 4096);
|
|
615
|
+
return o;
|
|
616
|
+
}
|
|
617
|
+
/** Strictly parses one authenticated owner-ceiling report (B2); throws {@link DeviceProtocolError}. */
|
|
618
|
+
export function parseOwnerCeilingReport(value) {
|
|
619
|
+
return freeze(structuredClone(owner(value)));
|
|
620
|
+
}
|
|
621
|
+
function narrowing(value) {
|
|
622
|
+
const o = object(value);
|
|
623
|
+
keys(o, ["fullAccess", "restrictedProjectReach"]);
|
|
624
|
+
if ((o.fullAccess !== undefined && o.fullAccess !== false) ||
|
|
625
|
+
(o.restrictedProjectReach !== undefined && o.restrictedProjectReach !== "workspace"))
|
|
626
|
+
throw new DeviceProtocolError("The deployment may only narrow the owner ceiling");
|
|
627
|
+
return o;
|
|
628
|
+
}
|
|
629
|
+
function owner(value) {
|
|
630
|
+
const o = object(value);
|
|
631
|
+
keys(o, [
|
|
632
|
+
"version",
|
|
633
|
+
"sequence",
|
|
634
|
+
"revision",
|
|
635
|
+
"fullAccess",
|
|
636
|
+
"restrictedProjectReach",
|
|
637
|
+
"restrictedAllowedDomains",
|
|
638
|
+
]);
|
|
639
|
+
integer(o.sequence);
|
|
640
|
+
if (o.version !== 2 || !["workspace", "os-user"].includes(String(o.restrictedProjectReach)))
|
|
641
|
+
throw new DeviceProtocolError("Invalid owner ceiling report version or project reach");
|
|
642
|
+
string(o.revision, 512);
|
|
643
|
+
if (typeof o.fullAccess !== "boolean" ||
|
|
644
|
+
!Array.isArray(o.restrictedAllowedDomains) ||
|
|
645
|
+
o.restrictedAllowedDomains.length > 100 ||
|
|
646
|
+
o.restrictedAllowedDomains.some((h) => typeof h !== "string" || validateAllowHost(h).length))
|
|
647
|
+
throw new DeviceProtocolError("Invalid owner ceiling");
|
|
648
|
+
return o;
|
|
649
|
+
}
|
|
650
|
+
const GENERATION = /^[0-9]{1,16}$/;
|
|
651
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
652
|
+
function generation(value) {
|
|
653
|
+
if (typeof value !== "string" || !GENERATION.test(value))
|
|
654
|
+
throw new DeviceProtocolError("Expected an instance generation");
|
|
655
|
+
return value;
|
|
656
|
+
}
|
|
657
|
+
function bindRequest(a) {
|
|
658
|
+
string(a.instanceId);
|
|
659
|
+
generation(a.instanceGeneration);
|
|
660
|
+
if (typeof a.bindingId !== "string" || !UUID.test(a.bindingId))
|
|
661
|
+
throw new DeviceProtocolError("Expected a binding id");
|
|
662
|
+
if (a.expectedPreviousGeneration !== null) {
|
|
663
|
+
generation(a.expectedPreviousGeneration);
|
|
664
|
+
if (BigInt(a.expectedPreviousGeneration) >= BigInt(a.instanceGeneration))
|
|
665
|
+
throw new DeviceProtocolError("Previous generation must precede the bound generation");
|
|
666
|
+
}
|
|
667
|
+
return a;
|
|
668
|
+
}
|
|
669
|
+
function identity(value) {
|
|
670
|
+
const o = object(value);
|
|
671
|
+
keys(o, ["runtimeHash", "helperHash", "imageFingerprint", "instanceGeneration"]);
|
|
672
|
+
for (const key of ["runtimeHash", "helperHash", "imageFingerprint"])
|
|
673
|
+
if (typeof o[key] !== "string" || !/^[a-f0-9]{64}$/.test(o[key]))
|
|
674
|
+
throw new DeviceProtocolError("Incomplete runtime identity");
|
|
675
|
+
string(o.instanceGeneration);
|
|
676
|
+
return o;
|
|
677
|
+
}
|
|
678
|
+
const natives = ["exec", "readFile", "writeFile", "stat", "list", "scan"];
|
|
679
|
+
const legacy = ["create", "stop", "policy", "policyStatus"];
|
|
680
|
+
function request(o) {
|
|
681
|
+
keys(o, ["type", "id", "op", "args", "deadlineMs"]);
|
|
682
|
+
const id = string(o.id), op = string(o.op), a = object(o.args), deadlineMs = integer(o.deadlineMs, 1);
|
|
683
|
+
if (legacy.includes(op)) {
|
|
684
|
+
if (op === "policy" && a.ownerCeiling !== undefined)
|
|
685
|
+
narrowing(a.ownerCeiling);
|
|
686
|
+
const parsed = parseLegacyDeviceFrame(JSON.stringify(o), "kernel");
|
|
687
|
+
if (parsed.type !== "req")
|
|
688
|
+
throw new DeviceProtocolError("Expected request");
|
|
689
|
+
return freeze({ ...parsed, op: op, args: object(parsed.args) });
|
|
690
|
+
}
|
|
691
|
+
if (op === "bindInstance") {
|
|
692
|
+
keys(a, ["instanceId", "instanceGeneration", "bindingId", "expectedPreviousGeneration"]);
|
|
693
|
+
bindRequest(a);
|
|
694
|
+
}
|
|
695
|
+
else if (op === "revokeOperation") {
|
|
696
|
+
keys(a, ["ref"]);
|
|
697
|
+
a.ref = parseSandboxOperationRef(a.ref);
|
|
698
|
+
}
|
|
699
|
+
else if (["backgroundStatus", "backgroundTail", "backgroundReadOutput", "backgroundStop"].includes(op)) {
|
|
700
|
+
keys(a, [
|
|
701
|
+
"ref",
|
|
702
|
+
...(op === "backgroundReadOutput" ? ["offset", "maxBytes"] : []),
|
|
703
|
+
...(op === "backgroundTail" ? ["maxBytes"] : op === "backgroundStop" ? ["graceMs"] : []),
|
|
704
|
+
]);
|
|
705
|
+
a.ref = parseSandboxExecutionRef(a.ref);
|
|
706
|
+
if (op === "backgroundTail" || op === "backgroundReadOutput")
|
|
707
|
+
integer(a.maxBytes, 0, 65536);
|
|
708
|
+
if (op === "backgroundReadOutput")
|
|
709
|
+
integer(a.offset);
|
|
710
|
+
if (op === "backgroundStop")
|
|
711
|
+
integer(a.graceMs, 0, 60000);
|
|
712
|
+
}
|
|
713
|
+
else {
|
|
714
|
+
const preparation = op.startsWith("prepare"), browsing = op.startsWith("browse"), background = op === "backgroundStart";
|
|
715
|
+
const method = background ? "exec" : preparation ? op.slice(7) : browsing ? op.slice(6) : op;
|
|
716
|
+
const native = method[0]?.toLowerCase() + method.slice(1);
|
|
717
|
+
if (!natives.includes(native) ||
|
|
718
|
+
(preparation && !["readFile", "writeFile", "stat"].includes(native)) ||
|
|
719
|
+
(browsing && !["stat", "list", "scan"].includes(native)))
|
|
720
|
+
throw new DeviceProtocolError("Unknown operation");
|
|
721
|
+
a.scope = preparation
|
|
722
|
+
? parseSandboxPreparationScope(a.scope)
|
|
723
|
+
: browsing
|
|
724
|
+
? parseSandboxBrowseScope(a.scope)
|
|
725
|
+
: parseSandboxOperationScope(a.scope);
|
|
726
|
+
const fields = native === "exec"
|
|
727
|
+
? ["command", "cwd", "env", "timeoutMs", "maxOutputBytes", "limits", "grants"]
|
|
728
|
+
: native === "readFile"
|
|
729
|
+
? ["path", "maxBytes"]
|
|
730
|
+
: native === "writeFile"
|
|
731
|
+
? ["path", "dataB64"]
|
|
732
|
+
: native === "stat"
|
|
733
|
+
? ["path"]
|
|
734
|
+
: native === "list"
|
|
735
|
+
? ["path", "limit"]
|
|
736
|
+
: ["base"];
|
|
737
|
+
keys(a, ["scope", ...fields, ...(background ? ["taskId", "outputPath", "retainUntilMs"] : [])]);
|
|
738
|
+
if (native !== "exec")
|
|
739
|
+
path(a[native === "scan" ? "base" : "path"]);
|
|
740
|
+
const validated = { ...a };
|
|
741
|
+
delete validated.scope;
|
|
742
|
+
if (native === "exec") {
|
|
743
|
+
const scope = parseSandboxOperationScope(a.scope);
|
|
744
|
+
validated.tag = scope.tag;
|
|
745
|
+
validated.actor = scope.actor;
|
|
746
|
+
if (background) {
|
|
747
|
+
string(a.taskId);
|
|
748
|
+
path(a.outputPath);
|
|
749
|
+
integer(a.retainUntilMs, scope.admitBeforeMs);
|
|
750
|
+
delete validated.taskId;
|
|
751
|
+
delete validated.outputPath;
|
|
752
|
+
delete validated.retainUntilMs;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
else if (native !== "writeFile")
|
|
756
|
+
validated.limits = { mode: "sandbox" };
|
|
757
|
+
// Reuse v2's pure value guards; inserted mode is never returned or used as authority.
|
|
758
|
+
parseLegacyDeviceFrame(JSON.stringify({ type: "req", id, op: native, args: validated, deadlineMs }), "kernel");
|
|
759
|
+
if (native === "writeFile" &&
|
|
760
|
+
(typeof a.dataB64 !== "string" ||
|
|
761
|
+
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a.dataB64)))
|
|
762
|
+
throw new DeviceProtocolError("Invalid base64 payload");
|
|
763
|
+
}
|
|
764
|
+
return freeze({ type: "req", id, op: op, args: a, deadlineMs });
|
|
765
|
+
}
|
|
766
|
+
/** Strictly parses one protocol 3 frame; throws {@link DeviceProtocolError}. */
|
|
767
|
+
export function parseDeviceFrame(raw, from, maxFrameBytes) {
|
|
768
|
+
if (maxFrameBytes !== undefined &&
|
|
769
|
+
new TextEncoder().encode(raw).byteLength > integer(maxFrameBytes, 1))
|
|
770
|
+
throw new DeviceProtocolError("Frame exceeds negotiated capacity; check device and deployment frame limits");
|
|
771
|
+
let parsed;
|
|
772
|
+
try {
|
|
773
|
+
parsed = JSON.parse(raw);
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
throw new DeviceProtocolError("Frame is not valid JSON");
|
|
777
|
+
}
|
|
778
|
+
const o = object(parsed);
|
|
779
|
+
if (o.type === "ready") {
|
|
780
|
+
if (from !== "kernel")
|
|
781
|
+
throw new DeviceProtocolError("Ready must come from kernel");
|
|
782
|
+
keys(o, ["type", "connectionId", "maxFrameBytes"]);
|
|
783
|
+
return freeze({
|
|
784
|
+
type: "ready",
|
|
785
|
+
connectionId: string(o.connectionId),
|
|
786
|
+
maxFrameBytes: integer(o.maxFrameBytes, 1024),
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
if (o.type === "req") {
|
|
790
|
+
if (from !== "kernel")
|
|
791
|
+
throw new DeviceProtocolError("Request must come from kernel");
|
|
792
|
+
return request(o);
|
|
793
|
+
}
|
|
794
|
+
if (o.type === "hello") {
|
|
795
|
+
if (from !== "device" || o.protocol !== 3)
|
|
796
|
+
throw new DeviceProtocolError("Expected protocol 3 hello");
|
|
797
|
+
const transport = object(o.transport);
|
|
798
|
+
keys(transport, ["maxFrameBytes"]);
|
|
799
|
+
const maxFrameBytes = integer(transport.maxFrameBytes, 1024);
|
|
800
|
+
const permissionSupport = support(o.permissionSupport);
|
|
801
|
+
if (o.instanceGeneration === null &&
|
|
802
|
+
(o.runtimeIdentity !== undefined ||
|
|
803
|
+
permissionSupport.restricted !== null ||
|
|
804
|
+
permissionSupport.fullAccess ||
|
|
805
|
+
permissionSupport.background ||
|
|
806
|
+
!permissionSupport.unavailableReason))
|
|
807
|
+
throw new DeviceProtocolError("Unbound hello cannot advertise runtime capability");
|
|
808
|
+
const base = parseLegacyDeviceFrame(raw, from);
|
|
809
|
+
if (base.type !== "hello")
|
|
810
|
+
throw new DeviceProtocolError("Expected hello");
|
|
811
|
+
let runtimeIdentity;
|
|
812
|
+
if (o.runtimeIdentity !== undefined) {
|
|
813
|
+
runtimeIdentity = identity(o.runtimeIdentity);
|
|
814
|
+
if (runtimeIdentity.instanceGeneration !== string(o.instanceGeneration))
|
|
815
|
+
throw new DeviceProtocolError("Runtime identity generation mismatch");
|
|
816
|
+
}
|
|
817
|
+
return freeze({
|
|
818
|
+
...base,
|
|
819
|
+
protocol: 3,
|
|
820
|
+
permissionSupport,
|
|
821
|
+
transport: { maxFrameBytes },
|
|
822
|
+
ownerCeiling: owner(o.ownerCeiling),
|
|
823
|
+
instanceGeneration: o.instanceGeneration === null ? null : string(o.instanceGeneration),
|
|
824
|
+
...(runtimeIdentity && { runtimeIdentity }),
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
if (o.type === "policy") {
|
|
828
|
+
if (from !== "device")
|
|
829
|
+
throw new DeviceProtocolError("Policy must come from device");
|
|
830
|
+
keys(o, ["type", "policy", "ownerCeiling"]);
|
|
831
|
+
const base = parseLegacyDeviceFrame(JSON.stringify({ type: "policy", policy: o.policy }), from);
|
|
832
|
+
if (base.type !== "policy")
|
|
833
|
+
throw new DeviceProtocolError("Expected policy");
|
|
834
|
+
return freeze({ ...base, ownerCeiling: owner(o.ownerCeiling) });
|
|
835
|
+
}
|
|
836
|
+
if (o.type === "res" && o.ok === false) {
|
|
837
|
+
if (from !== "device")
|
|
838
|
+
throw new DeviceProtocolError("Response must come from device");
|
|
839
|
+
keys(o, ["type", "id", "ok", "error"]);
|
|
840
|
+
const e = object(o.error);
|
|
841
|
+
keys(e, ["kind", "message"]);
|
|
842
|
+
if (!["gone", "fs_gone", "policy", "error", "denied", "unsupported", "unknown"].includes(String(e.kind)))
|
|
843
|
+
throw new DeviceProtocolError("Unknown outcome kind");
|
|
844
|
+
return freeze({
|
|
845
|
+
type: "res",
|
|
846
|
+
id: string(o.id),
|
|
847
|
+
ok: false,
|
|
848
|
+
error: {
|
|
849
|
+
kind: e.kind,
|
|
850
|
+
message: string(e.message, 8192),
|
|
851
|
+
},
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
const base = parseLegacyDeviceFrame(raw, from);
|
|
855
|
+
if (base.type === "hello" || base.type === "req" || base.type === "policy")
|
|
856
|
+
throw new DeviceProtocolError("Expected staged frame");
|
|
857
|
+
return freeze(base);
|
|
858
|
+
}
|
|
859
|
+
export function parseOperationResult(op, result, request) {
|
|
860
|
+
if (op === "bindInstance") {
|
|
861
|
+
if (!request || !("bindingId" in request))
|
|
862
|
+
throw new DeviceProtocolError("Binding validation requires the exact request");
|
|
863
|
+
const o = object(result);
|
|
864
|
+
keys(o, [
|
|
865
|
+
"instanceId",
|
|
866
|
+
"instanceGeneration",
|
|
867
|
+
"bindingId",
|
|
868
|
+
"runtimeIdentity",
|
|
869
|
+
"permissionSupport",
|
|
870
|
+
"ownerCeiling",
|
|
871
|
+
]);
|
|
872
|
+
const runtimeIdentity = identity(o.runtimeIdentity);
|
|
873
|
+
if (o.instanceId !== request.instanceId ||
|
|
874
|
+
o.instanceGeneration !== request.instanceGeneration ||
|
|
875
|
+
o.bindingId !== request.bindingId ||
|
|
876
|
+
runtimeIdentity.instanceGeneration !== request.instanceGeneration)
|
|
877
|
+
throw new DeviceProtocolError("Binding answer belongs to another instance generation");
|
|
878
|
+
return freeze({
|
|
879
|
+
instanceId: request.instanceId,
|
|
880
|
+
instanceGeneration: request.instanceGeneration,
|
|
881
|
+
bindingId: request.bindingId,
|
|
882
|
+
runtimeIdentity,
|
|
883
|
+
permissionSupport: support(o.permissionSupport),
|
|
884
|
+
ownerCeiling: owner(o.ownerCeiling),
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
if (op === "backgroundReadOutput") {
|
|
888
|
+
if (!request || !("offset" in request))
|
|
889
|
+
throw new DeviceProtocolError("Output validation requires the exact request bounds");
|
|
890
|
+
const offset = integer(request.offset), maxBytes = integer(request.maxBytes, 0, 65536);
|
|
891
|
+
const o = object(result);
|
|
892
|
+
if ("unavailable" in o) {
|
|
893
|
+
keys(o, ["unavailable"]);
|
|
894
|
+
if (o.unavailable !== "lost" && o.unavailable !== "expired")
|
|
895
|
+
throw new DeviceProtocolError("Invalid output outcome");
|
|
896
|
+
return freeze(o);
|
|
897
|
+
}
|
|
898
|
+
keys(o, ["dataB64", "offset", "nextOffset", "totalBytes"]);
|
|
899
|
+
const total = integer(o.totalBytes), next = integer(o.nextOffset);
|
|
900
|
+
if (integer(o.offset) !== offset ||
|
|
901
|
+
typeof o.dataB64 !== "string" ||
|
|
902
|
+
o.dataB64.length > 87384 ||
|
|
903
|
+
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o.dataB64))
|
|
904
|
+
throw new DeviceProtocolError("Invalid output range or base64");
|
|
905
|
+
const decoded = atob(o.dataB64);
|
|
906
|
+
if (btoa(decoded) !== o.dataB64 ||
|
|
907
|
+
decoded.length !== Math.min(maxBytes, Math.max(total - offset, 0)) ||
|
|
908
|
+
!Number.isSafeInteger(offset + decoded.length) ||
|
|
909
|
+
next !== offset + decoded.length)
|
|
910
|
+
throw new DeviceProtocolError("Inconsistent output range; retry from the same offset");
|
|
911
|
+
return freeze(o);
|
|
912
|
+
}
|
|
913
|
+
if (op === "backgroundStart")
|
|
914
|
+
return parseSandboxExecutionRef(result);
|
|
915
|
+
if (op === "backgroundStatus") {
|
|
916
|
+
const o = object(result);
|
|
917
|
+
keys(o, ["state", "exitCode", "timedOut"]);
|
|
918
|
+
if (o.state === "running" || o.state === "lost")
|
|
919
|
+
return freeze({ state: o.state });
|
|
920
|
+
if (o.state !== "exited" ||
|
|
921
|
+
(o.exitCode !== null && !Number.isInteger(o.exitCode)) ||
|
|
922
|
+
typeof o.timedOut !== "boolean")
|
|
923
|
+
throw new DeviceProtocolError("Invalid execution status");
|
|
924
|
+
return freeze(o);
|
|
925
|
+
}
|
|
926
|
+
if (op === "backgroundTail") {
|
|
927
|
+
if (result && typeof result === "object" && "unavailable" in result) {
|
|
928
|
+
const o = object(result);
|
|
929
|
+
keys(o, ["unavailable"]);
|
|
930
|
+
if (o.unavailable !== "lost" && o.unavailable !== "expired")
|
|
931
|
+
throw new DeviceProtocolError("Invalid output outcome");
|
|
932
|
+
return freeze(o);
|
|
933
|
+
}
|
|
934
|
+
return parseOpResult("readFile", result);
|
|
935
|
+
}
|
|
936
|
+
if (op === "backgroundStop") {
|
|
937
|
+
const o = object(result);
|
|
938
|
+
keys(o, ["outcome", "exitCode", "timedOut"]);
|
|
939
|
+
if (!["already-exited", "stopped", "cancel-pending", "lost"].includes(String(o.outcome)))
|
|
940
|
+
throw new DeviceProtocolError("Invalid stop outcome");
|
|
941
|
+
if (o.outcome === "already-exited" &&
|
|
942
|
+
((o.exitCode !== null && !Number.isInteger(o.exitCode)) || typeof o.timedOut !== "boolean"))
|
|
943
|
+
throw new DeviceProtocolError("Invalid stopped execution status");
|
|
944
|
+
return freeze(o);
|
|
945
|
+
}
|
|
946
|
+
if (op === "policy") {
|
|
947
|
+
const o = object(result);
|
|
948
|
+
keys(o, ["policy", "ownerCeiling"]);
|
|
949
|
+
return freeze({
|
|
950
|
+
...parseOpResult("policy", { policy: o.policy }),
|
|
951
|
+
ownerCeiling: owner(o.ownerCeiling),
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
if (op === "policyStatus") {
|
|
955
|
+
const o = object(result);
|
|
956
|
+
keys(o, ["outcome", "policy", "message", "ownerCeiling"]);
|
|
957
|
+
const { ownerCeiling, ...rest } = o;
|
|
958
|
+
const status = parseOpResult("policyStatus", rest);
|
|
959
|
+
if (status.outcome === "applied" && ownerCeiling === undefined)
|
|
960
|
+
throw new DeviceProtocolError("An applied policy status carries the owner report");
|
|
961
|
+
if (ownerCeiling !== undefined)
|
|
962
|
+
status.ownerCeiling = owner(ownerCeiling);
|
|
963
|
+
return freeze(status);
|
|
964
|
+
}
|
|
965
|
+
if (op === "revokeOperation") {
|
|
966
|
+
if (result !== null)
|
|
967
|
+
throw new DeviceProtocolError("Revoke result must be null");
|
|
968
|
+
return null;
|
|
969
|
+
}
|
|
970
|
+
const raw = op.startsWith("prepare") ? op.slice(7) : op.startsWith("browse") ? op.slice(6) : op;
|
|
971
|
+
return parseOpResult((raw.charAt(0).toLowerCase() + raw.slice(1)), result);
|
|
972
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const SDK_VERSION = "0.1.0-rc.
|
|
1
|
+
export declare const SDK_VERSION = "0.1.0-rc.36";
|
|
2
2
|
export * from "./agent-template.js";
|
|
3
3
|
export * from "./bootstrap.js";
|
|
4
4
|
export * from "./cards.js";
|
|
@@ -11,8 +11,8 @@ export * from "./connector-auth.js";
|
|
|
11
11
|
export * from "./context.js";
|
|
12
12
|
export * from "./ctx.js";
|
|
13
13
|
export * from "./define-extension.js";
|
|
14
|
+
export { DEVICE_DEFAULT_STATE_PATH, DEVICE_DENIED_SECRET_PATHS } from "./device-denied-paths.js";
|
|
14
15
|
export * from "./device-protocol.js";
|
|
15
|
-
export { type BackgroundReadOutputRequestV3, type BackgroundReadOutputResultV3, type BindInstanceRequestV3, type BindInstanceResultV3, type DeviceFrameV3, type DeviceHelloV3, type DeviceOperationV3, type DeviceOwnerCeilingNarrowingV3, type DeviceOwnerCeilingV3, type DevicePolicyArgsV3, type DevicePolicyChangedV3, type DevicePolicyResultV3, type DevicePolicyStatusV3, type DeviceResponseV3, type DeviceRuntimeIdentityV3, type KernelReadyV3, type KernelRequestV3, parseDeviceFrameV3, parseOperationResultV3, parseOwnerCeilingReportV3, STAGED_DEVICE_PROTOCOL_VERSION, } from "./device-protocol-v3.js";
|
|
16
16
|
export * from "./directory.js";
|
|
17
17
|
export * from "./extension-point.js";
|
|
18
18
|
export * from "./file-preview.js";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const SDK_VERSION = "0.1.0-rc.
|
|
1
|
+
export const SDK_VERSION = "0.1.0-rc.36";
|
|
2
2
|
export * from "./agent-template.js";
|
|
3
3
|
export * from "./bootstrap.js";
|
|
4
4
|
export * from "./cards.js";
|
|
@@ -11,9 +11,8 @@ export * from "./connector-auth.js";
|
|
|
11
11
|
export * from "./context.js";
|
|
12
12
|
export * from "./ctx.js";
|
|
13
13
|
export * from "./define-extension.js";
|
|
14
|
+
export { DEVICE_DEFAULT_STATE_PATH, DEVICE_DENIED_SECRET_PATHS } from "./device-denied-paths.js";
|
|
14
15
|
export * from "./device-protocol.js";
|
|
15
|
-
// Development staging: removed with the coordinated device protocol v3 activation.
|
|
16
|
-
export { parseDeviceFrameV3, parseOperationResultV3, parseOwnerCeilingReportV3, STAGED_DEVICE_PROTOCOL_VERSION, } from "./device-protocol-v3.js";
|
|
17
16
|
export * from "./directory.js";
|
|
18
17
|
export * from "./extension-point.js";
|
|
19
18
|
export * from "./file-preview.js";
|
|
@@ -179,11 +179,15 @@ export interface SandboxBackground {
|
|
|
179
179
|
* Persist exact ownership before acknowledging; retries of the same generation/operation/input
|
|
180
180
|
* return the same reference. Retain starting grants for the lifetime of the owned execution.
|
|
181
181
|
* Validate outputPath inside the scope. retainUntilMs bounds status/output record retention.
|
|
182
|
+
* instanceGeneration is the kernel's generation of the held instance `h` (the kernel always
|
|
183
|
+
* passes it, and allocates it only after `create` returns): a provider that keeps no generation
|
|
184
|
+
* of its own (a cloud provider) returns it in the reference and keys start idempotency by it.
|
|
182
185
|
*/
|
|
183
186
|
start(h: SandboxHandle, scope: SandboxOperationScope, args: SandboxExecOptions & {
|
|
184
187
|
taskId: string;
|
|
185
188
|
outputPath: string;
|
|
186
189
|
retainUntilMs: number;
|
|
190
|
+
instanceGeneration?: string;
|
|
187
191
|
}): Promise<SandboxExecutionRef>;
|
|
188
192
|
status(h: SandboxHandle, ref: SandboxExecutionRef, signal: AbortSignal): Promise<SandboxExecutionStatus>;
|
|
189
193
|
/** At most 65,536 bytes, preserving UTF-8 boundaries and existing final-line limits; no caller path. */
|
package/package.json
CHANGED
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
/** Development staging only. Task 8 replaces v2 and removes this module and its staged names together. */
|
|
2
|
-
import { type DeviceHello, type DeviceLocalPolicySummary, type DeviceOp, type DevicePolicyArgs, type DevicePolicyStatus, type DeviceRes, type KernelCancel } from "./device-protocol.js";
|
|
3
|
-
import { type SandboxPermissionSupport } from "./sandbox-operation.js";
|
|
4
|
-
export declare const STAGED_DEVICE_PROTOCOL_VERSION = 3;
|
|
5
|
-
export type DeviceOperationV3 = Exclude<DeviceOp, "killTagged" | "killAll"> | "prepareReadFile" | "prepareWriteFile" | "prepareStat" | "browseStat" | "browseList" | "browseScan" | "backgroundStart" | "backgroundStatus" | "backgroundTail" | "backgroundReadOutput" | "backgroundStop" | "revokeOperation" | "bindInstance";
|
|
6
|
-
export interface DeviceOwnerCeilingV3 {
|
|
7
|
-
readonly version: 2;
|
|
8
|
-
readonly sequence: number;
|
|
9
|
-
readonly restrictedProjectReach: "workspace" | "os-user";
|
|
10
|
-
readonly revision: string;
|
|
11
|
-
readonly fullAccess: boolean;
|
|
12
|
-
readonly restrictedAllowedDomains: readonly string[];
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* The only owner-ceiling change the kernel may ask of a machine (B2): narrowing. Widening is decided
|
|
16
|
-
* on the machine by its owner (`capybara-device ceiling set`), never over the wire.
|
|
17
|
-
*/
|
|
18
|
-
export interface DeviceOwnerCeilingNarrowingV3 {
|
|
19
|
-
readonly fullAccess?: false;
|
|
20
|
-
readonly restrictedProjectReach?: "workspace";
|
|
21
|
-
}
|
|
22
|
-
/** A staged `policy` op: the protocol 2 change plus an optional owner-ceiling narrowing. */
|
|
23
|
-
export interface DevicePolicyArgsV3 extends DevicePolicyArgs {
|
|
24
|
-
ownerCeiling?: DeviceOwnerCeilingNarrowingV3;
|
|
25
|
-
}
|
|
26
|
-
/** A staged `policy` answer: the policy as written and the owner report issued for it. */
|
|
27
|
-
export interface DevicePolicyResultV3 {
|
|
28
|
-
policy: DeviceLocalPolicySummary;
|
|
29
|
-
ownerCeiling: DeviceOwnerCeilingV3;
|
|
30
|
-
}
|
|
31
|
-
/** A staged `policyStatus` answer: an `applied` outcome carries the current owner report. */
|
|
32
|
-
export interface DevicePolicyStatusV3 extends DevicePolicyStatus {
|
|
33
|
-
ownerCeiling?: DeviceOwnerCeilingV3;
|
|
34
|
-
}
|
|
35
|
-
/** The device pushed a policy change: the owner report for the newly observed revision. */
|
|
36
|
-
export interface DevicePolicyChangedV3 {
|
|
37
|
-
type: "policy";
|
|
38
|
-
policy?: DeviceLocalPolicySummary;
|
|
39
|
-
ownerCeiling: DeviceOwnerCeilingV3;
|
|
40
|
-
}
|
|
41
|
-
export interface DeviceHelloV3 extends DeviceHello {
|
|
42
|
-
protocol: 3;
|
|
43
|
-
permissionSupport: SandboxPermissionSupport;
|
|
44
|
-
ownerCeiling: DeviceOwnerCeilingV3;
|
|
45
|
-
instanceGeneration: string | null;
|
|
46
|
-
transport: {
|
|
47
|
-
maxFrameBytes: number;
|
|
48
|
-
};
|
|
49
|
-
/** Absent until the program can attest actual installed runtime/helper/environment bytes. */
|
|
50
|
-
runtimeIdentity?: DeviceRuntimeIdentityV3;
|
|
51
|
-
}
|
|
52
|
-
/** A verified installed runtime/helper/environment identity bound to one instance generation. */
|
|
53
|
-
export interface DeviceRuntimeIdentityV3 {
|
|
54
|
-
runtimeHash: string;
|
|
55
|
-
helperHash: string;
|
|
56
|
-
imageFingerprint: string;
|
|
57
|
-
instanceGeneration: string;
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Private lifecycle request (permission runtime cutover B4): binds the kernel's committed instance
|
|
61
|
-
* generation to the device after commit. It carries no path, policy or manifest.
|
|
62
|
-
*/
|
|
63
|
-
export interface BindInstanceRequestV3 {
|
|
64
|
-
instanceId: string;
|
|
65
|
-
instanceGeneration: string;
|
|
66
|
-
bindingId: string;
|
|
67
|
-
expectedPreviousGeneration: string | null;
|
|
68
|
-
}
|
|
69
|
-
export interface BindInstanceResultV3 {
|
|
70
|
-
instanceId: string;
|
|
71
|
-
instanceGeneration: string;
|
|
72
|
-
bindingId: string;
|
|
73
|
-
runtimeIdentity: DeviceRuntimeIdentityV3;
|
|
74
|
-
permissionSupport: SandboxPermissionSupport;
|
|
75
|
-
ownerCeiling: DeviceOwnerCeilingV3;
|
|
76
|
-
}
|
|
77
|
-
export interface KernelReadyV3 {
|
|
78
|
-
type: "ready";
|
|
79
|
-
connectionId: string;
|
|
80
|
-
maxFrameBytes: number;
|
|
81
|
-
}
|
|
82
|
-
export interface BackgroundReadOutputRequestV3 {
|
|
83
|
-
offset: number;
|
|
84
|
-
maxBytes: number;
|
|
85
|
-
}
|
|
86
|
-
export type BackgroundReadOutputResultV3 = {
|
|
87
|
-
dataB64: string;
|
|
88
|
-
offset: number;
|
|
89
|
-
nextOffset: number;
|
|
90
|
-
totalBytes: number;
|
|
91
|
-
} | {
|
|
92
|
-
unavailable: "lost" | "expired";
|
|
93
|
-
};
|
|
94
|
-
export interface KernelRequestV3 {
|
|
95
|
-
type: "req";
|
|
96
|
-
id: string;
|
|
97
|
-
op: DeviceOperationV3;
|
|
98
|
-
args: Readonly<Record<string, unknown>>;
|
|
99
|
-
deadlineMs: number;
|
|
100
|
-
}
|
|
101
|
-
export type DeviceResponseV3 = Exclude<DeviceRes, {
|
|
102
|
-
ok: false;
|
|
103
|
-
}> | {
|
|
104
|
-
type: "res";
|
|
105
|
-
id: string;
|
|
106
|
-
ok: false;
|
|
107
|
-
error: {
|
|
108
|
-
kind: "gone" | "fs_gone" | "policy" | "error" | "denied" | "unsupported" | "unknown";
|
|
109
|
-
message: string;
|
|
110
|
-
};
|
|
111
|
-
};
|
|
112
|
-
export type DeviceFrameV3 = DeviceHelloV3 | KernelReadyV3 | KernelRequestV3 | KernelCancel | DeviceResponseV3 | DevicePolicyChangedV3;
|
|
113
|
-
/** Strictly parses one authenticated owner-ceiling report (B2); throws {@link DeviceProtocolError}. */
|
|
114
|
-
export declare function parseOwnerCeilingReportV3(value: unknown): DeviceOwnerCeilingV3;
|
|
115
|
-
/** Strict scope-bearing frames; active parseDeviceFrame still speaks v2. */
|
|
116
|
-
export declare function parseDeviceFrameV3(raw: string, from: "device" | "kernel", maxFrameBytes?: number): DeviceFrameV3;
|
|
117
|
-
export declare function parseOperationResultV3(op: DeviceOperationV3, result: unknown, request?: BackgroundReadOutputRequestV3 | BindInstanceRequestV3): unknown;
|
|
@@ -1,409 +0,0 @@
|
|
|
1
|
-
/** Development staging only. Task 8 replaces v2 and removes this module and its staged names together. */
|
|
2
|
-
import { DeviceProtocolError, parseDeviceFrame, parseOpResult, } from "./device-protocol.js";
|
|
3
|
-
import { validateAllowHost, validateSandboxPathShape } from "./sandbox.js";
|
|
4
|
-
import { parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationRef, parseSandboxOperationScope, parseSandboxPreparationScope, } from "./sandbox-operation.js";
|
|
5
|
-
export const STAGED_DEVICE_PROTOCOL_VERSION = 3;
|
|
6
|
-
const object = (value) => {
|
|
7
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
8
|
-
throw new DeviceProtocolError("Expected an object");
|
|
9
|
-
return value;
|
|
10
|
-
};
|
|
11
|
-
function keys(value, allowed) {
|
|
12
|
-
for (const key of Object.keys(value))
|
|
13
|
-
if (!allowed.includes(key))
|
|
14
|
-
throw new DeviceProtocolError(`Unknown field ${key}`);
|
|
15
|
-
}
|
|
16
|
-
function string(value, max = 128) {
|
|
17
|
-
if (typeof value !== "string" || !value.length || value.length > max)
|
|
18
|
-
throw new DeviceProtocolError("Expected a bounded nonempty string");
|
|
19
|
-
return value;
|
|
20
|
-
}
|
|
21
|
-
function integer(value, min = 0, max = Number.MAX_SAFE_INTEGER) {
|
|
22
|
-
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)
|
|
23
|
-
throw new DeviceProtocolError("Expected a bounded integer");
|
|
24
|
-
return value;
|
|
25
|
-
}
|
|
26
|
-
function path(value) {
|
|
27
|
-
if (typeof value !== "string" || validateSandboxPathShape(value).length)
|
|
28
|
-
throw new DeviceProtocolError("Expected an absolute filesystem path");
|
|
29
|
-
}
|
|
30
|
-
function freeze(value) {
|
|
31
|
-
if (value !== null && typeof value === "object") {
|
|
32
|
-
for (const v of Object.values(value))
|
|
33
|
-
freeze(v);
|
|
34
|
-
Object.freeze(value);
|
|
35
|
-
}
|
|
36
|
-
return value;
|
|
37
|
-
}
|
|
38
|
-
function support(value) {
|
|
39
|
-
const o = object(value);
|
|
40
|
-
keys(o, ["version", "restricted", "fullAccess", "background", "unavailableReason"]);
|
|
41
|
-
if (o.version !== 1 || typeof o.fullAccess !== "boolean" || typeof o.background !== "boolean")
|
|
42
|
-
throw new DeviceProtocolError("Invalid runtime permission report");
|
|
43
|
-
if (o.restricted !== null) {
|
|
44
|
-
const r = object(o.restricted);
|
|
45
|
-
keys(r, ["filesystem", "network", "native", "concurrentScopes"]);
|
|
46
|
-
for (const k of ["filesystem", "network", "native", "concurrentScopes"])
|
|
47
|
-
if (r[k] !== true)
|
|
48
|
-
throw new DeviceProtocolError("Incomplete restricted runtime report");
|
|
49
|
-
}
|
|
50
|
-
if (o.unavailableReason !== undefined)
|
|
51
|
-
string(o.unavailableReason, 4096);
|
|
52
|
-
return o;
|
|
53
|
-
}
|
|
54
|
-
/** Strictly parses one authenticated owner-ceiling report (B2); throws {@link DeviceProtocolError}. */
|
|
55
|
-
export function parseOwnerCeilingReportV3(value) {
|
|
56
|
-
return freeze(structuredClone(owner(value)));
|
|
57
|
-
}
|
|
58
|
-
function narrowing(value) {
|
|
59
|
-
const o = object(value);
|
|
60
|
-
keys(o, ["fullAccess", "restrictedProjectReach"]);
|
|
61
|
-
if ((o.fullAccess !== undefined && o.fullAccess !== false) ||
|
|
62
|
-
(o.restrictedProjectReach !== undefined && o.restrictedProjectReach !== "workspace"))
|
|
63
|
-
throw new DeviceProtocolError("The deployment may only narrow the owner ceiling");
|
|
64
|
-
return o;
|
|
65
|
-
}
|
|
66
|
-
function owner(value) {
|
|
67
|
-
const o = object(value);
|
|
68
|
-
keys(o, [
|
|
69
|
-
"version",
|
|
70
|
-
"sequence",
|
|
71
|
-
"revision",
|
|
72
|
-
"fullAccess",
|
|
73
|
-
"restrictedProjectReach",
|
|
74
|
-
"restrictedAllowedDomains",
|
|
75
|
-
]);
|
|
76
|
-
integer(o.sequence);
|
|
77
|
-
if (o.version !== 2 || !["workspace", "os-user"].includes(String(o.restrictedProjectReach)))
|
|
78
|
-
throw new DeviceProtocolError("Invalid owner ceiling report version or project reach");
|
|
79
|
-
string(o.revision, 512);
|
|
80
|
-
if (typeof o.fullAccess !== "boolean" ||
|
|
81
|
-
!Array.isArray(o.restrictedAllowedDomains) ||
|
|
82
|
-
o.restrictedAllowedDomains.length > 100 ||
|
|
83
|
-
o.restrictedAllowedDomains.some((h) => typeof h !== "string" || validateAllowHost(h).length))
|
|
84
|
-
throw new DeviceProtocolError("Invalid owner ceiling");
|
|
85
|
-
return o;
|
|
86
|
-
}
|
|
87
|
-
const GENERATION = /^[0-9]{1,16}$/;
|
|
88
|
-
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
89
|
-
function generation(value) {
|
|
90
|
-
if (typeof value !== "string" || !GENERATION.test(value))
|
|
91
|
-
throw new DeviceProtocolError("Expected an instance generation");
|
|
92
|
-
return value;
|
|
93
|
-
}
|
|
94
|
-
function bindRequest(a) {
|
|
95
|
-
string(a.instanceId);
|
|
96
|
-
generation(a.instanceGeneration);
|
|
97
|
-
if (typeof a.bindingId !== "string" || !UUID.test(a.bindingId))
|
|
98
|
-
throw new DeviceProtocolError("Expected a binding id");
|
|
99
|
-
if (a.expectedPreviousGeneration !== null) {
|
|
100
|
-
generation(a.expectedPreviousGeneration);
|
|
101
|
-
if (BigInt(a.expectedPreviousGeneration) >= BigInt(a.instanceGeneration))
|
|
102
|
-
throw new DeviceProtocolError("Previous generation must precede the bound generation");
|
|
103
|
-
}
|
|
104
|
-
return a;
|
|
105
|
-
}
|
|
106
|
-
function identity(value) {
|
|
107
|
-
const o = object(value);
|
|
108
|
-
keys(o, ["runtimeHash", "helperHash", "imageFingerprint", "instanceGeneration"]);
|
|
109
|
-
for (const key of ["runtimeHash", "helperHash", "imageFingerprint"])
|
|
110
|
-
if (typeof o[key] !== "string" || !/^[a-f0-9]{64}$/.test(o[key]))
|
|
111
|
-
throw new DeviceProtocolError("Incomplete runtime identity");
|
|
112
|
-
string(o.instanceGeneration);
|
|
113
|
-
return o;
|
|
114
|
-
}
|
|
115
|
-
const natives = ["exec", "readFile", "writeFile", "stat", "list", "scan"];
|
|
116
|
-
const legacy = ["create", "stop", "policy", "policyStatus"];
|
|
117
|
-
function request(o) {
|
|
118
|
-
keys(o, ["type", "id", "op", "args", "deadlineMs"]);
|
|
119
|
-
const id = string(o.id), op = string(o.op), a = object(o.args), deadlineMs = integer(o.deadlineMs, 1);
|
|
120
|
-
if (legacy.includes(op)) {
|
|
121
|
-
if (op === "policy" && a.ownerCeiling !== undefined)
|
|
122
|
-
narrowing(a.ownerCeiling);
|
|
123
|
-
const parsed = parseDeviceFrame(JSON.stringify(o), "kernel");
|
|
124
|
-
if (parsed.type !== "req")
|
|
125
|
-
throw new DeviceProtocolError("Expected request");
|
|
126
|
-
return freeze({ ...parsed, op: op, args: object(parsed.args) });
|
|
127
|
-
}
|
|
128
|
-
if (op === "bindInstance") {
|
|
129
|
-
keys(a, ["instanceId", "instanceGeneration", "bindingId", "expectedPreviousGeneration"]);
|
|
130
|
-
bindRequest(a);
|
|
131
|
-
}
|
|
132
|
-
else if (op === "revokeOperation") {
|
|
133
|
-
keys(a, ["ref"]);
|
|
134
|
-
a.ref = parseSandboxOperationRef(a.ref);
|
|
135
|
-
}
|
|
136
|
-
else if (["backgroundStatus", "backgroundTail", "backgroundReadOutput", "backgroundStop"].includes(op)) {
|
|
137
|
-
keys(a, [
|
|
138
|
-
"ref",
|
|
139
|
-
...(op === "backgroundReadOutput" ? ["offset", "maxBytes"] : []),
|
|
140
|
-
...(op === "backgroundTail" ? ["maxBytes"] : op === "backgroundStop" ? ["graceMs"] : []),
|
|
141
|
-
]);
|
|
142
|
-
a.ref = parseSandboxExecutionRef(a.ref);
|
|
143
|
-
if (op === "backgroundTail" || op === "backgroundReadOutput")
|
|
144
|
-
integer(a.maxBytes, 0, 65536);
|
|
145
|
-
if (op === "backgroundReadOutput")
|
|
146
|
-
integer(a.offset);
|
|
147
|
-
if (op === "backgroundStop")
|
|
148
|
-
integer(a.graceMs, 0, 60000);
|
|
149
|
-
}
|
|
150
|
-
else {
|
|
151
|
-
const preparation = op.startsWith("prepare"), browsing = op.startsWith("browse"), background = op === "backgroundStart";
|
|
152
|
-
const method = background ? "exec" : preparation ? op.slice(7) : browsing ? op.slice(6) : op;
|
|
153
|
-
const native = method[0]?.toLowerCase() + method.slice(1);
|
|
154
|
-
if (!natives.includes(native) ||
|
|
155
|
-
(preparation && !["readFile", "writeFile", "stat"].includes(native)) ||
|
|
156
|
-
(browsing && !["stat", "list", "scan"].includes(native)))
|
|
157
|
-
throw new DeviceProtocolError("Unknown operation");
|
|
158
|
-
a.scope = preparation
|
|
159
|
-
? parseSandboxPreparationScope(a.scope)
|
|
160
|
-
: browsing
|
|
161
|
-
? parseSandboxBrowseScope(a.scope)
|
|
162
|
-
: parseSandboxOperationScope(a.scope);
|
|
163
|
-
const fields = native === "exec"
|
|
164
|
-
? ["command", "cwd", "env", "timeoutMs", "maxOutputBytes", "limits", "grants"]
|
|
165
|
-
: native === "readFile"
|
|
166
|
-
? ["path", "maxBytes"]
|
|
167
|
-
: native === "writeFile"
|
|
168
|
-
? ["path", "dataB64"]
|
|
169
|
-
: native === "stat"
|
|
170
|
-
? ["path"]
|
|
171
|
-
: native === "list"
|
|
172
|
-
? ["path", "limit"]
|
|
173
|
-
: ["base"];
|
|
174
|
-
keys(a, ["scope", ...fields, ...(background ? ["taskId", "outputPath", "retainUntilMs"] : [])]);
|
|
175
|
-
if (native !== "exec")
|
|
176
|
-
path(a[native === "scan" ? "base" : "path"]);
|
|
177
|
-
const validated = { ...a };
|
|
178
|
-
delete validated.scope;
|
|
179
|
-
if (native === "exec") {
|
|
180
|
-
const scope = parseSandboxOperationScope(a.scope);
|
|
181
|
-
validated.tag = scope.tag;
|
|
182
|
-
validated.actor = scope.actor;
|
|
183
|
-
if (background) {
|
|
184
|
-
string(a.taskId);
|
|
185
|
-
path(a.outputPath);
|
|
186
|
-
integer(a.retainUntilMs, scope.admitBeforeMs);
|
|
187
|
-
delete validated.taskId;
|
|
188
|
-
delete validated.outputPath;
|
|
189
|
-
delete validated.retainUntilMs;
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
else if (native !== "writeFile")
|
|
193
|
-
validated.limits = { mode: "sandbox" };
|
|
194
|
-
// Reuse v2's pure value guards; inserted mode is never returned or used as authority.
|
|
195
|
-
parseDeviceFrame(JSON.stringify({ type: "req", id, op: native, args: validated, deadlineMs }), "kernel");
|
|
196
|
-
if (native === "writeFile" &&
|
|
197
|
-
(typeof a.dataB64 !== "string" ||
|
|
198
|
-
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a.dataB64)))
|
|
199
|
-
throw new DeviceProtocolError("Invalid base64 payload");
|
|
200
|
-
}
|
|
201
|
-
return freeze({ type: "req", id, op: op, args: a, deadlineMs });
|
|
202
|
-
}
|
|
203
|
-
/** Strict scope-bearing frames; active parseDeviceFrame still speaks v2. */
|
|
204
|
-
export function parseDeviceFrameV3(raw, from, maxFrameBytes) {
|
|
205
|
-
if (maxFrameBytes !== undefined &&
|
|
206
|
-
new TextEncoder().encode(raw).byteLength > integer(maxFrameBytes, 1))
|
|
207
|
-
throw new DeviceProtocolError("Frame exceeds negotiated capacity; check device and deployment frame limits");
|
|
208
|
-
let parsed;
|
|
209
|
-
try {
|
|
210
|
-
parsed = JSON.parse(raw);
|
|
211
|
-
}
|
|
212
|
-
catch {
|
|
213
|
-
throw new DeviceProtocolError("Frame is not valid JSON");
|
|
214
|
-
}
|
|
215
|
-
const o = object(parsed);
|
|
216
|
-
if (o.type === "ready") {
|
|
217
|
-
if (from !== "kernel")
|
|
218
|
-
throw new DeviceProtocolError("Ready must come from kernel");
|
|
219
|
-
keys(o, ["type", "connectionId", "maxFrameBytes"]);
|
|
220
|
-
return freeze({
|
|
221
|
-
type: "ready",
|
|
222
|
-
connectionId: string(o.connectionId),
|
|
223
|
-
maxFrameBytes: integer(o.maxFrameBytes, 1024),
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
if (o.type === "req") {
|
|
227
|
-
if (from !== "kernel")
|
|
228
|
-
throw new DeviceProtocolError("Request must come from kernel");
|
|
229
|
-
return request(o);
|
|
230
|
-
}
|
|
231
|
-
if (o.type === "hello") {
|
|
232
|
-
if (from !== "device" || o.protocol !== 3)
|
|
233
|
-
throw new DeviceProtocolError("Expected protocol 3 hello");
|
|
234
|
-
const transport = object(o.transport);
|
|
235
|
-
keys(transport, ["maxFrameBytes"]);
|
|
236
|
-
const maxFrameBytes = integer(transport.maxFrameBytes, 1024);
|
|
237
|
-
const permissionSupport = support(o.permissionSupport);
|
|
238
|
-
if (o.instanceGeneration === null &&
|
|
239
|
-
(o.runtimeIdentity !== undefined ||
|
|
240
|
-
permissionSupport.restricted !== null ||
|
|
241
|
-
permissionSupport.fullAccess ||
|
|
242
|
-
permissionSupport.background ||
|
|
243
|
-
!permissionSupport.unavailableReason))
|
|
244
|
-
throw new DeviceProtocolError("Unbound hello cannot advertise runtime capability");
|
|
245
|
-
const base = parseDeviceFrame(raw, from);
|
|
246
|
-
if (base.type !== "hello")
|
|
247
|
-
throw new DeviceProtocolError("Expected hello");
|
|
248
|
-
let runtimeIdentity;
|
|
249
|
-
if (o.runtimeIdentity !== undefined) {
|
|
250
|
-
runtimeIdentity = identity(o.runtimeIdentity);
|
|
251
|
-
if (runtimeIdentity.instanceGeneration !== string(o.instanceGeneration))
|
|
252
|
-
throw new DeviceProtocolError("Runtime identity generation mismatch");
|
|
253
|
-
}
|
|
254
|
-
return freeze({
|
|
255
|
-
...base,
|
|
256
|
-
protocol: 3,
|
|
257
|
-
permissionSupport,
|
|
258
|
-
transport: { maxFrameBytes },
|
|
259
|
-
ownerCeiling: owner(o.ownerCeiling),
|
|
260
|
-
instanceGeneration: o.instanceGeneration === null ? null : string(o.instanceGeneration),
|
|
261
|
-
...(runtimeIdentity && { runtimeIdentity }),
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
if (o.type === "policy") {
|
|
265
|
-
if (from !== "device")
|
|
266
|
-
throw new DeviceProtocolError("Policy must come from device");
|
|
267
|
-
keys(o, ["type", "policy", "ownerCeiling"]);
|
|
268
|
-
const base = parseDeviceFrame(JSON.stringify({ type: "policy", policy: o.policy }), from);
|
|
269
|
-
if (base.type !== "policy")
|
|
270
|
-
throw new DeviceProtocolError("Expected policy");
|
|
271
|
-
return freeze({ ...base, ownerCeiling: owner(o.ownerCeiling) });
|
|
272
|
-
}
|
|
273
|
-
if (o.type === "res" && o.ok === false) {
|
|
274
|
-
if (from !== "device")
|
|
275
|
-
throw new DeviceProtocolError("Response must come from device");
|
|
276
|
-
keys(o, ["type", "id", "ok", "error"]);
|
|
277
|
-
const e = object(o.error);
|
|
278
|
-
keys(e, ["kind", "message"]);
|
|
279
|
-
if (!["gone", "fs_gone", "policy", "error", "denied", "unsupported", "unknown"].includes(String(e.kind)))
|
|
280
|
-
throw new DeviceProtocolError("Unknown outcome kind");
|
|
281
|
-
return freeze({
|
|
282
|
-
type: "res",
|
|
283
|
-
id: string(o.id),
|
|
284
|
-
ok: false,
|
|
285
|
-
error: {
|
|
286
|
-
kind: e.kind,
|
|
287
|
-
message: string(e.message, 8192),
|
|
288
|
-
},
|
|
289
|
-
});
|
|
290
|
-
}
|
|
291
|
-
const base = parseDeviceFrame(raw, from);
|
|
292
|
-
if (base.type === "hello" || base.type === "req" || base.type === "policy")
|
|
293
|
-
throw new DeviceProtocolError("Expected staged frame");
|
|
294
|
-
return freeze(base);
|
|
295
|
-
}
|
|
296
|
-
export function parseOperationResultV3(op, result, request) {
|
|
297
|
-
if (op === "bindInstance") {
|
|
298
|
-
if (!request || !("bindingId" in request))
|
|
299
|
-
throw new DeviceProtocolError("Binding validation requires the exact request");
|
|
300
|
-
const o = object(result);
|
|
301
|
-
keys(o, [
|
|
302
|
-
"instanceId",
|
|
303
|
-
"instanceGeneration",
|
|
304
|
-
"bindingId",
|
|
305
|
-
"runtimeIdentity",
|
|
306
|
-
"permissionSupport",
|
|
307
|
-
"ownerCeiling",
|
|
308
|
-
]);
|
|
309
|
-
const runtimeIdentity = identity(o.runtimeIdentity);
|
|
310
|
-
if (o.instanceId !== request.instanceId ||
|
|
311
|
-
o.instanceGeneration !== request.instanceGeneration ||
|
|
312
|
-
o.bindingId !== request.bindingId ||
|
|
313
|
-
runtimeIdentity.instanceGeneration !== request.instanceGeneration)
|
|
314
|
-
throw new DeviceProtocolError("Binding answer belongs to another instance generation");
|
|
315
|
-
return freeze({
|
|
316
|
-
instanceId: request.instanceId,
|
|
317
|
-
instanceGeneration: request.instanceGeneration,
|
|
318
|
-
bindingId: request.bindingId,
|
|
319
|
-
runtimeIdentity,
|
|
320
|
-
permissionSupport: support(o.permissionSupport),
|
|
321
|
-
ownerCeiling: owner(o.ownerCeiling),
|
|
322
|
-
});
|
|
323
|
-
}
|
|
324
|
-
if (op === "backgroundReadOutput") {
|
|
325
|
-
if (!request || !("offset" in request))
|
|
326
|
-
throw new DeviceProtocolError("Output validation requires the exact request bounds");
|
|
327
|
-
const offset = integer(request.offset), maxBytes = integer(request.maxBytes, 0, 65536);
|
|
328
|
-
const o = object(result);
|
|
329
|
-
if ("unavailable" in o) {
|
|
330
|
-
keys(o, ["unavailable"]);
|
|
331
|
-
if (o.unavailable !== "lost" && o.unavailable !== "expired")
|
|
332
|
-
throw new DeviceProtocolError("Invalid output outcome");
|
|
333
|
-
return freeze(o);
|
|
334
|
-
}
|
|
335
|
-
keys(o, ["dataB64", "offset", "nextOffset", "totalBytes"]);
|
|
336
|
-
const total = integer(o.totalBytes), next = integer(o.nextOffset);
|
|
337
|
-
if (integer(o.offset) !== offset ||
|
|
338
|
-
typeof o.dataB64 !== "string" ||
|
|
339
|
-
o.dataB64.length > 87384 ||
|
|
340
|
-
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o.dataB64))
|
|
341
|
-
throw new DeviceProtocolError("Invalid output range or base64");
|
|
342
|
-
const decoded = atob(o.dataB64);
|
|
343
|
-
if (btoa(decoded) !== o.dataB64 ||
|
|
344
|
-
decoded.length !== Math.min(maxBytes, Math.max(total - offset, 0)) ||
|
|
345
|
-
!Number.isSafeInteger(offset + decoded.length) ||
|
|
346
|
-
next !== offset + decoded.length)
|
|
347
|
-
throw new DeviceProtocolError("Inconsistent output range; retry from the same offset");
|
|
348
|
-
return freeze(o);
|
|
349
|
-
}
|
|
350
|
-
if (op === "backgroundStart")
|
|
351
|
-
return parseSandboxExecutionRef(result);
|
|
352
|
-
if (op === "backgroundStatus") {
|
|
353
|
-
const o = object(result);
|
|
354
|
-
keys(o, ["state", "exitCode", "timedOut"]);
|
|
355
|
-
if (o.state === "running" || o.state === "lost")
|
|
356
|
-
return freeze({ state: o.state });
|
|
357
|
-
if (o.state !== "exited" ||
|
|
358
|
-
(o.exitCode !== null && !Number.isInteger(o.exitCode)) ||
|
|
359
|
-
typeof o.timedOut !== "boolean")
|
|
360
|
-
throw new DeviceProtocolError("Invalid execution status");
|
|
361
|
-
return freeze(o);
|
|
362
|
-
}
|
|
363
|
-
if (op === "backgroundTail") {
|
|
364
|
-
if (result && typeof result === "object" && "unavailable" in result) {
|
|
365
|
-
const o = object(result);
|
|
366
|
-
keys(o, ["unavailable"]);
|
|
367
|
-
if (o.unavailable !== "lost" && o.unavailable !== "expired")
|
|
368
|
-
throw new DeviceProtocolError("Invalid output outcome");
|
|
369
|
-
return freeze(o);
|
|
370
|
-
}
|
|
371
|
-
return parseOpResult("readFile", result);
|
|
372
|
-
}
|
|
373
|
-
if (op === "backgroundStop") {
|
|
374
|
-
const o = object(result);
|
|
375
|
-
keys(o, ["outcome", "exitCode", "timedOut"]);
|
|
376
|
-
if (!["already-exited", "stopped", "cancel-pending", "lost"].includes(String(o.outcome)))
|
|
377
|
-
throw new DeviceProtocolError("Invalid stop outcome");
|
|
378
|
-
if (o.outcome === "already-exited" &&
|
|
379
|
-
((o.exitCode !== null && !Number.isInteger(o.exitCode)) || typeof o.timedOut !== "boolean"))
|
|
380
|
-
throw new DeviceProtocolError("Invalid stopped execution status");
|
|
381
|
-
return freeze(o);
|
|
382
|
-
}
|
|
383
|
-
if (op === "policy") {
|
|
384
|
-
const o = object(result);
|
|
385
|
-
keys(o, ["policy", "ownerCeiling"]);
|
|
386
|
-
return freeze({
|
|
387
|
-
...parseOpResult("policy", { policy: o.policy }),
|
|
388
|
-
ownerCeiling: owner(o.ownerCeiling),
|
|
389
|
-
});
|
|
390
|
-
}
|
|
391
|
-
if (op === "policyStatus") {
|
|
392
|
-
const o = object(result);
|
|
393
|
-
keys(o, ["outcome", "policy", "message", "ownerCeiling"]);
|
|
394
|
-
const { ownerCeiling, ...rest } = o;
|
|
395
|
-
const status = parseOpResult("policyStatus", rest);
|
|
396
|
-
if (status.outcome === "applied" && ownerCeiling === undefined)
|
|
397
|
-
throw new DeviceProtocolError("An applied policy status carries the owner report");
|
|
398
|
-
if (ownerCeiling !== undefined)
|
|
399
|
-
status.ownerCeiling = owner(ownerCeiling);
|
|
400
|
-
return freeze(status);
|
|
401
|
-
}
|
|
402
|
-
if (op === "revokeOperation") {
|
|
403
|
-
if (result !== null)
|
|
404
|
-
throw new DeviceProtocolError("Revoke result must be null");
|
|
405
|
-
return null;
|
|
406
|
-
}
|
|
407
|
-
const raw = op.startsWith("prepare") ? op.slice(7) : op.startsWith("browse") ? op.slice(6) : op;
|
|
408
|
-
return parseOpResult((raw.charAt(0).toLowerCase() + raw.slice(1)), result);
|
|
409
|
-
}
|