@eum-agent/sandbox 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1136 -0
- package/package.json +52 -3
- package/ui/ui.js +1273 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1136 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { isAbsolute, normalize, parse, posix, win32 } from "node:path";
|
|
5
|
+
//#region src/path-semantics.ts
|
|
6
|
+
/** Host path syntax used by runtime callers; URI and wire paths do not use this module. */
|
|
7
|
+
/** Chooses path operations from an explicit host fact, independently of the test runner. */
|
|
8
|
+
function pathsFor(platform = process.platform) {
|
|
9
|
+
return platform === "win32" ? win32 : posix;
|
|
10
|
+
}
|
|
11
|
+
/** Accepts POSIX roots or complete Windows drive/UNC roots; rejects NUL and implicit drives. */
|
|
12
|
+
function isCompleteAbsolute(path, paths = pathsFor()) {
|
|
13
|
+
if (path.includes("\0")) return false;
|
|
14
|
+
if (paths !== win32) return paths.isAbsolute(path);
|
|
15
|
+
if (/^[a-z]:[\\/]/i.test(path)) return true;
|
|
16
|
+
const unc = /^[/\\]{2}([^/\\]+)[/\\]([^/\\]+)(?:[/\\]|$)/.exec(path);
|
|
17
|
+
return unc !== null && ![
|
|
18
|
+
".",
|
|
19
|
+
"..",
|
|
20
|
+
"?"
|
|
21
|
+
].includes(unc[1] ?? "") && ![".", ".."].includes(unc[2] ?? "");
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Contains canonical absolute paths by exact normalized segments.
|
|
25
|
+
* Windows drive syntax is normalized; object names never undergo case folding.
|
|
26
|
+
* This lexical check does not replace real-path resolution or safe file opening.
|
|
27
|
+
*/
|
|
28
|
+
function containsPath(root, path, paths = pathsFor()) {
|
|
29
|
+
if (!isCompleteAbsolute(root, paths) || !isCompleteAbsolute(path, paths)) return false;
|
|
30
|
+
const parts = (value) => {
|
|
31
|
+
const normalized = paths.normalize(value);
|
|
32
|
+
const root = paths.parse(normalized).root;
|
|
33
|
+
return {
|
|
34
|
+
root: paths === win32 ? root.replace(/^[a-z]:/i, (drive) => drive.toUpperCase()) : root,
|
|
35
|
+
segments: normalized.slice(root.length).split(paths.sep).filter(Boolean)
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
const base = parts(root);
|
|
39
|
+
const target = parts(path);
|
|
40
|
+
return base.root === target.root && base.segments.length <= target.segments.length && base.segments.every((segment, index) => segment === target.segments[index]);
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/paths.ts
|
|
44
|
+
const MAX_LINK_HOPS = 40;
|
|
45
|
+
/** Resolves existing physical objects and follows dangling links without assuming absence. */
|
|
46
|
+
function resolveThroughExisting(path, host) {
|
|
47
|
+
const paths = pathsFor(host.process.platform);
|
|
48
|
+
if (path.includes("\0") || host.process.platform === "win32" && (/^[a-z]:/i.test(path) || /^[\\/]/.test(path)) && !isCompleteAbsolute(path, paths)) throw new Error(`path must name a complete absolute root: ${path}`);
|
|
49
|
+
const { basename, dirname, resolve } = paths;
|
|
50
|
+
return resolveWithHops(path, 0);
|
|
51
|
+
/** `resolveThroughExisting`, carrying the links already followed on the way
|
|
52
|
+
* here. A cycle stops when that count reaches `MAX_LINK_HOPS`. */
|
|
53
|
+
function resolveWithHops(path, hops) {
|
|
54
|
+
let candidate = resolve(host.process.cwd(), path);
|
|
55
|
+
const rest = [];
|
|
56
|
+
while (true) {
|
|
57
|
+
const real = realPathOf(candidate, hops);
|
|
58
|
+
if (real !== void 0) return rest.length === 0 ? real : resolve(real, ...rest);
|
|
59
|
+
const parent = dirname(candidate);
|
|
60
|
+
if (parent === candidate) throw new Error(`could not resolve existing path root: ${candidate}`);
|
|
61
|
+
rest.unshift(basename(candidate));
|
|
62
|
+
candidate = parent;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* `path` with every symlink on it followed, or `undefined` when nothing is
|
|
67
|
+
* there under that name.
|
|
68
|
+
*
|
|
69
|
+
* `host.fs.realpathSync` reports two different situations with one error — a path
|
|
70
|
+
* that does not exist, and a symlink whose target does not exist — and the
|
|
71
|
+
* second must not be read as the first. Reading it as "nothing here" ends the
|
|
72
|
+
* upward walk at the link's parent and answers with the link's own name,
|
|
73
|
+
* which is a name in whatever directory the link happens to sit in while the
|
|
74
|
+
* bytes would land wherever it points. So the link is followed by hand: its
|
|
75
|
+
* target is taken as written, resolved against its parent's real path, and
|
|
76
|
+
* put through the same walk.
|
|
77
|
+
*/
|
|
78
|
+
function realPathOf(path, hops) {
|
|
79
|
+
try {
|
|
80
|
+
return host.fs.realpathSync(path);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error.code !== "ENOENT") throw error;
|
|
83
|
+
}
|
|
84
|
+
if (hops >= MAX_LINK_HOPS) throw new Error("too many symbolic links in path");
|
|
85
|
+
let target;
|
|
86
|
+
try {
|
|
87
|
+
if (!host.fs.lstatSync(path).isSymbolicLink()) throw new Error(`could not resolve existing path: ${path}`);
|
|
88
|
+
target = host.fs.readlinkSync(path);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (error.code === "ENOENT") return void 0;
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
const parent = dirname(path);
|
|
94
|
+
const base = parent === path ? parent : resolveWithHops(parent, hops + 1);
|
|
95
|
+
return resolveWithHops(resolve(base, target), hops + 1);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function isWithin(root, path, paths = pathsFor()) {
|
|
99
|
+
return containsPath(root, path, paths);
|
|
100
|
+
}
|
|
101
|
+
//#endregion
|
|
102
|
+
//#region src/readable.ts
|
|
103
|
+
/** Manual read roots are resolved independently of owner-provided preset permissions. */
|
|
104
|
+
/**
|
|
105
|
+
* The list as a plan uses it: real paths, in order, without the entries that
|
|
106
|
+
* are not on this machine.
|
|
107
|
+
*
|
|
108
|
+
* Resolved through symlinks because everything a plan compares against is a
|
|
109
|
+
* real path, and because `/private/etc` and `/etc` have to end up as one
|
|
110
|
+
* entry rather than two rules that disagree. A missing entry is skipped
|
|
111
|
+
* rather than refused; a missing manual root contributes no permission.
|
|
112
|
+
*/
|
|
113
|
+
function resolveReadablePaths(paths, host) {
|
|
114
|
+
const resolved = [];
|
|
115
|
+
for (const path of paths) {
|
|
116
|
+
if (!isAbsolute(path)) continue;
|
|
117
|
+
if (!host.fs.existsSync(path)) continue;
|
|
118
|
+
resolved.push(host.fs.realpathSync(path));
|
|
119
|
+
}
|
|
120
|
+
return dedupe(resolved);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Why this path cannot join the readable list, or `undefined` when it can.
|
|
124
|
+
*
|
|
125
|
+
* The same check serves the management method and the `allowed-always` half
|
|
126
|
+
* of a permission: a person widening the list from
|
|
127
|
+
* a settings page and a person answering "allow and remember" are granting
|
|
128
|
+
* the same thing, so one of them being able to name the token directory and
|
|
129
|
+
* the other not would be the hole. Phrased like the fence's own refusals, in
|
|
130
|
+
* the same direction as `workspace add-dir`'s.
|
|
131
|
+
*/
|
|
132
|
+
function readablePathRefusal(path, protectedPaths, host) {
|
|
133
|
+
if (!isAbsolute(path)) return `readable path must be absolute: ${path}`;
|
|
134
|
+
const real = resolveThroughExisting(path, host);
|
|
135
|
+
const sealedRoot = (protectedPaths.sealed ?? []).find((dir) => isWithin(dir, real));
|
|
136
|
+
if (sealedRoot !== void 0) return `${path} is inside yaoguang's own state directory (${sealedRoot}), which no readable path can cover`;
|
|
137
|
+
}
|
|
138
|
+
/** Insertion order, first occurrence wins — the order a person wrote the
|
|
139
|
+
* list in is the order they read it back in. */
|
|
140
|
+
function dedupe(paths) {
|
|
141
|
+
return [...new Set(paths)];
|
|
142
|
+
}
|
|
143
|
+
//#endregion
|
|
144
|
+
//#region src/targets.ts
|
|
145
|
+
/** Canonical loopback host forms share machine-wide TCP port grants. */
|
|
146
|
+
function isLocalHost(host) {
|
|
147
|
+
return [
|
|
148
|
+
"localhost",
|
|
149
|
+
"127.0.0.1",
|
|
150
|
+
"::1"
|
|
151
|
+
].includes(host);
|
|
152
|
+
}
|
|
153
|
+
/** Validates exact argv and a complete physical working directory. */
|
|
154
|
+
function commandTarget(target, host) {
|
|
155
|
+
if (!isCompleteAbsolute(target.cwd, pathsFor(host.process.platform)) || !target.argv.length || !target.argv[0] || target.argv.some((arg) => arg.includes("\0"))) throw new Error("invalid-authorization: invalid command argv or cwd");
|
|
156
|
+
return {
|
|
157
|
+
argv: [...target.argv],
|
|
158
|
+
cwd: resolveThroughExisting(target.cwd, host)
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/authorize.ts
|
|
163
|
+
/** External hosts are purpose declarations, never address restrictions for shell processes. */
|
|
164
|
+
const NETWORK_WARNING = "External access permits any outside address; declared hosts are not enforced. Remembered resource permissions apply globally. Local connections and listening use independent policies; the resident gateway stays blocked.";
|
|
165
|
+
/** Seatbelt enforces a listening port, but cannot enforce a loopback binding address. */
|
|
166
|
+
const LISTEN_WARNING = "Listening is authorized by TCP port. Bind the service to 127.0.0.1 or ::1 yourself; wildcard bindings (0.0.0.0 / ::) may expose it to the LAN. Seatbelt cannot enforce this address restriction.";
|
|
167
|
+
/** Returns one reentrant decision; lasting grants are committed together before granting execution. */
|
|
168
|
+
function createAuthorize(deps) {
|
|
169
|
+
const host = deps.host;
|
|
170
|
+
const ask = deps.approval;
|
|
171
|
+
return function authorize(ctx, permissions, reason, execution, mode = "sandboxed", fallbackReason) {
|
|
172
|
+
if (!deps.available()) return {
|
|
173
|
+
kind: "refused",
|
|
174
|
+
reason: "policy",
|
|
175
|
+
message: "Authorization strategy is unavailable. Nothing ran."
|
|
176
|
+
};
|
|
177
|
+
let command;
|
|
178
|
+
try {
|
|
179
|
+
command = commandTarget({
|
|
180
|
+
argv: [...execution.argv],
|
|
181
|
+
cwd: execution.cwd
|
|
182
|
+
}, host);
|
|
183
|
+
} catch (error) {
|
|
184
|
+
return {
|
|
185
|
+
kind: "refused",
|
|
186
|
+
reason: "policy",
|
|
187
|
+
message: String(error)
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
const policies = deps.policies();
|
|
191
|
+
const files = mode === "direct" ? [] : [...(permissions.read ?? []).map((path) => ({
|
|
192
|
+
kind: "file",
|
|
193
|
+
path: resolveThroughExisting(path, host),
|
|
194
|
+
operations: ["read"]
|
|
195
|
+
})), ...(permissions.write ?? []).map((path) => ({
|
|
196
|
+
kind: "file",
|
|
197
|
+
path: resolveThroughExisting(path, host),
|
|
198
|
+
operations: ["write"]
|
|
199
|
+
}))];
|
|
200
|
+
const locals = mode === "direct" ? [] : [...(permissions.connect ?? []).map((item) => ({
|
|
201
|
+
kind: "host",
|
|
202
|
+
...item,
|
|
203
|
+
operations: ["connect"]
|
|
204
|
+
})), ...(permissions.listen ?? []).map((item) => ({
|
|
205
|
+
kind: "host",
|
|
206
|
+
...item,
|
|
207
|
+
operations: ["listen"]
|
|
208
|
+
}))];
|
|
209
|
+
try {
|
|
210
|
+
for (const input of locals) deps.validateTarget(input);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
return {
|
|
213
|
+
kind: "refused",
|
|
214
|
+
reason: "policy",
|
|
215
|
+
message: String(error)
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
if (mode === "sandboxed" && (permissions.connect ?? []).some((item) => item.port !== "any" && deps.protectedPorts().includes(item.port))) return {
|
|
219
|
+
kind: "refused",
|
|
220
|
+
reason: "policy",
|
|
221
|
+
message: "The resident gateway connection is protected."
|
|
222
|
+
};
|
|
223
|
+
const wantsExternal = mode === "sandboxed" && (permissions.network?.length ?? 0) > 0;
|
|
224
|
+
if (mode === "sandboxed" && (wantsExternal && policies.external === "deny" || (permissions.connect?.length ?? 0) > 0 && policies.connect === "deny" || (permissions.listen?.length ?? 0) > 0 && policies.listen === "deny")) return {
|
|
225
|
+
kind: "refused",
|
|
226
|
+
reason: "policy",
|
|
227
|
+
message: "The requested sandbox network capability is denied by its policy."
|
|
228
|
+
};
|
|
229
|
+
const toolInputs = files.filter((input) => input.kind === "file" && !deps.access.holds(ctx.address, ctx.sessionId, input.path, input.operations[0]) && !(input.operations[0] === "read" && deps.access.holds(ctx.address, ctx.sessionId, input.path, "write")));
|
|
230
|
+
if (!deps.access.holdsCommand(command)) toolInputs.unshift({
|
|
231
|
+
kind: "command",
|
|
232
|
+
...command
|
|
233
|
+
});
|
|
234
|
+
const networkInputs = locals.filter((input) => input.kind === "host" && policies[input.operations[0]] === "ask" && !deps.access.holdsHost(input.host, input.port, input.operations[0]));
|
|
235
|
+
const external = wantsExternal && policies.external === "ask" && !deps.access.holdsNetwork(ctx.address, ctx.sessionId);
|
|
236
|
+
const defaultPolicy = deps.defaultPolicy();
|
|
237
|
+
if (toolInputs.length && defaultPolicy === "deny") return {
|
|
238
|
+
kind: "refused",
|
|
239
|
+
reason: "policy",
|
|
240
|
+
message: "The default authorization policy refuses this command or file access."
|
|
241
|
+
};
|
|
242
|
+
const inputs = [...defaultPolicy === "ask" ? toolInputs : [], ...networkInputs];
|
|
243
|
+
const id = `sandbox:${host.crypto.createHash("sha256").update(JSON.stringify({
|
|
244
|
+
mode,
|
|
245
|
+
fallbackReason,
|
|
246
|
+
command,
|
|
247
|
+
files,
|
|
248
|
+
locals,
|
|
249
|
+
externalPurpose: mode === "direct" ? [] : permissions.network ?? []
|
|
250
|
+
})).digest("hex")}`;
|
|
251
|
+
if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === ask.questionId(id))) return {
|
|
252
|
+
kind: "refused",
|
|
253
|
+
reason: "rejected",
|
|
254
|
+
message: "stale-approval: the execution or requested resources changed."
|
|
255
|
+
};
|
|
256
|
+
if (!inputs.length && !external) return { kind: "granted" };
|
|
257
|
+
const targets = inputs.map((input) => input.kind === "file" ? {
|
|
258
|
+
access: input.operations[0],
|
|
259
|
+
target: input.path
|
|
260
|
+
} : input.kind === "host" ? {
|
|
261
|
+
access: input.operations[0],
|
|
262
|
+
target: `${input.host}:${input.port}`
|
|
263
|
+
} : {
|
|
264
|
+
access: "execute",
|
|
265
|
+
target: `${JSON.stringify(input.argv)} in ${input.cwd}`
|
|
266
|
+
});
|
|
267
|
+
if (external) targets.push({
|
|
268
|
+
access: "network",
|
|
269
|
+
target: "All outside addresses"
|
|
270
|
+
});
|
|
271
|
+
const decision = ask.decide(ctx, {
|
|
272
|
+
id,
|
|
273
|
+
subject: targets.map((target) => `${target.access} ${target.target}`).join("; "),
|
|
274
|
+
targets,
|
|
275
|
+
reason,
|
|
276
|
+
accepts: [
|
|
277
|
+
"allowed-once",
|
|
278
|
+
"allowed-always",
|
|
279
|
+
"rejected"
|
|
280
|
+
],
|
|
281
|
+
globalResource: true,
|
|
282
|
+
warning: mode === "direct" ? `${fallbackReason ? `The preferred sandbox is unavailable: ${fallbackReason}.` : "Shell sandbox is disabled."} This command runs with host permissions, without YaoGuang file, network, sealed-state or gateway isolation; resource declarations do not confine it or create resource grants. Inherited outer restrictions still apply.` : [NETWORK_WARNING, ...permissions.listen?.length ? [LISTEN_WARNING] : []].join("\n")
|
|
283
|
+
});
|
|
284
|
+
if (decision.kind === "ask") return {
|
|
285
|
+
kind: "ask",
|
|
286
|
+
result: decision.result
|
|
287
|
+
};
|
|
288
|
+
const result = decision.result;
|
|
289
|
+
if (result.kind === "allowed-once") return { kind: "granted" };
|
|
290
|
+
if (result.kind === "allowed-always") try {
|
|
291
|
+
deps.access.recordResources(inputs, external);
|
|
292
|
+
return { kind: "granted" };
|
|
293
|
+
} catch (error) {
|
|
294
|
+
return {
|
|
295
|
+
kind: "refused",
|
|
296
|
+
reason: "record-failed",
|
|
297
|
+
message: `Recording permission failed: ${String(error)}. Nothing ran.`
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
kind: "refused",
|
|
302
|
+
reason: "rejected",
|
|
303
|
+
message: result.kind === "rejected" && result.reason ? `Permission refused: ${result.reason}` : "Permission refused by the person."
|
|
304
|
+
};
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
//#endregion
|
|
308
|
+
//#region src/local-ports.ts
|
|
309
|
+
/** Owns the actual gateway port, and refreshes all network decisions before spawning. */
|
|
310
|
+
function createSandboxNetwork(config, access, changed) {
|
|
311
|
+
let gatewayPort;
|
|
312
|
+
function protectedPorts() {
|
|
313
|
+
return gatewayPort === void 0 ? [] : [gatewayPort];
|
|
314
|
+
}
|
|
315
|
+
function effective(permissions = {}, triggerExternal = false) {
|
|
316
|
+
const policies = config.networkPolicies();
|
|
317
|
+
const local = (operation) => {
|
|
318
|
+
if (gatewayPort === void 0 || policies[operation] === "deny") return [];
|
|
319
|
+
if (policies[operation] === "allow") return ["any"];
|
|
320
|
+
return [.../* @__PURE__ */ new Set([...(access?.list() ?? []).flatMap((row) => row.kind === "host" && row.effective && isLocalHost(row.target.host) && row.target.operation === operation ? [row.target.port] : []), ...(permissions[operation] ?? []).map((item) => item.port)])].filter((port) => operation !== "connect" || port !== gatewayPort);
|
|
321
|
+
};
|
|
322
|
+
return {
|
|
323
|
+
connectAllow: local("connect"),
|
|
324
|
+
listenAllow: local("listen"),
|
|
325
|
+
protectedLocalPorts: protectedPorts(),
|
|
326
|
+
externalAllowed: policies.external !== "deny" && (policies.external === "allow" || triggerExternal || (permissions.network?.length ?? 0) > 0)
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
protectedPorts,
|
|
331
|
+
effective,
|
|
332
|
+
/** Registers one port for this runtime; no local capability exists before registration. */
|
|
333
|
+
bind(port) {
|
|
334
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid gateway port");
|
|
335
|
+
if (gatewayPort === port) return;
|
|
336
|
+
if (gatewayPort !== void 0) throw new Error("The runtime already has a gateway port");
|
|
337
|
+
gatewayPort = port;
|
|
338
|
+
changed();
|
|
339
|
+
},
|
|
340
|
+
/** Refreshes against current policy and shared grants; running processes retain their profile. */
|
|
341
|
+
refresh(plan) {
|
|
342
|
+
const current = effective(plan.requested);
|
|
343
|
+
return {
|
|
344
|
+
...plan,
|
|
345
|
+
...current,
|
|
346
|
+
proxyEnvironment: gatewayPort === void 0 || !current.externalAllowed ? {} : plan.proxyEnvironment
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
//#endregion
|
|
352
|
+
//#region src/plan.ts
|
|
353
|
+
/**
|
|
354
|
+
* Where a sandboxed command's rules come from.
|
|
355
|
+
*
|
|
356
|
+
* Nothing here is stored. One call's rules are derived from three things —
|
|
357
|
+
* this workspace's directories and global grants, the readable-path list, and
|
|
358
|
+
* the permissions this one call asked for — and thrown away afterwards. That
|
|
359
|
+
* is what keeps the shell's boundary and `fs_write`'s the same boundary:
|
|
360
|
+
* the write set *is* the fence's read-write roots, so there is no second
|
|
361
|
+
* configuration for the two to disagree about, and a directory a person
|
|
362
|
+
* authorized a second ago is in the next plan without anything being
|
|
363
|
+
* invalidated.
|
|
364
|
+
*
|
|
365
|
+
* This module is the **one** caller of `fence.roots`. A tool that derived its own rules would be a second path
|
|
366
|
+
* judgement, and a second one is a second thing to get wrong.
|
|
367
|
+
*/
|
|
368
|
+
/** `/tmp` on macOS is a symlink to this, and a command that writes through
|
|
369
|
+
* `/tmp` has to land somewhere the rules name. The per-call temporary
|
|
370
|
+
* directory is under it already; this makes the shared one readable, which
|
|
371
|
+
* is what `mktemp`-using scripts and most build tools assume. */
|
|
372
|
+
const SHARED_TMP = "/private/tmp";
|
|
373
|
+
function createSandboxPlanner(deps) {
|
|
374
|
+
const host = deps.host;
|
|
375
|
+
/** Whether a path is somewhere a command could start. A permission that names
|
|
376
|
+
* a file is honoured as a file; it is simply not a working directory. */
|
|
377
|
+
function isDirectory(path) {
|
|
378
|
+
try {
|
|
379
|
+
return host.fs.statSync(path).isDirectory();
|
|
380
|
+
} catch {
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
const sealed = (deps.sealed ?? []).map((path) => resolveThroughExisting(path, host));
|
|
385
|
+
const refreshers = /* @__PURE__ */ new WeakMap();
|
|
386
|
+
/** A permission path that no answer could ever grant, or
|
|
387
|
+
* `undefined`. Judged on the real path, so a symlink into a protected
|
|
388
|
+
* tree is caught, and judged *before* anybody is asked — the person never
|
|
389
|
+
* sees a question whose yes would not be honoured. */
|
|
390
|
+
function refuseProtected(path) {
|
|
391
|
+
if (!isAbsolute(path)) return {
|
|
392
|
+
ok: false,
|
|
393
|
+
reason: "not-absolute",
|
|
394
|
+
message: `permission paths must be absolute: ${path}. A session has no current directory, because a workspace is not a directory`
|
|
395
|
+
};
|
|
396
|
+
const real = resolveThroughExisting(path, host);
|
|
397
|
+
const sealedRoot = sealed.find((dir) => isWithin(dir, real));
|
|
398
|
+
if (sealedRoot !== void 0) return {
|
|
399
|
+
ok: false,
|
|
400
|
+
reason: "sealed",
|
|
401
|
+
message: `${path} is inside yaoguang's own state directory (${sealedRoot}) — the master key, the event log, this installation's configuration and its plugin code: no permission can cover it`
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
return {
|
|
405
|
+
refresh(plan) {
|
|
406
|
+
const refresh = refreshers.get(plan);
|
|
407
|
+
if (!refresh) throw new Error("The sandbox plan does not belong to this host");
|
|
408
|
+
return refresh();
|
|
409
|
+
},
|
|
410
|
+
async plan(caller, request, mode = "sandboxed", includeContributions = true) {
|
|
411
|
+
const workspaceId = caller.address.workspaceId;
|
|
412
|
+
const roots = deps.fence.roots(workspaceId);
|
|
413
|
+
if (!roots.allowed) return {
|
|
414
|
+
ok: false,
|
|
415
|
+
reason: roots.reason,
|
|
416
|
+
message: roots.message
|
|
417
|
+
};
|
|
418
|
+
const permissions = request.permissions;
|
|
419
|
+
for (const path of mode === "direct" ? [] : [...permissions?.read ?? [], ...permissions?.write ?? []]) {
|
|
420
|
+
const refusal = refuseProtected(path);
|
|
421
|
+
if (refusal !== void 0) return refusal;
|
|
422
|
+
}
|
|
423
|
+
const tmp = resolveThroughExisting(request.tmp, host);
|
|
424
|
+
const grantedRead = mode === "direct" ? [] : (permissions?.read ?? []).map((path) => resolveThroughExisting(path, host));
|
|
425
|
+
const grantedWrite = mode === "direct" ? [] : (permissions?.write ?? []).map((path) => resolveThroughExisting(path, host));
|
|
426
|
+
const authorized = roots.roots.map((root) => root.path);
|
|
427
|
+
const permittedRead = deps.access?.paths(caller.address, caller.sessionId, "read") ?? [];
|
|
428
|
+
const permittedWrite = deps.access?.paths(caller.address, caller.sessionId, "write") ?? [];
|
|
429
|
+
const read = dedupe([
|
|
430
|
+
...authorized,
|
|
431
|
+
...permittedRead,
|
|
432
|
+
...permittedWrite,
|
|
433
|
+
...resolveReadablePaths(deps.readable(), host),
|
|
434
|
+
...includeContributions && mode === "sandboxed" ? deps.contributed?.() ?? [] : [],
|
|
435
|
+
tmp,
|
|
436
|
+
SHARED_TMP,
|
|
437
|
+
...grantedRead,
|
|
438
|
+
...grantedWrite
|
|
439
|
+
]);
|
|
440
|
+
const write = dedupe([
|
|
441
|
+
...permittedWrite,
|
|
442
|
+
tmp,
|
|
443
|
+
...grantedWrite
|
|
444
|
+
]);
|
|
445
|
+
const deny = dedupe([...roots.sealed, ...sealed]);
|
|
446
|
+
const network = mode === "direct" ? {
|
|
447
|
+
externalAllowed: true,
|
|
448
|
+
connectAllow: [],
|
|
449
|
+
listenAllow: [],
|
|
450
|
+
protectedLocalPorts: []
|
|
451
|
+
} : deps.network?.(permissions ?? {}, deps.triggerExternal?.(caller) ?? false) ?? {
|
|
452
|
+
externalAllowed: false,
|
|
453
|
+
connectAllow: [],
|
|
454
|
+
listenAllow: [],
|
|
455
|
+
protectedLocalPorts: []
|
|
456
|
+
};
|
|
457
|
+
let cwd;
|
|
458
|
+
if (request.cwd === void 0) {
|
|
459
|
+
const fallback = [...permittedWrite, ...authorized].find(isDirectory);
|
|
460
|
+
if (fallback === void 0) return {
|
|
461
|
+
ok: false,
|
|
462
|
+
reason: "no-directories",
|
|
463
|
+
message: `workspace ${workspaceId} has nowhere for a command to run: none of its directories exist and nothing it may write is one`
|
|
464
|
+
};
|
|
465
|
+
cwd = fallback;
|
|
466
|
+
} else {
|
|
467
|
+
if (!isAbsolute(request.cwd)) return {
|
|
468
|
+
ok: false,
|
|
469
|
+
reason: "not-absolute",
|
|
470
|
+
message: `cwd must be an absolute path: ${request.cwd}. A session has no current directory, because a workspace is not a directory`
|
|
471
|
+
};
|
|
472
|
+
const requested = resolveThroughExisting(request.cwd, host);
|
|
473
|
+
if (!read.some((root) => isWithin(root, requested))) return {
|
|
474
|
+
ok: false,
|
|
475
|
+
reason: "bad-cwd",
|
|
476
|
+
message: `${request.cwd} is not inside any directory this command may read. Run it in an authorized directory, or ask for the path as a read permission`
|
|
477
|
+
};
|
|
478
|
+
const protectedCwd = refuseProtected(requested);
|
|
479
|
+
if (protectedCwd) return protectedCwd;
|
|
480
|
+
if (!isDirectory(requested)) return {
|
|
481
|
+
ok: false,
|
|
482
|
+
reason: "bad-cwd",
|
|
483
|
+
message: "cwd must be an existing directory"
|
|
484
|
+
};
|
|
485
|
+
cwd = requested;
|
|
486
|
+
}
|
|
487
|
+
const proxyEnvironment = network.externalAllowed ? await deps.proxyEnvironment?.() ?? {} : {};
|
|
488
|
+
if (mode === "direct") return {
|
|
489
|
+
ok: true,
|
|
490
|
+
plan: {
|
|
491
|
+
mode,
|
|
492
|
+
execution: {
|
|
493
|
+
argv: [...request.argv],
|
|
494
|
+
cwd
|
|
495
|
+
},
|
|
496
|
+
requested: permissions ?? {},
|
|
497
|
+
cwd,
|
|
498
|
+
tmp,
|
|
499
|
+
externalAllowed: true,
|
|
500
|
+
proxyEnvironment
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
const currentNetwork = deps.network?.(permissions ?? {}, deps.triggerExternal?.(caller) ?? false) ?? network;
|
|
504
|
+
const plan = {
|
|
505
|
+
mode,
|
|
506
|
+
read,
|
|
507
|
+
write,
|
|
508
|
+
deny,
|
|
509
|
+
...currentNetwork,
|
|
510
|
+
execution: {
|
|
511
|
+
argv: [...request.argv],
|
|
512
|
+
cwd
|
|
513
|
+
},
|
|
514
|
+
requested: permissions ?? {},
|
|
515
|
+
cwd,
|
|
516
|
+
tmp,
|
|
517
|
+
proxyEnvironment: currentNetwork.externalAllowed ? proxyEnvironment : {}
|
|
518
|
+
};
|
|
519
|
+
refreshers.set(plan, () => {
|
|
520
|
+
const currentRead = deps.access?.paths(caller.address, caller.sessionId, "read") ?? [];
|
|
521
|
+
const currentWrite = deps.access?.paths(caller.address, caller.sessionId, "write") ?? [];
|
|
522
|
+
const read = dedupe([
|
|
523
|
+
...authorized,
|
|
524
|
+
...currentRead,
|
|
525
|
+
...currentWrite,
|
|
526
|
+
...resolveReadablePaths(deps.readable(), host),
|
|
527
|
+
...includeContributions && mode === "sandboxed" ? deps.contributed?.() ?? [] : [],
|
|
528
|
+
tmp,
|
|
529
|
+
SHARED_TMP,
|
|
530
|
+
...grantedRead,
|
|
531
|
+
...grantedWrite
|
|
532
|
+
]);
|
|
533
|
+
if (!read.some((root) => isWithin(root, cwd))) throw new Error("The working directory is no longer readable");
|
|
534
|
+
const network = deps.network?.(permissions ?? {}, deps.triggerExternal?.(caller) ?? false) ?? currentNetwork;
|
|
535
|
+
return {
|
|
536
|
+
...plan,
|
|
537
|
+
read,
|
|
538
|
+
write: dedupe([
|
|
539
|
+
...currentWrite,
|
|
540
|
+
tmp,
|
|
541
|
+
...grantedWrite
|
|
542
|
+
]),
|
|
543
|
+
...network,
|
|
544
|
+
proxyEnvironment: network.externalAllowed && network.protectedLocalPorts.length ? proxyEnvironment : {}
|
|
545
|
+
};
|
|
546
|
+
});
|
|
547
|
+
return {
|
|
548
|
+
ok: true,
|
|
549
|
+
plan
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
//#endregion
|
|
555
|
+
//#region src/schema.ts
|
|
556
|
+
/** Sandbox-owned stored rules and management schemas. */
|
|
557
|
+
/** Concrete network decision values owned by sandbox. */
|
|
558
|
+
const NetworkPolicy = z.enum([
|
|
559
|
+
"ask",
|
|
560
|
+
"deny",
|
|
561
|
+
"allow"
|
|
562
|
+
]);
|
|
563
|
+
/** Independent external connection and listener policy settings. */
|
|
564
|
+
const NetworkPolicies = z.object({
|
|
565
|
+
external: NetworkPolicy,
|
|
566
|
+
connect: NetworkPolicy,
|
|
567
|
+
listen: NetworkPolicy
|
|
568
|
+
}).strict();
|
|
569
|
+
/** Complete persisted sandbox settings, including user read roots. */
|
|
570
|
+
const SandboxConfiguration = z.object({
|
|
571
|
+
enabled: z.boolean(),
|
|
572
|
+
readable: z.array(z.string()),
|
|
573
|
+
networkPolicies: NetworkPolicies
|
|
574
|
+
}).strict();
|
|
575
|
+
/** Partial owner updates retain unrelated current settings. */
|
|
576
|
+
const SandboxConfigurationUpdate = SandboxConfiguration.partial().strict();
|
|
577
|
+
/** Backend capability and the current selected execution preference. */
|
|
578
|
+
const SandboxStatus = z.object({
|
|
579
|
+
enabled: z.boolean(),
|
|
580
|
+
mode: z.enum(["sandboxed", "direct"]),
|
|
581
|
+
availability: z.discriminatedUnion("ok", [z.object({
|
|
582
|
+
ok: z.literal(true),
|
|
583
|
+
backend: z.string()
|
|
584
|
+
}), z.object({
|
|
585
|
+
ok: z.literal(false),
|
|
586
|
+
reason: z.string()
|
|
587
|
+
})])
|
|
588
|
+
});
|
|
589
|
+
/** Combined professional/simple values include only active owners. */
|
|
590
|
+
const SecurityConfiguration = z.object({
|
|
591
|
+
approvalPolicy: NetworkPolicy.optional(),
|
|
592
|
+
sandboxEnabled: z.boolean(),
|
|
593
|
+
networkPolicies: NetworkPolicies
|
|
594
|
+
}).strict();
|
|
595
|
+
/** Current settings snapshot; failed owner reads expose no partial values. */
|
|
596
|
+
const SecurityState = z.discriminatedUnion("status", [SecurityConfiguration.extend({ status: z.literal("ready") }), z.object({
|
|
597
|
+
status: z.literal("recovery-required"),
|
|
598
|
+
error: z.string()
|
|
599
|
+
}).strict()]);
|
|
600
|
+
z.object({ readable: z.array(z.string()) }).strict();
|
|
601
|
+
z.object({ enabled: z.boolean() }).strict();
|
|
602
|
+
//#endregion
|
|
603
|
+
//#region src/service.ts
|
|
604
|
+
/** Prefers available confinement and binds the selected capability to approval and launch. */
|
|
605
|
+
function createSandbox(deps) {
|
|
606
|
+
const state = () => deps.state?.() ?? {
|
|
607
|
+
enabled: true,
|
|
608
|
+
revision: 0
|
|
609
|
+
};
|
|
610
|
+
const owned = /* @__PURE__ */ new WeakMap();
|
|
611
|
+
function available() {
|
|
612
|
+
if (!deps.backend) return {
|
|
613
|
+
ok: false,
|
|
614
|
+
reason: `no sandbox backend is implemented for ${deps.host.process.platform}`
|
|
615
|
+
};
|
|
616
|
+
const ready = deps.backend.available();
|
|
617
|
+
return ready.ok ? {
|
|
618
|
+
ok: true,
|
|
619
|
+
backend: deps.backend.name
|
|
620
|
+
} : ready;
|
|
621
|
+
}
|
|
622
|
+
function assertCurrent(plan) {
|
|
623
|
+
deps.signal?.throwIfAborted();
|
|
624
|
+
const entry = owned.get(plan);
|
|
625
|
+
if (!entry || entry.revision !== void 0 && entry.revision !== state().revision) throw new Error("stale-approval: shell execution mode changed or the plan belongs to another host. Nothing ran.");
|
|
626
|
+
if (deps.authorizationIdentity && (!entry.authorizationIdentity || entry.authorizationIdentity !== deps.authorizationIdentity())) throw new Error("stale-approval: authorization strategy changed. Nothing ran.");
|
|
627
|
+
if (entry.routingRevision !== void 0 && entry.routingRevision !== deps.routingRevision?.()) throw new Error("stale-approval: network routing changed. Nothing ran.");
|
|
628
|
+
if (entry.availability !== void 0 && entry.availability !== JSON.stringify(available())) throw new Error("stale-approval: sandbox capability changed. Plan and approve the command again.");
|
|
629
|
+
if ("signal" in entry.authority && entry.authority.signal.aborted) throw new Error("exit by cancellation. The command did not run.");
|
|
630
|
+
if (plan.mode !== entry.mode) throw new Error("stale-approval: the execution mode differs from the host plan");
|
|
631
|
+
if (plan.cwd !== plan.execution.cwd || JSON.stringify(plan.execution) !== entry.execution) throw new Error("stale-approval: execution differs from the host plan. Nothing ran.");
|
|
632
|
+
}
|
|
633
|
+
async function plan(ctx, input, confined) {
|
|
634
|
+
const snapshot = state();
|
|
635
|
+
const routingRevision = deps.routingRevision?.();
|
|
636
|
+
const authorizationIdentity = deps.authorizationIdentity?.();
|
|
637
|
+
const capability = confined || snapshot.enabled ? available() : void 0;
|
|
638
|
+
const result = await deps.planner.plan({
|
|
639
|
+
address: ctx.address,
|
|
640
|
+
sessionId: ctx.sessionId
|
|
641
|
+
}, input, capability?.ok ? "sandboxed" : "direct", !confined);
|
|
642
|
+
if (!result.ok) return result;
|
|
643
|
+
const selected = result.plan.mode === "direct" && capability && !capability.ok ? {
|
|
644
|
+
...result.plan,
|
|
645
|
+
fallbackReason: capability.reason
|
|
646
|
+
} : result.plan;
|
|
647
|
+
owned.set(selected, {
|
|
648
|
+
...confined ? {} : { revision: snapshot.revision },
|
|
649
|
+
authority: ctx,
|
|
650
|
+
...routingRevision === void 0 ? {} : { routingRevision },
|
|
651
|
+
...authorizationIdentity === void 0 ? {} : { authorizationIdentity },
|
|
652
|
+
mode: selected.mode,
|
|
653
|
+
execution: JSON.stringify(selected.execution),
|
|
654
|
+
...capability ? { availability: JSON.stringify(capability) } : {}
|
|
655
|
+
});
|
|
656
|
+
try {
|
|
657
|
+
assertCurrent(selected);
|
|
658
|
+
} catch (error) {
|
|
659
|
+
return {
|
|
660
|
+
ok: false,
|
|
661
|
+
reason: "stale-approval",
|
|
662
|
+
message: String(error)
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
return {
|
|
666
|
+
ok: true,
|
|
667
|
+
plan: selected
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
return {
|
|
671
|
+
start: (spec, onExit) => {
|
|
672
|
+
deps.signal?.throwIfAborted();
|
|
673
|
+
if (!deps.start) return Promise.reject(/* @__PURE__ */ new Error("Sandbox executor is unavailable"));
|
|
674
|
+
return deps.start(spec, onExit);
|
|
675
|
+
},
|
|
676
|
+
available,
|
|
677
|
+
status() {
|
|
678
|
+
const enabled = state().enabled;
|
|
679
|
+
const availability = available();
|
|
680
|
+
return {
|
|
681
|
+
enabled,
|
|
682
|
+
mode: enabled && availability.ok ? "sandboxed" : "direct",
|
|
683
|
+
availability
|
|
684
|
+
};
|
|
685
|
+
},
|
|
686
|
+
plan: (ctx, input) => plan(ctx, input, false),
|
|
687
|
+
planSandboxed: (ctx, input) => plan(ctx, input, true),
|
|
688
|
+
prepare(plan, command) {
|
|
689
|
+
assertCurrent(plan);
|
|
690
|
+
if (JSON.stringify(command) !== JSON.stringify(plan.execution.argv)) throw new Error("stale-approval: command differs from approved execution");
|
|
691
|
+
if (plan.mode === "direct") return {
|
|
692
|
+
mode: "direct",
|
|
693
|
+
...plan.fallbackReason ? { fallbackReason: plan.fallbackReason } : {},
|
|
694
|
+
argv: [...command],
|
|
695
|
+
externalAllowed: true,
|
|
696
|
+
proxyEnvironment: plan.proxyEnvironment,
|
|
697
|
+
assertCurrent: () => assertCurrent(plan)
|
|
698
|
+
};
|
|
699
|
+
if (!deps.backend) throw new Error("no sandbox backend is available on this host");
|
|
700
|
+
const available = deps.backend.available();
|
|
701
|
+
if (!available.ok) throw new Error(`sandbox-unavailable: ${available.reason}`);
|
|
702
|
+
const refreshed = deps.refreshPlan?.(plan) ?? plan;
|
|
703
|
+
return {
|
|
704
|
+
mode: "sandboxed",
|
|
705
|
+
argv: deps.backend.argv(refreshed, command),
|
|
706
|
+
externalAllowed: refreshed.externalAllowed,
|
|
707
|
+
proxyEnvironment: refreshed.proxyEnvironment ?? {},
|
|
708
|
+
assertCurrent: () => assertCurrent(plan)
|
|
709
|
+
};
|
|
710
|
+
},
|
|
711
|
+
authorize(ctx, plan, reason) {
|
|
712
|
+
try {
|
|
713
|
+
assertCurrent(plan);
|
|
714
|
+
} catch (error) {
|
|
715
|
+
return {
|
|
716
|
+
kind: "refused",
|
|
717
|
+
reason: "policy",
|
|
718
|
+
message: String(error)
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
return deps.authorize(ctx, plan.requested, reason, plan.execution, plan.mode, plan.mode === "direct" ? plan.fallbackReason : void 0);
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
//#endregion
|
|
726
|
+
//#region src/sources.ts
|
|
727
|
+
/** Validates generic owner roots without interpreting capability-specific configuration. */
|
|
728
|
+
/** Creates the host projection; inspection never reads file bodies or expands locators. */
|
|
729
|
+
function createSandboxReadableProjection(deps) {
|
|
730
|
+
const { host } = deps;
|
|
731
|
+
function inspect(target) {
|
|
732
|
+
if (!isAbsolute(target.path) || normalize(target.path) !== target.path || target.path === parse(target.path).root || target.path === resolveThroughExisting(host.os.homedir(), host) || !["file", "directory"].includes(target.targetType)) return "invalid";
|
|
733
|
+
try {
|
|
734
|
+
const real = host.fs.realpathSync(target.path);
|
|
735
|
+
if (deps.sealed.some((root) => isWithin(resolveThroughExisting(root, host), real))) return "sealed";
|
|
736
|
+
if (real !== target.path) return "changed-target";
|
|
737
|
+
const stat = host.fs.statSync(real);
|
|
738
|
+
if (target.targetType === "file" ? !stat.isFile() : !stat.isDirectory()) return "type-mismatch";
|
|
739
|
+
return null;
|
|
740
|
+
} catch {
|
|
741
|
+
return "missing";
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
function current() {
|
|
745
|
+
const base = [...deps.base()];
|
|
746
|
+
const sources = deps.registry.list().map(({ owner, epoch, source }) => {
|
|
747
|
+
const view = {
|
|
748
|
+
owner,
|
|
749
|
+
epoch,
|
|
750
|
+
id: source.id,
|
|
751
|
+
label: source.label,
|
|
752
|
+
revision: 0,
|
|
753
|
+
paths: [],
|
|
754
|
+
status: "unavailable",
|
|
755
|
+
rejected: []
|
|
756
|
+
};
|
|
757
|
+
try {
|
|
758
|
+
const data = source.read();
|
|
759
|
+
if (!Number.isSafeInteger(data.revision) || data.revision < 0 || !Array.isArray(data.paths) || data.paths.length > 4096) return view;
|
|
760
|
+
const paths = [], rejected = [];
|
|
761
|
+
for (const target of data.paths) {
|
|
762
|
+
if (!target || typeof target.path !== "string" || target.path.length > 4096) return view;
|
|
763
|
+
const reason = inspect(target);
|
|
764
|
+
if (reason) rejected.push({
|
|
765
|
+
path: target.path,
|
|
766
|
+
reason
|
|
767
|
+
});
|
|
768
|
+
else if (!paths.some((item) => item.path === target.path && item.targetType === target.targetType)) paths.push({
|
|
769
|
+
path: target.path,
|
|
770
|
+
targetType: target.targetType
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
return {
|
|
774
|
+
...view,
|
|
775
|
+
revision: data.revision,
|
|
776
|
+
paths,
|
|
777
|
+
rejected,
|
|
778
|
+
status: "active"
|
|
779
|
+
};
|
|
780
|
+
} catch {
|
|
781
|
+
return view;
|
|
782
|
+
}
|
|
783
|
+
});
|
|
784
|
+
const baseTargets = base.map((path) => {
|
|
785
|
+
try {
|
|
786
|
+
const real = host.fs.realpathSync(path), stat = host.fs.statSync(real);
|
|
787
|
+
return {
|
|
788
|
+
path,
|
|
789
|
+
real,
|
|
790
|
+
type: stat.isFile() ? "file" : stat.isDirectory() ? "directory" : "other"
|
|
791
|
+
};
|
|
792
|
+
} catch {
|
|
793
|
+
return {
|
|
794
|
+
path,
|
|
795
|
+
real: null,
|
|
796
|
+
type: "missing"
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
});
|
|
800
|
+
return {
|
|
801
|
+
revision: host.crypto.createHash("sha256").update(JSON.stringify({
|
|
802
|
+
base,
|
|
803
|
+
baseTargets,
|
|
804
|
+
sources,
|
|
805
|
+
enabled: deps.enabled?.() ?? true
|
|
806
|
+
})).digest("hex"),
|
|
807
|
+
base,
|
|
808
|
+
sources,
|
|
809
|
+
enabled: deps.enabled?.() ?? true
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
return {
|
|
813
|
+
inspect,
|
|
814
|
+
current
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
//#endregion
|
|
818
|
+
//#region src/index.ts
|
|
819
|
+
/** Owns Agent shell planning, launch orchestration, rules and settings. */
|
|
820
|
+
const plugin = {
|
|
821
|
+
name: "@eum-agent/sandbox",
|
|
822
|
+
requires: [
|
|
823
|
+
"sandbox-host",
|
|
824
|
+
"network",
|
|
825
|
+
"subprocess",
|
|
826
|
+
"work-lifecycle",
|
|
827
|
+
"configuration-transactions"
|
|
828
|
+
],
|
|
829
|
+
optionalServices: ["authorization-strategy"],
|
|
830
|
+
provides: [
|
|
831
|
+
"sandbox",
|
|
832
|
+
"sandbox-settings",
|
|
833
|
+
"sandbox-settings-participant",
|
|
834
|
+
"sandbox-readable-projection"
|
|
835
|
+
],
|
|
836
|
+
apply(ctx) {
|
|
837
|
+
const host = ctx.services.get("sandbox-host");
|
|
838
|
+
const network = ctx.services.get("network");
|
|
839
|
+
const subprocess = ctx.services.get("subprocess");
|
|
840
|
+
const transactions = ctx.services.get("configuration-transactions");
|
|
841
|
+
const storage = ctx.storage.open();
|
|
842
|
+
const database = storage.db;
|
|
843
|
+
const table = storage.tableName("settings");
|
|
844
|
+
database.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY CHECK (id = 1), value TEXT NOT NULL)`);
|
|
845
|
+
const frame = ctx.client.registerFrame({
|
|
846
|
+
name: "sandboxChanged",
|
|
847
|
+
delivery: "broadcast",
|
|
848
|
+
payload: SandboxConfiguration.extend({ protectedLocalPorts: z.array(z.number()).optional() })
|
|
849
|
+
});
|
|
850
|
+
let revision = 0;
|
|
851
|
+
const read = () => {
|
|
852
|
+
ctx.signal.throwIfAborted();
|
|
853
|
+
const row = database.prepare(`SELECT value FROM ${table} WHERE id = 1`).get();
|
|
854
|
+
return row ? SandboxConfiguration.parse(JSON.parse(row.value)) : {
|
|
855
|
+
enabled: true,
|
|
856
|
+
readable: [],
|
|
857
|
+
networkPolicies: {
|
|
858
|
+
external: "ask",
|
|
859
|
+
connect: "ask",
|
|
860
|
+
listen: "ask"
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
};
|
|
864
|
+
const strategy = () => ctx.services.find("authorization-strategy");
|
|
865
|
+
const projection = createSandboxReadableProjection({
|
|
866
|
+
host: host.host,
|
|
867
|
+
registry: { list: () => host.readableSources() },
|
|
868
|
+
enabled: () => read().enabled,
|
|
869
|
+
base: () => read().readable,
|
|
870
|
+
sealed: host.sealedDirectories
|
|
871
|
+
});
|
|
872
|
+
ctx.services.provide("sandbox-readable-projection", projection);
|
|
873
|
+
const sandboxNetwork = createSandboxNetwork({ networkPolicies: () => read().networkPolicies }, host.resources, () => frame.emit({
|
|
874
|
+
...read(),
|
|
875
|
+
protectedLocalPorts: [...host.protectedPorts()]
|
|
876
|
+
}));
|
|
877
|
+
const bindPorts = () => {
|
|
878
|
+
const port = host.protectedPorts()[0];
|
|
879
|
+
if (port !== void 0) sandboxNetwork.bind(port);
|
|
880
|
+
};
|
|
881
|
+
bindPorts();
|
|
882
|
+
const unsubscribe = host.subscribe(bindPorts);
|
|
883
|
+
ctx.onDispose(unsubscribe);
|
|
884
|
+
const planner = createSandboxPlanner({
|
|
885
|
+
host: host.host,
|
|
886
|
+
fence: host.fence,
|
|
887
|
+
readable: () => read().readable,
|
|
888
|
+
contributed: () => projection.current().sources.flatMap((source) => source.paths.map((target) => target.path)),
|
|
889
|
+
network: sandboxNetwork.effective,
|
|
890
|
+
triggerExternal: (caller) => host.resources.holdsNetwork(caller.address, caller.sessionId),
|
|
891
|
+
sealed: host.sealedDirectories,
|
|
892
|
+
proxyEnvironment: async () => (await network.environment()).env,
|
|
893
|
+
access: host.resources
|
|
894
|
+
});
|
|
895
|
+
const handles = /* @__PURE__ */ new Set();
|
|
896
|
+
const starts = /* @__PURE__ */ new Set();
|
|
897
|
+
let withdrawing = false;
|
|
898
|
+
const start = (spec, onExit) => {
|
|
899
|
+
ctx.signal.throwIfAborted();
|
|
900
|
+
if (withdrawing) return Promise.reject(/* @__PURE__ */ new Error("Sandbox execution owner is withdrawing"));
|
|
901
|
+
let completed = false;
|
|
902
|
+
let owned;
|
|
903
|
+
const pending = subprocess.start({
|
|
904
|
+
...spec,
|
|
905
|
+
beforeSpawn() {
|
|
906
|
+
ctx.signal.throwIfAborted();
|
|
907
|
+
if (withdrawing) throw new Error("Sandbox execution owner is withdrawing");
|
|
908
|
+
spec.beforeSpawn?.();
|
|
909
|
+
}
|
|
910
|
+
}, (ending) => {
|
|
911
|
+
completed = true;
|
|
912
|
+
if (owned) handles.delete(owned);
|
|
913
|
+
return onExit(ending);
|
|
914
|
+
}).then(async (handle) => {
|
|
915
|
+
owned = handle;
|
|
916
|
+
if (!completed) handles.add(handle);
|
|
917
|
+
if (withdrawing || ctx.signal.aborted) try {
|
|
918
|
+
await handle.stop("cancelled");
|
|
919
|
+
} catch (error) {
|
|
920
|
+
throw Object.assign(new Error("Sandbox withdrawal cleanup failed", { cause: error }), {
|
|
921
|
+
reason: "unavailable",
|
|
922
|
+
cleanupHandle: handle
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
return handle;
|
|
926
|
+
}, (error) => {
|
|
927
|
+
const retained = error?.cleanupHandle;
|
|
928
|
+
if (retained) {
|
|
929
|
+
owned = retained;
|
|
930
|
+
if (!completed) handles.add(retained);
|
|
931
|
+
}
|
|
932
|
+
throw error;
|
|
933
|
+
});
|
|
934
|
+
starts.add(pending);
|
|
935
|
+
pending.finally(() => starts.delete(pending)).catch(() => {});
|
|
936
|
+
return pending;
|
|
937
|
+
};
|
|
938
|
+
const drain = async () => {
|
|
939
|
+
withdrawing = true;
|
|
940
|
+
await Promise.allSettled([...starts]);
|
|
941
|
+
await Promise.all([...handles].map((handle) => handle.stop("cancelled")));
|
|
942
|
+
};
|
|
943
|
+
ctx.signal.addEventListener("abort", () => {
|
|
944
|
+
withdrawing = true;
|
|
945
|
+
for (const handle of handles) handle.stop("cancelled").catch(() => {});
|
|
946
|
+
}, { once: true });
|
|
947
|
+
const removeDrain = ctx.services.get("work-lifecycle").register(drain);
|
|
948
|
+
ctx.onDispose(async () => {
|
|
949
|
+
await drain();
|
|
950
|
+
removeDrain();
|
|
951
|
+
});
|
|
952
|
+
const sandbox = createSandbox({
|
|
953
|
+
host: host.host,
|
|
954
|
+
signal: ctx.signal,
|
|
955
|
+
routingRevision: () => network.routingRevision(),
|
|
956
|
+
authorizationIdentity: strategy,
|
|
957
|
+
start,
|
|
958
|
+
refreshPlan: planner.refresh,
|
|
959
|
+
state: () => ({
|
|
960
|
+
enabled: read().enabled,
|
|
961
|
+
revision
|
|
962
|
+
}),
|
|
963
|
+
planner,
|
|
964
|
+
...host.backend ? { backend: host.backend } : {},
|
|
965
|
+
authorize: createAuthorize({
|
|
966
|
+
host: host.host,
|
|
967
|
+
access: host.resources,
|
|
968
|
+
available: () => Boolean(strategy()),
|
|
969
|
+
validateTarget: (input) => host.validateTarget(input),
|
|
970
|
+
approval: {
|
|
971
|
+
questionId: (id) => strategy()?.askQuestionId(id),
|
|
972
|
+
decide: (authority, input) => strategy()?.ask(authority, input) ?? {
|
|
973
|
+
kind: "result",
|
|
974
|
+
result: { kind: "unavailable" },
|
|
975
|
+
source: "policy-deny"
|
|
976
|
+
}
|
|
977
|
+
},
|
|
978
|
+
defaultPolicy: () => strategy()?.policy() ?? "deny",
|
|
979
|
+
policies: () => read().networkPolicies,
|
|
980
|
+
protectedPorts: () => host.protectedPorts()
|
|
981
|
+
})
|
|
982
|
+
});
|
|
983
|
+
ctx.services.provide("sandbox", sandbox);
|
|
984
|
+
const participant = {
|
|
985
|
+
connectionIdentity: storage.connectionIdentity,
|
|
986
|
+
prepare(value) {
|
|
987
|
+
const update = SandboxConfigurationUpdate.parse(value);
|
|
988
|
+
const input = SandboxConfiguration.parse({
|
|
989
|
+
...read(),
|
|
990
|
+
...update
|
|
991
|
+
});
|
|
992
|
+
const unchanged = JSON.stringify(input) === JSON.stringify(read());
|
|
993
|
+
const at = revision;
|
|
994
|
+
const assertCurrent = () => {
|
|
995
|
+
ctx.signal.throwIfAborted();
|
|
996
|
+
if (revision !== at) throw new Error("Sandbox settings changed before commit");
|
|
997
|
+
};
|
|
998
|
+
return {
|
|
999
|
+
assertCurrent,
|
|
1000
|
+
write() {
|
|
1001
|
+
assertCurrent();
|
|
1002
|
+
if (unchanged) return;
|
|
1003
|
+
database.prepare(`INSERT INTO ${table} (id, value) VALUES (1, ?) ON CONFLICT (id) DO UPDATE SET value = excluded.value`).run(JSON.stringify(input));
|
|
1004
|
+
},
|
|
1005
|
+
publish() {
|
|
1006
|
+
if (!unchanged) {
|
|
1007
|
+
revision++;
|
|
1008
|
+
frame.emit(input);
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
ctx.services.provide("sandbox-settings-participant", participant);
|
|
1015
|
+
const update = (value) => transactions.commit([{
|
|
1016
|
+
service: "sandbox-settings-participant",
|
|
1017
|
+
value
|
|
1018
|
+
}]);
|
|
1019
|
+
const security = () => {
|
|
1020
|
+
const config = read(), policy = strategy()?.policy();
|
|
1021
|
+
return {
|
|
1022
|
+
status: "ready",
|
|
1023
|
+
sandboxEnabled: config.enabled,
|
|
1024
|
+
networkPolicies: config.networkPolicies,
|
|
1025
|
+
...policy === void 0 ? {} : { approvalPolicy: policy }
|
|
1026
|
+
};
|
|
1027
|
+
};
|
|
1028
|
+
ctx.client.registerMethod({
|
|
1029
|
+
name: "securityGet",
|
|
1030
|
+
params: z.object({}).strict(),
|
|
1031
|
+
result: SecurityState,
|
|
1032
|
+
handle: security
|
|
1033
|
+
});
|
|
1034
|
+
ctx.client.registerMethod({
|
|
1035
|
+
name: "securitySet",
|
|
1036
|
+
params: SecurityConfiguration,
|
|
1037
|
+
result: SecurityState,
|
|
1038
|
+
handle(input) {
|
|
1039
|
+
transactions.commit([...input.approvalPolicy === void 0 ? [] : [{
|
|
1040
|
+
service: "authorization-settings-participant",
|
|
1041
|
+
value: { policy: input.approvalPolicy }
|
|
1042
|
+
}], {
|
|
1043
|
+
service: "sandbox-settings-participant",
|
|
1044
|
+
value: {
|
|
1045
|
+
enabled: input.sandboxEnabled,
|
|
1046
|
+
networkPolicies: input.networkPolicies
|
|
1047
|
+
}
|
|
1048
|
+
}]);
|
|
1049
|
+
return security();
|
|
1050
|
+
}
|
|
1051
|
+
});
|
|
1052
|
+
ctx.client.registerMethod({
|
|
1053
|
+
name: "getEnabled",
|
|
1054
|
+
params: z.object({}).strict(),
|
|
1055
|
+
result: SandboxStatus,
|
|
1056
|
+
handle: () => sandbox.status()
|
|
1057
|
+
});
|
|
1058
|
+
ctx.client.registerMethod({
|
|
1059
|
+
name: "setEnabled",
|
|
1060
|
+
params: z.object({ enabled: z.boolean() }).strict(),
|
|
1061
|
+
result: SandboxStatus,
|
|
1062
|
+
handle(input) {
|
|
1063
|
+
update(input);
|
|
1064
|
+
return sandbox.status();
|
|
1065
|
+
}
|
|
1066
|
+
});
|
|
1067
|
+
const networkState = () => ({
|
|
1068
|
+
policies: read().networkPolicies,
|
|
1069
|
+
protectedLocalPorts: [...host.protectedPorts()],
|
|
1070
|
+
externalApproval: host.resources.list().find((row) => row.kind === "sandbox-network")
|
|
1071
|
+
});
|
|
1072
|
+
const networkStateSchema = z.object({
|
|
1073
|
+
policies: NetworkPolicies,
|
|
1074
|
+
protectedLocalPorts: z.array(z.number()),
|
|
1075
|
+
externalApproval: z.unknown().optional()
|
|
1076
|
+
});
|
|
1077
|
+
ctx.client.registerMethod({
|
|
1078
|
+
name: "getNetworkPolicies",
|
|
1079
|
+
params: z.object({}).strict(),
|
|
1080
|
+
result: networkStateSchema,
|
|
1081
|
+
handle: networkState
|
|
1082
|
+
});
|
|
1083
|
+
ctx.client.registerMethod({
|
|
1084
|
+
name: "setNetworkPolicies",
|
|
1085
|
+
params: NetworkPolicies,
|
|
1086
|
+
result: networkStateSchema,
|
|
1087
|
+
handle(input) {
|
|
1088
|
+
update({ networkPolicies: input });
|
|
1089
|
+
return networkState();
|
|
1090
|
+
}
|
|
1091
|
+
});
|
|
1092
|
+
const readable = () => ({ readable: read().readable });
|
|
1093
|
+
const readableSchema = z.object({ readable: z.array(z.string()) });
|
|
1094
|
+
ctx.client.registerMethod({
|
|
1095
|
+
name: "listReadablePaths",
|
|
1096
|
+
params: z.object({}).strict(),
|
|
1097
|
+
result: readableSchema,
|
|
1098
|
+
handle: readable
|
|
1099
|
+
});
|
|
1100
|
+
const management = {
|
|
1101
|
+
read,
|
|
1102
|
+
status: () => sandbox.status(),
|
|
1103
|
+
addReadablePath(path) {
|
|
1104
|
+
const refusal = readablePathRefusal(path, { sealed: host.sealedDirectories }, host.host);
|
|
1105
|
+
if (refusal) throw new Error(refusal);
|
|
1106
|
+
update({ readable: [.../* @__PURE__ */ new Set([...read().readable, resolveThroughExisting(path, host.host)])] });
|
|
1107
|
+
return readable();
|
|
1108
|
+
},
|
|
1109
|
+
removeReadablePath(path) {
|
|
1110
|
+
const paths = /* @__PURE__ */ new Set([path, resolveThroughExisting(path, host.host)]);
|
|
1111
|
+
const previous = read();
|
|
1112
|
+
const next = previous.readable.filter((entry) => !paths.has(entry));
|
|
1113
|
+
update({ readable: next });
|
|
1114
|
+
if (next.length === previous.readable.length) frame.emit(previous);
|
|
1115
|
+
return readable();
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
ctx.services.provide("sandbox-settings", management);
|
|
1119
|
+
ctx.client.registerMethod({
|
|
1120
|
+
name: "addReadablePath",
|
|
1121
|
+
params: z.object({ path: z.string() }).strict(),
|
|
1122
|
+
result: readableSchema,
|
|
1123
|
+
handle: (input) => management.addReadablePath(input.path)
|
|
1124
|
+
});
|
|
1125
|
+
ctx.client.registerMethod({
|
|
1126
|
+
name: "removeReadablePath",
|
|
1127
|
+
params: z.object({ path: z.string() }).strict(),
|
|
1128
|
+
result: readableSchema,
|
|
1129
|
+
handle: (input) => management.removeReadablePath(input.path)
|
|
1130
|
+
});
|
|
1131
|
+
const module = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
1132
|
+
if (existsSync(module)) ctx.client.registerUi({ module });
|
|
1133
|
+
}
|
|
1134
|
+
};
|
|
1135
|
+
//#endregion
|
|
1136
|
+
export { createSandbox, createSandboxPlanner, plugin as default };
|