@agentpro/scroll 0.0.0-stage → 2.5.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/AGENTS.md +55 -0
- package/LICENSE +21 -0
- package/README.md +293 -2
- package/SPEC.md +1079 -0
- package/bin/scroll.js +8 -0
- package/docs/prompt-caching.md +128 -0
- package/index.js +33 -0
- package/lib/audit.js +358 -0
- package/lib/auth.js +849 -0
- package/lib/chat-sdk/admin-controller.js +289 -0
- package/lib/chat-sdk/debouncer.js +94 -0
- package/lib/chat-sdk/group-grants.js +150 -0
- package/lib/chat-sdk/index.js +222 -0
- package/lib/chat-sdk/long-task-runner.js +413 -0
- package/lib/chat-session.js +1788 -0
- package/lib/chat-telemetry.js +557 -0
- package/lib/codex-app-server.js +851 -0
- package/lib/digest.js +112 -0
- package/lib/effects.js +157 -0
- package/lib/eval.js +408 -0
- package/lib/grounding.js +356 -0
- package/lib/installers.js +176 -0
- package/lib/knowledge.js +335 -0
- package/lib/ledger.js +38 -0
- package/lib/loop.js +197 -0
- package/lib/mcp-client.js +926 -0
- package/lib/memory-cli.js +66 -0
- package/lib/memory-tracker.js +1472 -0
- package/lib/memory.js +1279 -0
- package/lib/people-cli.js +81 -0
- package/lib/people.js +534 -0
- package/lib/permissions.js +272 -0
- package/lib/providers.js +1572 -0
- package/lib/runtime.js +928 -0
- package/lib/sandbox.js +744 -0
- package/lib/scheduler.js +402 -0
- package/lib/scroll.js +1225 -0
- package/lib/skill-cli.js +120 -0
- package/lib/skill-eval.js +156 -0
- package/lib/skills.js +860 -0
- package/lib/style.js +126 -0
- package/lib/tool-retriever.js +489 -0
- package/lib/tools.js +1833 -0
- package/lib/user.js +711 -0
- package/lib/vault.js +151 -0
- package/package.json +88 -4
- package/templates/agent/IDENTITY.md +56 -0
- package/templates/agent/SOUL.md +23 -0
- package/templates/agent/TOOLS.md +25 -0
- package/templates/agent/evals/case-02-citation-discipline.md +29 -0
- package/templates/agent/evals/case-03-boundary.md +27 -0
- package/templates/agent/evals/case-example.md +43 -0
- package/templates/agent/hard-rules.md +11 -0
- package/templates/agent/memory/lessons.md +5 -0
- package/templates/agent/memory/log/.gitkeep +0 -0
- package/templates/external-safety-contract.md +5 -0
- package/templates/long-task-planner.md +17 -0
- package/templates/work/LOOP.md +37 -0
- package/templates/work/WORK.md +50 -0
- package/types/chat.d.ts +61 -0
- package/types/index.d.ts +112 -0
package/lib/sandbox.js
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
1
|
+
// SCROLL 2.5 -- §20.4 / D07 Zero-Dependency OS Sandbox, Process Hygiene & Argv Exec Policy.
|
|
2
|
+
//
|
|
3
|
+
// Isolates `exec` and subprocess tool execution at the OS kernel boundary:
|
|
4
|
+
// - macOS: `/usr/bin/sandbox-exec` with DENY-DEFAULT SBPL profile (`(deny default)`):
|
|
5
|
+
// blocks $HOME reads outside cwd, blocks Mach/AppleEvents/LaunchServices escape,
|
|
6
|
+
// blocks all writes outside cwd & /tmp, marks sensitive policy/VCS subpaths
|
|
7
|
+
// (.git, .scroll, agents, .mcp.json, mcp-lock.json, USER.md) read-only inside cwd,
|
|
8
|
+
// and blocks network by default.
|
|
9
|
+
// - Linux: `bwrap` (Bubblewrap namespaces: --unshare-user/pid/ipc/uts/net, --new-session,
|
|
10
|
+
// --cap-drop ALL, --clearenv + explicit --setenv, read-only system dirs, and
|
|
11
|
+
// read-only overlay of sensitive policy/VCS subpaths inside cwd).
|
|
12
|
+
// - Process-group isolation: spawns detached and terminates the entire process group
|
|
13
|
+
// (`process.kill(-pid, 'SIGKILL')`) on timeout or AbortSignal, with streaming byte caps.
|
|
14
|
+
// - Declarative argv-prefix exec policy (`evaluateExecPolicy`), never shell-string regexes.
|
|
15
|
+
// - Pluggable `execRunner` hook for custom container/microVM runners.
|
|
16
|
+
// - Fail-closed when `requireSandbox: true` and no OS sandbox binary is available.
|
|
17
|
+
//
|
|
18
|
+
// Zero runtime dependencies. Node >= 20 built-ins only.
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import os from 'node:os';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import { spawn } from 'node:child_process';
|
|
23
|
+
|
|
24
|
+
export const DEFAULT_ENV_ALLOWLIST = [
|
|
25
|
+
'PATH',
|
|
26
|
+
'LANG',
|
|
27
|
+
'LC_ALL',
|
|
28
|
+
'LC_CTYPE',
|
|
29
|
+
'TZ',
|
|
30
|
+
'TMPDIR',
|
|
31
|
+
'TERM',
|
|
32
|
+
'NO_COLOR',
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
// Sensitive subpaths inside a writable workspace that MUST remain read-only so sandboxed
|
|
36
|
+
// commands cannot install persistent code or weaken SCROLL security policy.
|
|
37
|
+
export const PROTECTED_CWD_SUBPATHS = Object.freeze([
|
|
38
|
+
'.git',
|
|
39
|
+
'.scroll',
|
|
40
|
+
'.mcp.json',
|
|
41
|
+
'mcp-lock.json',
|
|
42
|
+
'USER.md',
|
|
43
|
+
'agents',
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
// Sensitive directories under $HOME that are always denied read & write in Seatbelt.
|
|
47
|
+
const SENSITIVE_HOME_SUBDIRS = Object.freeze([
|
|
48
|
+
'.ssh',
|
|
49
|
+
'.aws',
|
|
50
|
+
'.gnupg',
|
|
51
|
+
'.openclaw',
|
|
52
|
+
'.scroll-telegram',
|
|
53
|
+
'.kube',
|
|
54
|
+
'.config',
|
|
55
|
+
]);
|
|
56
|
+
|
|
57
|
+
const SECRET_ENV_NAME_RE = /(?:^|_)(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD|CREDENTIAL|AUTH|COOKIE|PRIVATE|BEARER)(?:$|_)/i;
|
|
58
|
+
|
|
59
|
+
export function buildSanitizedEnv({
|
|
60
|
+
allowEnv = DEFAULT_ENV_ALLOWLIST,
|
|
61
|
+
extraEnv = null,
|
|
62
|
+
baseEnv = process.env,
|
|
63
|
+
sandboxHome = null,
|
|
64
|
+
} = {}) {
|
|
65
|
+
const out = {};
|
|
66
|
+
const allowSet = new Set(Array.isArray(allowEnv) ? allowEnv.map(String) : DEFAULT_ENV_ALLOWLIST);
|
|
67
|
+
for (const k of allowSet) {
|
|
68
|
+
if (baseEnv && baseEnv[k] !== undefined && !SECRET_ENV_NAME_RE.test(k)) {
|
|
69
|
+
out[k] = String(baseEnv[k]);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (!out.PATH) out.PATH = '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin';
|
|
73
|
+
if (sandboxHome) {
|
|
74
|
+
out.HOME = String(sandboxHome);
|
|
75
|
+
out.TMPDIR = out.TMPDIR || os.tmpdir();
|
|
76
|
+
}
|
|
77
|
+
if (extraEnv && typeof extraEnv === 'object') {
|
|
78
|
+
for (const [k, v] of Object.entries(extraEnv)) {
|
|
79
|
+
if (v !== undefined && v !== null) out[String(k)] = String(v);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function realpathSafe(p) {
|
|
86
|
+
try { return fs.realpathSync.native(p); } catch {
|
|
87
|
+
try { return fs.realpathSync(p); } catch { return path.resolve(p); }
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function escapeSbpl(s) {
|
|
92
|
+
return String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isUnsafeSandboxCwd(realCwd, realHome) {
|
|
96
|
+
if (!realCwd || realCwd === '/' || realCwd === realHome) return true;
|
|
97
|
+
// Also reject direct ancestor of realHome (e.g. /Users or /home)
|
|
98
|
+
if (realHome && realHome.startsWith(realCwd + path.sep)) return true;
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function safeRuntimeReadPrefixes(command, realHome) {
|
|
103
|
+
if (!command || !path.isAbsolute(command)) return [];
|
|
104
|
+
const binReal = realpathSafe(command);
|
|
105
|
+
const binDir = path.dirname(binReal);
|
|
106
|
+
const parent = path.dirname(binDir);
|
|
107
|
+
const isSafePrefix = (p) => {
|
|
108
|
+
if (!p || p === '/' || p === realHome || p === '/Users' || p === '/home') return false;
|
|
109
|
+
if (realHome && realHome.startsWith(p + path.sep)) return false;
|
|
110
|
+
return true;
|
|
111
|
+
};
|
|
112
|
+
const out = [];
|
|
113
|
+
if (isSafePrefix(binDir)) out.push(binDir);
|
|
114
|
+
// Allow versioned runtime prefix (e.g. ~/.nvm/versions/node/v24.x or /opt/homebrew/Cellar/node/24.x)
|
|
115
|
+
// ONLY when binReal sits inside a `bin/` subdir and parent is strictly below realHome or /opt,
|
|
116
|
+
// NEVER `/` and NEVER `realHome` itself!
|
|
117
|
+
if (path.basename(binDir) === 'bin' && isSafePrefix(parent) && parent !== '/usr' && parent !== '/usr/local') {
|
|
118
|
+
out.push(parent);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function detectOsSandbox({ platform = process.platform } = {}) {
|
|
124
|
+
if (platform === 'darwin') {
|
|
125
|
+
if (fs.existsSync('/usr/bin/sandbox-exec')) {
|
|
126
|
+
return { available: true, kind: 'seatbelt', bin: '/usr/bin/sandbox-exec' };
|
|
127
|
+
}
|
|
128
|
+
return { available: false, kind: null, bin: null };
|
|
129
|
+
}
|
|
130
|
+
if (platform === 'linux') {
|
|
131
|
+
for (const candidate of ['/usr/bin/bwrap', '/bin/bwrap', '/usr/local/bin/bwrap']) {
|
|
132
|
+
if (fs.existsSync(candidate)) {
|
|
133
|
+
return { available: true, kind: 'bwrap', bin: candidate };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return { available: false, kind: null, bin: null };
|
|
137
|
+
}
|
|
138
|
+
return { available: false, kind: null, bin: null };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Declarative Codex-style argv-prefix execution policy (data-driven, never shell regex).
|
|
142
|
+
// Rule formats:
|
|
143
|
+
// - "git" -> matches command basename "git" with any args
|
|
144
|
+
// - ["git", "status"] -> matches command basename "git" + args prefix ["status"]
|
|
145
|
+
// - { prefix: ["python3", "script.py"] } -> matches prefix array
|
|
146
|
+
// - { prefix: ["rm", "-rf"], decision: "deny" }
|
|
147
|
+
function normalizeExecRule(raw, defaultDecision = 'allow') {
|
|
148
|
+
if (!raw) return null;
|
|
149
|
+
if (typeof raw === 'string') {
|
|
150
|
+
const trimmed = raw.trim();
|
|
151
|
+
return trimmed ? { prefix: [trimmed], decision: defaultDecision } : null;
|
|
152
|
+
}
|
|
153
|
+
if (Array.isArray(raw)) {
|
|
154
|
+
const prefix = raw.map((x) => String(x || '').trim()).filter(Boolean);
|
|
155
|
+
return prefix.length ? { prefix, decision: defaultDecision } : null;
|
|
156
|
+
}
|
|
157
|
+
if (typeof raw === 'object' && Array.isArray(raw.prefix)) {
|
|
158
|
+
const prefix = raw.prefix.map((x) => String(x || '').trim()).filter(Boolean);
|
|
159
|
+
const decision = raw.decision === 'deny' ? 'deny' : defaultDecision;
|
|
160
|
+
return prefix.length ? { prefix, decision } : null;
|
|
161
|
+
}
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const TRUSTED_SYSTEM_BIN_DIRS = [
|
|
166
|
+
'/bin',
|
|
167
|
+
'/usr/bin',
|
|
168
|
+
'/sbin',
|
|
169
|
+
'/usr/sbin',
|
|
170
|
+
'/usr/local/bin',
|
|
171
|
+
'/opt/homebrew/bin',
|
|
172
|
+
];
|
|
173
|
+
|
|
174
|
+
function isBareCommandName(cmd) {
|
|
175
|
+
return Boolean(cmd) && !cmd.includes('/') && !cmd.includes('\\');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function isTrustedSystemBinaryPath(cmd, expectedBase) {
|
|
179
|
+
if (!cmd || !expectedBase) return false;
|
|
180
|
+
if (path.basename(cmd) !== expectedBase) return false;
|
|
181
|
+
if (!path.isAbsolute(cmd)) return false;
|
|
182
|
+
const dir = path.dirname(cmd);
|
|
183
|
+
if (TRUSTED_SYSTEM_BIN_DIRS.includes(dir)) return true;
|
|
184
|
+
const real = realpathSafe(cmd);
|
|
185
|
+
return path.basename(real) === expectedBase && TRUSTED_SYSTEM_BIN_DIRS.includes(path.dirname(real));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function expandShortFlagSet(args) {
|
|
189
|
+
const flags = new Set();
|
|
190
|
+
for (const a of args) {
|
|
191
|
+
if (typeof a !== 'string' || !a.startsWith('-') || a.length < 2) continue;
|
|
192
|
+
// Catch both full GNU long options (`--recursive`, `--force`) and unambiguous GNU prefixes (`--recurs`, `--forc`)
|
|
193
|
+
if (a.startsWith('--')) {
|
|
194
|
+
if (a.length >= 3 && '--recursive'.startsWith(a)) flags.add('r');
|
|
195
|
+
else if (a.length >= 3 && '--force'.startsWith(a)) flags.add('f');
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
for (let i = 1; i < a.length; i++) {
|
|
199
|
+
const ch = a[i];
|
|
200
|
+
flags.add(ch === 'R' ? 'r' : ch);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return flags;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function matchesArgvPrefix(argv, prefix, { mode = 'allow' } = {}) {
|
|
207
|
+
if (!Array.isArray(prefix) || !prefix.length || argv.length < prefix.length) return false;
|
|
208
|
+
const cmd = argv[0];
|
|
209
|
+
const cmdBase = path.basename(cmd);
|
|
210
|
+
const p0 = prefix[0];
|
|
211
|
+
|
|
212
|
+
if (p0 !== '*') {
|
|
213
|
+
if (mode === 'deny') {
|
|
214
|
+
// Defense-in-depth for deny rules: match exact path, realpath, or basename
|
|
215
|
+
const cmdReal = cmd.includes('/') ? realpathSafe(cmd) : cmd;
|
|
216
|
+
const p0Real = p0.includes('/') ? realpathSafe(p0) : p0;
|
|
217
|
+
if (p0 !== cmd && p0 !== cmdBase && p0Real !== cmdReal) return false;
|
|
218
|
+
} else {
|
|
219
|
+
// Strict allow-rule executable binding: NEVER allow `./git` to match bare allow rule `["git", ...]`!
|
|
220
|
+
if (isBareCommandName(p0)) {
|
|
221
|
+
if (!((isBareCommandName(cmd) && cmd === p0) || isTrustedSystemBinaryPath(cmd, p0))) {
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
} else {
|
|
225
|
+
if (cmd !== p0 && realpathSafe(cmd) !== realpathSafe(p0)) return false;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
for (let i = 1; i < prefix.length; i++) {
|
|
231
|
+
const pat = prefix[i];
|
|
232
|
+
if (pat === '*') continue;
|
|
233
|
+
if (pat.endsWith('*')) {
|
|
234
|
+
if (!argv[i].startsWith(pat.slice(0, -1))) return false;
|
|
235
|
+
} else if (argv[i] !== pat) {
|
|
236
|
+
// For deny rules with combined short flags (e.g. `['rm', '-rf']`), also catch `-fr` or `-r -f`!
|
|
237
|
+
if (mode === 'deny' && pat.startsWith('-') && !pat.startsWith('--') && pat.length > 2) {
|
|
238
|
+
const present = expandShortFlagSet(argv.slice(1));
|
|
239
|
+
const allPresent = [...pat.slice(1)].every((ch) => present.has(ch));
|
|
240
|
+
if (allPresent) continue;
|
|
241
|
+
}
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export function evaluateExecPolicy({
|
|
249
|
+
command,
|
|
250
|
+
args = [],
|
|
251
|
+
allowRules = null,
|
|
252
|
+
denyRules = null,
|
|
253
|
+
} = {}) {
|
|
254
|
+
const bin = String(command || '').trim();
|
|
255
|
+
if (!bin) return { ok: false, decision: 'deny', reason: 'exec_missing_command' };
|
|
256
|
+
const argv = [bin, ...(Array.isArray(args) ? args.map(String) : [])];
|
|
257
|
+
|
|
258
|
+
const denies = [];
|
|
259
|
+
const allows = [];
|
|
260
|
+
for (const r of Array.isArray(denyRules) ? denyRules : []) {
|
|
261
|
+
const norm = normalizeExecRule(r, 'deny');
|
|
262
|
+
if (norm) denies.push(norm);
|
|
263
|
+
}
|
|
264
|
+
if (Array.isArray(allowRules)) {
|
|
265
|
+
for (const r of allowRules) {
|
|
266
|
+
const norm = normalizeExecRule(r, 'allow');
|
|
267
|
+
if (!norm) continue;
|
|
268
|
+
if (norm.decision === 'deny') denies.push(norm);
|
|
269
|
+
else allows.push(norm);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
for (const d of denies) {
|
|
274
|
+
if (matchesArgvPrefix(argv, d.prefix, { mode: 'deny' })) {
|
|
275
|
+
return { ok: false, decision: 'deny', reason: `exec_policy_denied:${d.prefix.join(' ')}` };
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (Array.isArray(allowRules)) {
|
|
280
|
+
for (const a of allows) {
|
|
281
|
+
if (matchesArgvPrefix(argv, a.prefix, { mode: 'allow' })) {
|
|
282
|
+
return { ok: true, decision: 'allow', matchedRule: a.prefix };
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return { ok: false, decision: 'deny', reason: `exec_command_not_allowed:${path.basename(bin)}` };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return { ok: true, decision: 'allow', matchedRule: null };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export function buildSeatbeltProfile({
|
|
292
|
+
cwd,
|
|
293
|
+
command = null,
|
|
294
|
+
extraReadPaths = [],
|
|
295
|
+
protectedSubpaths = PROTECTED_CWD_SUBPATHS,
|
|
296
|
+
allowNetwork = false,
|
|
297
|
+
} = {}) {
|
|
298
|
+
const realCwd = realpathSafe(cwd || process.cwd());
|
|
299
|
+
const realHome = realpathSafe(os.homedir());
|
|
300
|
+
const realTmp = realpathSafe(os.tmpdir());
|
|
301
|
+
|
|
302
|
+
if (isUnsafeSandboxCwd(realCwd, realHome)) {
|
|
303
|
+
throw new Error(`sandbox_unsafe_cwd:${realCwd}`);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const readAllows = new Set([
|
|
307
|
+
'/usr',
|
|
308
|
+
'/bin',
|
|
309
|
+
'/sbin',
|
|
310
|
+
'/System',
|
|
311
|
+
'/Library/Frameworks',
|
|
312
|
+
'/Library/Apple',
|
|
313
|
+
'/Library/Developer/CommandLineTools',
|
|
314
|
+
'/Applications/Xcode.app/Contents/Developer',
|
|
315
|
+
'/private/var/db',
|
|
316
|
+
'/private/etc',
|
|
317
|
+
'/etc',
|
|
318
|
+
'/dev',
|
|
319
|
+
'/opt/homebrew',
|
|
320
|
+
'/nix',
|
|
321
|
+
realCwd,
|
|
322
|
+
realTmp,
|
|
323
|
+
'/tmp',
|
|
324
|
+
'/private/tmp',
|
|
325
|
+
]);
|
|
326
|
+
for (const p of safeRuntimeReadPrefixes(command, realHome)) {
|
|
327
|
+
readAllows.add(p);
|
|
328
|
+
}
|
|
329
|
+
for (const p of extraReadPaths || []) {
|
|
330
|
+
if (!p) continue;
|
|
331
|
+
const rp = realpathSafe(p);
|
|
332
|
+
if (!isUnsafeSandboxCwd(rp, realHome)) readAllows.add(rp);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const readClauses = [...readAllows].map((p) => `(subpath "${escapeSbpl(p)}")`).join(' ');
|
|
336
|
+
const writeClauses = [realCwd, realTmp, '/tmp', '/private/tmp']
|
|
337
|
+
.map((p) => `(subpath "${escapeSbpl(p)}")`)
|
|
338
|
+
.join(' ');
|
|
339
|
+
|
|
340
|
+
const machServices = [
|
|
341
|
+
'(global-name "com.apple.system.logger")',
|
|
342
|
+
'(global-name "com.apple.system.notification_center")',
|
|
343
|
+
];
|
|
344
|
+
if (allowNetwork) {
|
|
345
|
+
machServices.push(
|
|
346
|
+
'(global-name "com.apple.SystemConfiguration.configd")',
|
|
347
|
+
'(global-name "com.apple.SystemConfiguration.DNSConfiguration")',
|
|
348
|
+
'(global-name "com.apple.mDNSResponder")',
|
|
349
|
+
'(global-name "com.apple.TrustEvaluationAgent")',
|
|
350
|
+
'(global-name "com.apple.SecurityServer")',
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const lines = [
|
|
355
|
+
'(version 1)',
|
|
356
|
+
'(deny default)',
|
|
357
|
+
'(allow process-exec)',
|
|
358
|
+
'(allow process-fork)',
|
|
359
|
+
'(allow signal (target same-sandbox))',
|
|
360
|
+
'(allow process-info* (target same-sandbox))',
|
|
361
|
+
'(allow sysctl-read)',
|
|
362
|
+
`(allow mach-lookup ${machServices.join(' ')})`,
|
|
363
|
+
'(allow file-read-metadata)',
|
|
364
|
+
`(allow file-read* (literal "/") ${readClauses})`,
|
|
365
|
+
'(allow file-read* file-write* (literal "/dev/null") (literal "/dev/zero") (literal "/dev/random") (literal "/dev/urandom"))',
|
|
366
|
+
'(allow file-ioctl (literal "/dev/null") (literal "/dev/tty") (literal "/dev/dtracehelper"))',
|
|
367
|
+
`(allow file-write* ${writeClauses})`,
|
|
368
|
+
];
|
|
369
|
+
|
|
370
|
+
if (allowNetwork) {
|
|
371
|
+
// Allow outbound IP + mDNSResponder DNS socket ONLY (blocks SSH_AUTH_SOCK & other AF_UNIX sockets, blocks inbound bind/listen!)
|
|
372
|
+
lines.push('(allow system-socket)');
|
|
373
|
+
lines.push('(allow network-outbound (remote ip))');
|
|
374
|
+
lines.push('(allow network-outbound (literal "/private/var/run/mDNSResponder"))');
|
|
375
|
+
} else {
|
|
376
|
+
lines.push('(deny network*)');
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Last-match-wins: lock sensitive policy & VCS paths (plus resolved symlink targets) inside writable cwd as read-only
|
|
380
|
+
const deniedWriteTargets = new Set();
|
|
381
|
+
for (const rel of protectedSubpaths || []) {
|
|
382
|
+
if (!rel) continue;
|
|
383
|
+
const full = path.join(realCwd, rel);
|
|
384
|
+
deniedWriteTargets.add(full);
|
|
385
|
+
if (fs.existsSync(full)) {
|
|
386
|
+
const resolved = realpathSafe(full);
|
|
387
|
+
if (resolved && resolved !== realCwd) deniedWriteTargets.add(resolved);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
for (const full of deniedWriteTargets) {
|
|
391
|
+
lines.push(`(deny file-write* (subpath "${escapeSbpl(full)}") (literal "${escapeSbpl(full)}"))`);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Defense-in-depth: unconditionally deny sensitive $HOME credential dirs at profile tail
|
|
395
|
+
const sensitiveClauses = SENSITIVE_HOME_SUBDIRS
|
|
396
|
+
.map((rel) => `(subpath "${escapeSbpl(path.join(realHome, rel))}")`)
|
|
397
|
+
.join(' ');
|
|
398
|
+
lines.push(`(deny file-read* file-write* ${sensitiveClauses})`);
|
|
399
|
+
|
|
400
|
+
return lines.join('\n');
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export function buildBwrapArgs({
|
|
404
|
+
cwd,
|
|
405
|
+
command,
|
|
406
|
+
args = [],
|
|
407
|
+
env = null,
|
|
408
|
+
protectedSubpaths = PROTECTED_CWD_SUBPATHS,
|
|
409
|
+
allowNetwork = false,
|
|
410
|
+
} = {}) {
|
|
411
|
+
const realCwd = realpathSafe(cwd || process.cwd());
|
|
412
|
+
const realHome = realpathSafe(os.homedir());
|
|
413
|
+
if (isUnsafeSandboxCwd(realCwd, realHome)) {
|
|
414
|
+
throw new Error(`sandbox_unsafe_cwd:${realCwd}`);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const bwrapArgs = [
|
|
418
|
+
'--unshare-user',
|
|
419
|
+
'--unshare-pid',
|
|
420
|
+
'--unshare-ipc',
|
|
421
|
+
'--unshare-uts',
|
|
422
|
+
'--new-session',
|
|
423
|
+
'--cap-drop', 'ALL',
|
|
424
|
+
'--die-with-parent',
|
|
425
|
+
'--clearenv',
|
|
426
|
+
];
|
|
427
|
+
if (!allowNetwork) bwrapArgs.push('--unshare-net');
|
|
428
|
+
|
|
429
|
+
const safeEnv = env || buildSanitizedEnv({ sandboxHome: realCwd });
|
|
430
|
+
for (const [k, v] of Object.entries(safeEnv)) {
|
|
431
|
+
bwrapArgs.push('--setenv', String(k), String(v));
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
for (const ro of ['/usr', '/bin', '/sbin', '/lib', '/lib64', '/etc', '/opt/homebrew', '/nix', '/snap']) {
|
|
435
|
+
if (fs.existsSync(ro)) bwrapArgs.push('--ro-bind', ro, ro);
|
|
436
|
+
}
|
|
437
|
+
for (const p of safeRuntimeReadPrefixes(command, realHome)) {
|
|
438
|
+
if (fs.existsSync(p)) bwrapArgs.push('--ro-bind', p, p);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
bwrapArgs.push(
|
|
442
|
+
'--proc', '/proc',
|
|
443
|
+
'--dev', '/dev',
|
|
444
|
+
'--tmpfs', '/tmp',
|
|
445
|
+
'--bind', realCwd, realCwd,
|
|
446
|
+
);
|
|
447
|
+
|
|
448
|
+
// Re-mount existing protected policy & VCS paths inside cwd as read-only
|
|
449
|
+
for (const rel of protectedSubpaths || []) {
|
|
450
|
+
if (!rel) continue;
|
|
451
|
+
const full = path.join(realCwd, rel);
|
|
452
|
+
if (fs.existsSync(full)) {
|
|
453
|
+
bwrapArgs.push('--ro-bind', full, full);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
bwrapArgs.push(
|
|
458
|
+
'--chdir', realCwd,
|
|
459
|
+
'--',
|
|
460
|
+
String(command),
|
|
461
|
+
...(Array.isArray(args) ? args.map(String) : []),
|
|
462
|
+
);
|
|
463
|
+
return bwrapArgs;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// Spawn with detached process-group kill on timeout/abort and streaming byte caps (no unbounded RAM buffer).
|
|
467
|
+
function spawnBoundedProcess(bin, argv, { cwd, env, timeoutMs, maxBuffer, signal }) {
|
|
468
|
+
return new Promise((resolve, reject) => {
|
|
469
|
+
if (signal?.aborted) {
|
|
470
|
+
reject(new Error('sandbox_exec_aborted'));
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const child = spawn(bin, argv, {
|
|
475
|
+
cwd,
|
|
476
|
+
env,
|
|
477
|
+
detached: process.platform !== 'win32',
|
|
478
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
const cap = Math.max(4096, Number(maxBuffer || 4 * 1024 * 1024));
|
|
482
|
+
const stdoutChunks = [];
|
|
483
|
+
const stderrChunks = [];
|
|
484
|
+
let stdoutBytes = 0;
|
|
485
|
+
let stderrBytes = 0;
|
|
486
|
+
let stdoutTruncated = false;
|
|
487
|
+
let stderrTruncated = false;
|
|
488
|
+
let settled = false;
|
|
489
|
+
let killedReason = null;
|
|
490
|
+
|
|
491
|
+
function killGroup() {
|
|
492
|
+
if (!child.pid) return;
|
|
493
|
+
try {
|
|
494
|
+
if (process.platform !== 'win32') {
|
|
495
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
496
|
+
} else {
|
|
497
|
+
child.kill('SIGKILL');
|
|
498
|
+
}
|
|
499
|
+
} catch {
|
|
500
|
+
try { child.kill('SIGKILL'); } catch { /* ignore */ }
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const timer = setTimeout(() => {
|
|
505
|
+
killedReason = `sandbox_exec_timeout:${timeoutMs}ms`;
|
|
506
|
+
killGroup();
|
|
507
|
+
}, timeoutMs);
|
|
508
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
509
|
+
|
|
510
|
+
const onAbort = () => {
|
|
511
|
+
killedReason = 'sandbox_exec_aborted';
|
|
512
|
+
killGroup();
|
|
513
|
+
};
|
|
514
|
+
if (signal) signal.addEventListener('abort', onAbort, { once: true });
|
|
515
|
+
|
|
516
|
+
function cleanup() {
|
|
517
|
+
clearTimeout(timer);
|
|
518
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
child.stdout?.on('data', (chunk) => {
|
|
522
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
523
|
+
if (stdoutBytes < cap) {
|
|
524
|
+
const take = Math.min(buf.length, cap - stdoutBytes);
|
|
525
|
+
stdoutChunks.push(take === buf.length ? buf : buf.subarray(0, take));
|
|
526
|
+
stdoutBytes += take;
|
|
527
|
+
if (take < buf.length) stdoutTruncated = true;
|
|
528
|
+
} else {
|
|
529
|
+
stdoutTruncated = true;
|
|
530
|
+
}
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
child.stderr?.on('data', (chunk) => {
|
|
534
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
535
|
+
if (stderrBytes < cap) {
|
|
536
|
+
const take = Math.min(buf.length, cap - stderrBytes);
|
|
537
|
+
stderrChunks.push(take === buf.length ? buf : buf.subarray(0, take));
|
|
538
|
+
stderrBytes += take;
|
|
539
|
+
if (take < buf.length) stderrTruncated = true;
|
|
540
|
+
} else {
|
|
541
|
+
stderrTruncated = true;
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
child.once('error', (err) => {
|
|
546
|
+
if (settled) return;
|
|
547
|
+
settled = true;
|
|
548
|
+
cleanup();
|
|
549
|
+
killGroup();
|
|
550
|
+
reject(err);
|
|
551
|
+
});
|
|
552
|
+
|
|
553
|
+
child.once('close', (code, sig) => {
|
|
554
|
+
if (settled) return;
|
|
555
|
+
settled = true;
|
|
556
|
+
cleanup();
|
|
557
|
+
const stdout = Buffer.concat(stdoutChunks).toString('utf8');
|
|
558
|
+
const stderr = Buffer.concat(stderrChunks).toString('utf8');
|
|
559
|
+
if (killedReason) {
|
|
560
|
+
const err = new Error(killedReason);
|
|
561
|
+
err.stdout = stdout;
|
|
562
|
+
err.stderr = stderr;
|
|
563
|
+
err.killed = true;
|
|
564
|
+
reject(err);
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
if (code !== 0) {
|
|
568
|
+
const msg = stderr.trim() || stdout.trim() || `exit_${code ?? sig}`;
|
|
569
|
+
const err = new Error(`Command failed (${code ?? sig}): ${msg.slice(0, 500)}`);
|
|
570
|
+
err.code = code;
|
|
571
|
+
err.signal = sig;
|
|
572
|
+
err.stdout = stdout;
|
|
573
|
+
err.stderr = stderr;
|
|
574
|
+
reject(err);
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
resolve({ stdout, stderr, stdoutTruncated, stderrTruncated });
|
|
578
|
+
});
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// Snapshot EVERY prefix segment of a protected subpath via lstatSync (never following symlinks!)
|
|
583
|
+
export function snapshotProtectedPathChain(realCwd, rel) {
|
|
584
|
+
const segs = String(rel || '').split(/[\\/]+/).filter(Boolean);
|
|
585
|
+
const chain = [];
|
|
586
|
+
let cur = realCwd;
|
|
587
|
+
for (let i = 0; i < segs.length; i++) {
|
|
588
|
+
cur = path.join(cur, segs[i]);
|
|
589
|
+
let st = null;
|
|
590
|
+
try { st = fs.lstatSync(cur); } catch { st = null; }
|
|
591
|
+
if (!st) {
|
|
592
|
+
chain.push({ seg: segs[i], full: cur, kind: 'missing', linkTarget: null });
|
|
593
|
+
// Once a prefix segment is missing, all deeper segments are necessarily missing too
|
|
594
|
+
for (let j = i + 1; j < segs.length; j++) {
|
|
595
|
+
cur = path.join(cur, segs[j]);
|
|
596
|
+
chain.push({ seg: segs[j], full: cur, kind: 'missing', linkTarget: null });
|
|
597
|
+
}
|
|
598
|
+
break;
|
|
599
|
+
}
|
|
600
|
+
if (st.isSymbolicLink()) {
|
|
601
|
+
let target = null;
|
|
602
|
+
try { target = fs.readlinkSync(cur); } catch { target = null; }
|
|
603
|
+
chain.push({ seg: segs[i], full: cur, kind: 'symlink', linkTarget: target });
|
|
604
|
+
// Never traverse past a pre-existing symlink
|
|
605
|
+
break;
|
|
606
|
+
}
|
|
607
|
+
chain.push({ seg: segs[i], full: cur, kind: st.isDirectory() ? 'dir' : 'other', linkTarget: null });
|
|
608
|
+
}
|
|
609
|
+
return { rel, chain };
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// Reconcile a protected subpath after bwrap execution:
|
|
613
|
+
// - Detects & unlinks newly-created intermediate symlinks (EVEN dangling symlinks where deeper lstat returns ENOENT!)
|
|
614
|
+
// - Removes newly-created final protected targets without traversing symlinks outside realCwd
|
|
615
|
+
// - Preserves pre-existing symlinks (never deletes a symlink that already existed before execution)
|
|
616
|
+
export function reconcileProtectedPathChain(snapshot) {
|
|
617
|
+
const { chain } = snapshot || {};
|
|
618
|
+
if (!Array.isArray(chain) || !chain.length) return false;
|
|
619
|
+
let violated = false;
|
|
620
|
+
for (let i = 0; i < chain.length; i++) {
|
|
621
|
+
const before = chain[i];
|
|
622
|
+
let st = null;
|
|
623
|
+
try { st = fs.lstatSync(before.full); } catch { st = null; }
|
|
624
|
+
if (!st) break; // Segment does not exist after execution
|
|
625
|
+
|
|
626
|
+
if (st.isSymbolicLink()) {
|
|
627
|
+
if (before.kind === 'symlink') {
|
|
628
|
+
// Pre-existing symlink: never unlink it; flag violation only if its target was mutated
|
|
629
|
+
let nowTarget = null;
|
|
630
|
+
try { nowTarget = fs.readlinkSync(before.full); } catch { nowTarget = null; }
|
|
631
|
+
if (nowTarget !== before.linkTarget) violated = true;
|
|
632
|
+
return violated;
|
|
633
|
+
}
|
|
634
|
+
// Newly created symlink (or non-symlink replaced with symlink) at an intermediate or final segment:
|
|
635
|
+
// unlink the symlink itself directly without ever traversing outside realCwd!
|
|
636
|
+
try { fs.unlinkSync(before.full); } catch { /* best-effort */ }
|
|
637
|
+
return true;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// Pre-existing symlink replaced by a regular file or directory -> flag violation
|
|
641
|
+
if (before.kind === 'symlink') {
|
|
642
|
+
return true;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// Final segment was missing before execution and now exists
|
|
646
|
+
if (i === chain.length - 1 && before.kind === 'missing') {
|
|
647
|
+
try { fs.rmSync(before.full, { recursive: true, force: true }); } catch { /* best-effort */ }
|
|
648
|
+
return true;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return violated;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
export async function runSandboxedExec({
|
|
655
|
+
command,
|
|
656
|
+
args = [],
|
|
657
|
+
cwd = process.cwd(),
|
|
658
|
+
allowEnv = DEFAULT_ENV_ALLOWLIST,
|
|
659
|
+
extraEnv = null,
|
|
660
|
+
baseEnv = process.env,
|
|
661
|
+
timeoutMs = 15_000,
|
|
662
|
+
maxBuffer = 4 * 1024 * 1024,
|
|
663
|
+
sandbox = 'os', // 'os' | 'none'
|
|
664
|
+
requireSandbox = true,
|
|
665
|
+
allowNetwork = false,
|
|
666
|
+
protectedSubpaths = PROTECTED_CWD_SUBPATHS,
|
|
667
|
+
execRunner = null,
|
|
668
|
+
signal = null,
|
|
669
|
+
} = {}) {
|
|
670
|
+
const bin = String(command || '').trim();
|
|
671
|
+
if (!bin) throw new Error('sandbox_exec: command is required');
|
|
672
|
+
const cmdArgs = Array.isArray(args) ? args.map(String) : [];
|
|
673
|
+
const realCwd = realpathSafe(cwd);
|
|
674
|
+
const env = buildSanitizedEnv({ allowEnv, extraEnv, baseEnv, sandboxHome: realCwd });
|
|
675
|
+
const effTimeout = Math.min(60_000, Math.max(500, Number(timeoutMs || 15_000)));
|
|
676
|
+
|
|
677
|
+
if (typeof execRunner === 'function') {
|
|
678
|
+
return execRunner({
|
|
679
|
+
command: bin,
|
|
680
|
+
args: cmdArgs,
|
|
681
|
+
cwd: realCwd,
|
|
682
|
+
env,
|
|
683
|
+
timeoutMs: effTimeout,
|
|
684
|
+
maxBuffer,
|
|
685
|
+
allowNetwork,
|
|
686
|
+
signal,
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
if (sandbox === 'none') {
|
|
691
|
+
if (requireSandbox) throw new Error('sandbox_required_cannot_disable');
|
|
692
|
+
const r = await spawnBoundedProcess(bin, cmdArgs, { cwd: realCwd, env, timeoutMs: effTimeout, maxBuffer, signal });
|
|
693
|
+
return { ok: true, exitCode: 0, stdout: r.stdout, stderr: r.stderr, truncated: r.stdoutTruncated || r.stderrTruncated, sandbox: 'none' };
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
const detected = detectOsSandbox();
|
|
697
|
+
if (!detected.available) {
|
|
698
|
+
if (requireSandbox) {
|
|
699
|
+
throw new Error(`sandbox_unavailable: no OS sandbox binary found on ${process.platform}`);
|
|
700
|
+
}
|
|
701
|
+
const r = await spawnBoundedProcess(bin, cmdArgs, { cwd: realCwd, env, timeoutMs: effTimeout, maxBuffer, signal });
|
|
702
|
+
return { ok: true, exitCode: 0, stdout: r.stdout, stderr: r.stderr, truncated: r.stdoutTruncated || r.stderrTruncated, sandbox: 'fallback_unsandboxed' };
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
if (detected.kind === 'seatbelt') {
|
|
706
|
+
const profile = buildSeatbeltProfile({ cwd: realCwd, command: bin, protectedSubpaths, allowNetwork });
|
|
707
|
+
const r = await spawnBoundedProcess(detected.bin, ['-p', profile, bin, ...cmdArgs], {
|
|
708
|
+
cwd: realCwd,
|
|
709
|
+
env,
|
|
710
|
+
timeoutMs: effTimeout,
|
|
711
|
+
maxBuffer,
|
|
712
|
+
signal,
|
|
713
|
+
});
|
|
714
|
+
return { ok: true, exitCode: 0, stdout: r.stdout, stderr: r.stderr, truncated: r.stdoutTruncated || r.stderrTruncated, sandbox: 'seatbelt' };
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// Snapshot every prefix segment of each protected subpath via lstatSync before bwrap execution
|
|
718
|
+
const protectedSnapshots = (protectedSubpaths || [])
|
|
719
|
+
.filter(Boolean)
|
|
720
|
+
.map((rel) => snapshotProtectedPathChain(realCwd, rel));
|
|
721
|
+
|
|
722
|
+
const bwrapArgs = buildBwrapArgs({ cwd: realCwd, command: bin, args: cmdArgs, env, protectedSubpaths, allowNetwork });
|
|
723
|
+
let r;
|
|
724
|
+
try {
|
|
725
|
+
r = await spawnBoundedProcess(detected.bin, bwrapArgs, {
|
|
726
|
+
cwd: realCwd,
|
|
727
|
+
env,
|
|
728
|
+
timeoutMs: effTimeout,
|
|
729
|
+
maxBuffer,
|
|
730
|
+
signal,
|
|
731
|
+
});
|
|
732
|
+
} finally {
|
|
733
|
+
const createdProtected = [];
|
|
734
|
+
for (const snap of protectedSnapshots) {
|
|
735
|
+
if (reconcileProtectedPathChain(snap)) {
|
|
736
|
+
createdProtected.push(snap.rel);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
if (createdProtected.length) {
|
|
740
|
+
throw new Error(`sandbox_protected_path_created:${createdProtected.join(',')}`);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
return { ok: true, exitCode: 0, stdout: r.stdout, stderr: r.stderr, truncated: r.stdoutTruncated || r.stderrTruncated, sandbox: 'bwrap' };
|
|
744
|
+
}
|