aegisone 1.0.39 → 1.0.41

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.
Files changed (122) hide show
  1. package/LICENSING.md +186 -0
  2. package/README.md +2 -2
  3. package/bin/aegis.js +1 -1
  4. package/package.json +3 -2
  5. package/scripts/predist.mjs +1 -1
  6. package/src/child.js +1 -1
  7. package/src/permissions.js +1 -1
  8. package/vendor/cli/package.json +4 -2
  9. package/vendor/cli/src/app.js +1 -1
  10. package/vendor/cli/src/chatflow.js +1 -1
  11. package/vendor/cli/src/commands.js +3 -1
  12. package/vendor/cli/src/config.js +1 -1
  13. package/vendor/cli/src/diff.js +1 -1
  14. package/vendor/cli/src/diffview.js +1 -1
  15. package/vendor/cli/src/engine.js +1 -1
  16. package/vendor/cli/src/history.js +1 -1
  17. package/vendor/cli/src/models.js +1 -1
  18. package/vendor/cli/src/overlays.js +1 -1
  19. package/vendor/cli/src/panels.js +1 -1
  20. package/vendor/cli/vendor/client/brain-catalog.js +1 -1
  21. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  22. package/vendor/cli/vendor/client/credits.js +45 -0
  23. package/vendor/cli/vendor/client/foreign-sessions.js +3 -0
  24. package/vendor/cli/vendor/client/naming.js +1 -1
  25. package/vendor/cli/vendor/client/prefs.js +1 -1
  26. package/vendor/cli/vendor/client/session-search.js +3 -0
  27. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  28. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  29. package/vendor/cli/vendor/desktop/lib/local/integrity.js +42 -2
  30. package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +206 -0
  31. package/vendor/cli/vendor/desktop/lib/local/perm-store.js +298 -0
  32. package/vendor/cli/vendor/desktop/lib/local/perm-write.js +199 -0
  33. package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
  34. package/vendor/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
  35. package/vendor/cli/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
  36. package/vendor/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
  37. package/vendor/cli/vendor/desktop/lib/local/sandbox.js +493 -0
  38. package/vendor/cli/vendor/desktop/lib/local/shell.js +155 -20
  39. package/vendor/cli/vendor/desktop/lib/local/tools.js +29 -4
  40. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  41. package/vendor/cli/vendor/desktop/main.js +774 -37
  42. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
  43. package/vendor/cli/vendor/mcp/admission.js +3 -0
  44. package/vendor/cli/vendor/mcp/server.js +1 -1
  45. package/vendor/cli/vendor/one/src/child.js +1 -1
  46. package/vendor/cli/vendor/one/src/permissions.js +1 -1
  47. package/vendor/desktop/bin/aegis.js +1 -1
  48. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  49. package/vendor/desktop/lib/local/engine.js +1 -1
  50. package/vendor/desktop/lib/local/integrity.js +42 -2
  51. package/vendor/desktop/lib/local/perm-rules.js +206 -0
  52. package/vendor/desktop/lib/local/perm-store.js +298 -0
  53. package/vendor/desktop/lib/local/perm-write.js +199 -0
  54. package/vendor/desktop/lib/local/pro-sessions.js +3 -0
  55. package/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
  56. package/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
  57. package/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
  58. package/vendor/desktop/lib/local/sandbox.js +493 -0
  59. package/vendor/desktop/lib/local/shell.js +155 -20
  60. package/vendor/desktop/lib/local/tools.js +29 -4
  61. package/vendor/desktop/lib/settings.js +1 -1
  62. package/vendor/desktop/lib/sync/memory-store.js +3 -0
  63. package/vendor/desktop/main.js +774 -37
  64. package/vendor/desktop/package.json +19 -7
  65. package/vendor/desktop/preload.js +1 -1
  66. package/vendor/desktop/renderer/app.js +5 -1
  67. package/vendor/desktop/renderer/diff.js +1 -1
  68. package/vendor/desktop/renderer/diffview.js +1 -1
  69. package/vendor/desktop/renderer/index.html +221 -5
  70. package/vendor/desktop/renderer/provider-mark.js +1 -1
  71. package/vendor/desktop/renderer/provider-toolbar.js +1 -1
  72. package/vendor/desktop/renderer/providers.js +1 -1
  73. package/vendor/desktop/renderer/style.css +223 -6
  74. package/vendor/desktop/renderer/usage.js +1 -1
  75. package/vendor/desktop/vendor/brain-catalog.js +1 -1
  76. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  77. package/vendor/desktop/vendor/credits.js +45 -0
  78. package/vendor/desktop/vendor/faces/cli/package.json +3 -2
  79. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  80. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
  81. package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -1
  82. package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
  83. package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
  84. package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
  85. package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
  86. package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
  87. package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
  88. package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
  89. package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
  90. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
  91. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
  92. package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +45 -0
  93. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +3 -0
  94. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
  95. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
  96. package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +3 -0
  97. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  98. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  99. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  100. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +3 -0
  101. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -0
  102. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +3 -0
  103. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
  104. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +3 -0
  105. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-bwrap.js +3 -0
  106. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +3 -0
  107. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox.js +3 -0
  108. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
  109. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  110. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  111. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -2
  112. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
  113. package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +3 -0
  114. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
  115. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
  116. package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +1 -1
  117. package/vendor/desktop/vendor/foreign-sessions.js +3 -0
  118. package/vendor/desktop/vendor/naming.js +1 -1
  119. package/vendor/desktop/vendor/prefs.js +1 -1
  120. package/vendor/desktop/vendor/sandbox/provenance.json +20 -0
  121. package/vendor/desktop/vendor/sandbox/x64-linux/bwrap +0 -0
  122. package/vendor/desktop/vendor/session-search.js +3 -0
@@ -0,0 +1,316 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * sandbox-bwrap.js — the Linux mechanism behind `sandbox.js` (plan §1d).
10
+ *
11
+ * bubblewrap is a setuid-free user-namespace wrapper: `--ro-bind / /` makes the
12
+ * whole filesystem read-only, and each `--bind` re-opens exactly the paths the
13
+ * policy grants write. That is a capability grant, not a path blacklist — a
14
+ * blacklist is what a determined command walks around.
15
+ *
16
+ * It is NOT a defence against a kernel user-namespace escape, and it is not a
17
+ * network firewall: `--unshare-net` removes the interface, which stops TCP/UDP
18
+ * and leaves nothing to leak through because there is no interface to bind.
19
+ *
20
+ * Unprivileged user namespaces are restricted by AppArmor on Ubuntu 23.10+ and
21
+ * in most container images. When that happens the probe FAILS and the caller
22
+ * gets a loud degrade, not a quiet pass.
23
+ */
24
+
25
+ const { spawnSync } = require('node:child_process');
26
+ const fs = require('node:fs');
27
+ const path = require('node:path');
28
+
29
+ /** Where a vendored bwrap would live, relative to the app dir. */
30
+ const VENDOR_REL = path.join('vendor', 'sandbox');
31
+
32
+ /**
33
+ * Candidate bwrap paths, best first.
34
+ *
35
+ * The vendored copy wins over the system one, for the same reason the
36
+ * comparison set vendors its own: a distro package can be absent, or can be a
37
+ * version whose flags differ, and the sandbox must not vary by distro.
38
+ */
39
+ function candidates(appDir, env = process.env) {
40
+ const out = [];
41
+ if (appDir) {
42
+ // A PACKAGED appDir ends in `app.asar`, and asar is an ARCHIVE: Electron's
43
+ // fs patch answers `statSync` for a virtual path inside it, but there is no
44
+ // directory entry there for `execve`. `electron-builder.yml`'s `asarUnpack`
45
+ // puts the real bytes beside it under `app.asar.unpacked/`, so the spawnable
46
+ // path is the .unpacked one. Both are offered, unpacked FIRST: the virtual
47
+ // path would pass `findBwrap`'s stat and then fail at spawn, which is the
48
+ // "looks available, fails at use" shape the mechanism must never report.
49
+ const unpacked = /app\.asar[\\/]?$/.test(String(appDir))
50
+ ? String(appDir).replace(/app\.asar[\\/]?$/, 'app.asar.unpacked')
51
+ : String(appDir).replace(/app\.asar([\\/])/, 'app.asar.unpacked$1');
52
+ if (unpacked !== appDir) {
53
+ out.push(path.join(unpacked, VENDOR_REL, `${process.arch}-linux`, 'bwrap'));
54
+ out.push(path.join(unpacked, VENDOR_REL, 'linux', 'bwrap'));
55
+ }
56
+ out.push(path.join(appDir, VENDOR_REL, `${process.arch}-linux`, 'bwrap'));
57
+ out.push(path.join(appDir, VENDOR_REL, 'linux', 'bwrap'));
58
+ }
59
+ if (env && env.AEGIS_SANDBOX_BWRAP) out.push(String(env.AEGIS_SANDBOX_BWRAP));
60
+ out.push('/usr/bin/bwrap', '/bin/bwrap', '/usr/local/bin/bwrap');
61
+ return out;
62
+ }
63
+
64
+ /** First candidate that exists and is executable, or null. */
65
+ function findBwrap(appDir, env) {
66
+ for (const c of candidates(appDir, env)) {
67
+ try {
68
+ const st = fs.statSync(c);
69
+ if (st.isFile()) {
70
+ fs.accessSync(c, fs.constants.X_OK);
71
+ return c;
72
+ }
73
+ } catch {
74
+ /* try the next one */
75
+ }
76
+ }
77
+ return null;
78
+ }
79
+
80
+ /**
81
+ * Execute the probe for real. Never throws.
82
+ *
83
+ * `--ro-bind / /` alone is the cheapest thing that still proves the kernel
84
+ * granted a user namespace: without that grant bwrap cannot even perform the
85
+ * bind and exits non-zero. `spawnSync` with a short timeout because a hung
86
+ * probe would hang the first tool call of every turn.
87
+ *
88
+ * @returns {{ available: boolean, path: string|null, reason: string|null, probed: boolean }}
89
+ */
90
+ function detect({ appDir, env = process.env, platform = process.platform, probe } = {}) {
91
+ if (platform !== 'linux') {
92
+ return { available: false, path: null, reason: `no linux mechanism on ${platform}`, probed: false };
93
+ }
94
+ const bin = findBwrap(appDir, env);
95
+ if (!bin) {
96
+ return { available: false, path: null, reason: 'bwrap not found', probed: false };
97
+ }
98
+ // Injectable so the "unavailable" branch is testable without breaking the
99
+ // host's own user namespaces.
100
+ const run = typeof probe === 'function' ? probe : defaultProbe;
101
+ const res = run(bin);
102
+ if (res && res.ok) return { available: true, path: bin, reason: null, probed: true, mechanism: 'bwrap' };
103
+ return {
104
+ available: false,
105
+ path: bin,
106
+ reason: (res && res.reason) || 'bwrap probe failed (unprivileged user namespaces unavailable?)',
107
+ probed: true,
108
+ };
109
+ }
110
+
111
+ function defaultProbe(bin) {
112
+ try {
113
+ const r = spawnSync(bin, ['--ro-bind', '/', '/', '--dev', '/dev', '--', '/bin/true'], {
114
+ timeout: 5000,
115
+ encoding: 'utf8',
116
+ stdio: ['ignore', 'pipe', 'pipe'],
117
+ });
118
+ if (r.error) return { ok: false, reason: `bwrap probe error: ${r.error.message}` };
119
+ if (r.status !== 0) {
120
+ const why = String(r.stderr || '').trim().split('\n')[0];
121
+ return { ok: false, reason: why || `bwrap probe exited ${r.status}` };
122
+ }
123
+ return { ok: true };
124
+ } catch (e) {
125
+ return { ok: false, reason: `bwrap probe threw: ${e.message}` };
126
+ }
127
+ }
128
+
129
+ /** Is this a special we know how to map onto bwrap argv? */
130
+ function isSpecial(entry, kind) {
131
+ const p = entry && entry.path;
132
+ return Boolean(p && p.type === 'special' && p.value && p.value.kind === kind);
133
+ }
134
+
135
+ /** Resolve an entry's absolute path, or null when it names a special location. */
136
+ function entryPath(entry) {
137
+ const p = entry && entry.path;
138
+ if (!p) return null;
139
+ if (p.type === 'path') return typeof p.path === 'string' && p.path ? p.path : null;
140
+ return null;
141
+ }
142
+
143
+ /**
144
+ * Build the bwrap argv prefix for one command.
145
+ *
146
+ * Takes the ALREADY-NORMALISED policy from `sandbox.js`, so the mode bound
147
+ * (`read-only` cannot carry a write grant) is enforced in one place.
148
+ *
149
+ * Returns `{ ok: true, argv }` where argv is the full command line (bwrap plus
150
+ * the shell invocation), or `{ ok: false, reason }` when the policy cannot be
151
+ * honoured. Callers must treat `ok: false` as "do not run" and show `reason`.
152
+ *
153
+ * Shape, and why each flag:
154
+ * --ro-bind / / everything read-only first; the grants below re-open
155
+ * --dev /dev --proc /proc a command with no /dev or /proc fails obscurely
156
+ * --bind <ws> <ws> the ONE writable tree, when the mode grants it
157
+ * --ro-bind <p> <p> entries that exist with read access inside a write grant
158
+ * --unshare-net no interface at all when network is restricted
159
+ * --die-with-parent a killed turn must not leave the child running
160
+ * --new-session detach the controlling tty (no TIOCSTI injection back)
161
+ */
162
+ function wrap(policyInput, command, opts = {}) {
163
+ const { bwrap, workspace, argv = [], cwd } = opts;
164
+ if (!bwrap) return { ok: false, reason: 'no bwrap binary' };
165
+ const policy = policyInput || {};
166
+ if (policy.mode === 'off') return { ok: false, reason: 'sandbox disabled by policy' };
167
+
168
+ const ws = workspace ? path.resolve(workspace) : null;
169
+ const out = [bwrap, '--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc'];
170
+ const entries = (policy.fileSystem && Array.isArray(policy.fileSystem.entries))
171
+ ? policy.fileSystem.entries
172
+ : [];
173
+
174
+ // Write grants. `root` read is already implied by --ro-bind /; a `root`
175
+ // WRITE grant is refused rather than honoured — it would make the sandbox a
176
+ // no-op while still reporting itself as active, which is the one failure
177
+ // mode this file must not have.
178
+ let rootWrite = false;
179
+ for (const e of entries) {
180
+ if (e.access !== 'write') continue;
181
+ if (isSpecial(e, 'root')) {
182
+ rootWrite = true;
183
+ continue;
184
+ }
185
+ if (isSpecial(e, 'slash_tmp')) {
186
+ out.push('--bind', '/tmp', '/tmp');
187
+ continue;
188
+ }
189
+ const p = entryPath(e);
190
+ if (!p) continue;
191
+ // `missingPathBehavior: 'skip'` means "bind it read-only IF it exists" —
192
+ // `.git` in a non-repo workspace, for instance. bwrap errors on a missing
193
+ // bind source, so existence is decided here, before the spawn.
194
+ let exists = false;
195
+ try {
196
+ fs.statSync(p);
197
+ exists = true;
198
+ } catch {
199
+ exists = false;
200
+ }
201
+ if (!exists) {
202
+ if (e.missingPathBehavior === 'skip') continue;
203
+ return { ok: false, policyFault: true, reason: `sandbox path does not exist: ${p}` };
204
+ }
205
+ out.push('--bind', p, p);
206
+ }
207
+ if (rootWrite) {
208
+ return {
209
+ ok: false,
210
+ policyFault: true,
211
+ reason: 'policy grants write to the filesystem root, which a sandbox cannot honour',
212
+ };
213
+ }
214
+
215
+ // The workspace itself, when the mode says so and the policy did not already
216
+ // name it (defaultPolicy does, so this is the belt to that braces).
217
+ // `read-only` never takes this branch: that is the whole meaning of the mode.
218
+ if (ws && policy.mode === 'workspace-write') {
219
+ let already = false;
220
+ for (const e of entries) {
221
+ const p = entryPath(e);
222
+ if (e.access === 'write' && p && path.resolve(p) === ws) already = true;
223
+ }
224
+ if (!already) out.push('--bind', ws, ws);
225
+ }
226
+
227
+ // Read-only re-grants INSIDE a writable tree (e.g. workspace write but .git
228
+ // read). Applied after the bind so it wins — bwrap's later mounts shadow.
229
+ for (const e of entries) {
230
+ if (e.access !== 'read') continue;
231
+ const p = entryPath(e);
232
+ if (!p) continue;
233
+ try {
234
+ fs.statSync(p);
235
+ } catch {
236
+ if (e.missingPathBehavior === 'skip') continue;
237
+ return { ok: false, policyFault: true, reason: `sandbox path does not exist: ${p}` };
238
+ }
239
+ out.push('--ro-bind', p, p);
240
+ }
241
+
242
+ // Denies, LAST — after every bind and every re-grant, because bwrap mounts
243
+ // shadow in argv order and a deny emitted before a bind is silently undone by
244
+ // it. `--tmpfs` over the path empties it in the child's mount namespace while
245
+ // leaving the parent's untouched.
246
+ //
247
+ // Only paths that resolve inside an already-bound tree can be denied: bwrap
248
+ // has nothing to shadow under a path that was never mounted. A missing path
249
+ // is a hard fault rather than a skip, because `--tmpfs` on a nonexistent path
250
+ // exits non-zero and would otherwise be read as "the sandbox refused the
251
+ // command" — the wrong diagnosis for a typo.
252
+ const denies = (policy.fileSystem && Array.isArray(policy.fileSystem.denies))
253
+ ? policy.fileSystem.denies
254
+ : [];
255
+ for (const d of denies) {
256
+ const p = d && d.path;
257
+ if (!p) continue;
258
+ let st = null;
259
+ try {
260
+ st = fs.statSync(p);
261
+ } catch {
262
+ return { ok: false, policyFault: true, reason: `sandbox deny path does not exist: ${p}` };
263
+ }
264
+ // A FILE cannot be shadowed by --tmpfs (it mounts a directory). Denying one
265
+ // file inside a writable tree needs --ro-bind of /dev/null over it, which is
266
+ // a different mechanism; refuse rather than silently not denying.
267
+ if (!st.isDirectory()) {
268
+ return {
269
+ ok: false,
270
+ policyFault: true,
271
+ reason: `sandbox deny must name a directory, not a file: ${p}`,
272
+ };
273
+ }
274
+ out.push('--tmpfs', p);
275
+ }
276
+
277
+ if (policy.network === 'restricted') out.push('--unshare-net');
278
+ out.push('--die-with-parent', '--new-session');
279
+ if (cwd) out.push('--chdir', cwd);
280
+ out.push('--');
281
+ for (const a of argv) out.push(String(a));
282
+ out.push(String(command));
283
+ return { ok: true, argv: out, policy, guarantee: 'capability' };
284
+ }
285
+
286
+ /**
287
+ * The sentence the UI and the transcript print.
288
+ *
289
+ * Never says "sandboxed" on a host where nothing was enforced — a lie here
290
+ * costs more than the sandbox buys, because it transfers trust the user did not
291
+ * grant.
292
+ */
293
+ function describe(state, policy) {
294
+ if (!state || !state.available) {
295
+ return `sandbox: OFF — ${(state && state.reason) || 'unavailable'} (commands run with full user access)`;
296
+ }
297
+ const mode = (policy && policy.mode) || 'workspace-write';
298
+ const net = (policy && policy.network) === 'open' ? 'network open' : 'network restricted';
299
+ return `sandbox: ${mode} via bwrap — ${net}`;
300
+ }
301
+
302
+ module.exports = {
303
+ name: 'linux',
304
+ mechanism: 'bwrap',
305
+ guarantee: 'capability',
306
+ implemented: true,
307
+ VENDOR_REL,
308
+ candidates,
309
+ findBwrap,
310
+ detect,
311
+ defaultProbe,
312
+ wrap,
313
+ describe,
314
+ isSpecial,
315
+ entryPath,
316
+ };
@@ -0,0 +1,380 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * sandbox-seatbelt.js — the macOS mechanism behind `sandbox.js` (plan §1d).
10
+ *
11
+ * `sandbox.js` holds the POLICY (what a batch may reach) and the cross-platform
12
+ * argv decision (`spawnPlan`). This file holds the one thing that cannot be
13
+ * shared: how macOS enforces a policy. Splitting it out is what lets the pure
14
+ * policy logic stay testable on every host while the platform half is honest
15
+ * about what it does and does not do here.
16
+ *
17
+ * ── Why Sandbox (Seatbelt) and not something else ────────────────────────────
18
+ *
19
+ * `/usr/bin/sandbox-exec -f <profile> <cmd>` is the only userspace sandbox on
20
+ * macOS that exists without entitlements, code signing, or a helper daemon.
21
+ *
22
+ * Two facts worth stating plainly, because they shape every limit below:
23
+ *
24
+ * 1. **`sandbox-exec` is formally deprecated.** Apple has said so for years,
25
+ * and it has NOT been removed — nor can it be, without breaking a large
26
+ * installed base (it is how `xcrun`, package managers and test harnesses
27
+ * confine builds). It is deprecated in the sense of "unsupported, no new
28
+ * features", not "gone". So it is used, and this comment exists so nobody
29
+ * discovers the deprecation later and concludes the code is careless.
30
+ *
31
+ * 2. **The real macOS answer is App Sandbox entitlements**, decided at SIGN
32
+ * time, not at spawn time. Entitlements confine the *whole app* to one
33
+ * fixed posture chosen by the developer; they cannot express "this turn may
34
+ * write here, that turn may not". A per-command bound is what `sandbox.js`
35
+ * is for, so entitlements are the wrong tool for this layer even though
36
+ * they are the stronger one for the app as a whole. They are complementary:
37
+ * entitlements bound the app, Seatbelt bounds the child.
38
+ *
39
+ * ── What this is NOT ─────────────────────────────────────────────────────────
40
+ *
41
+ * Seatbelt's file model is *allow-by-default then narrow with denies*, which is
42
+ * the opposite polarity of bwrap's *deny-by-default then re-open with binds*.
43
+ * A `(deny file-write*)` plus re-allow is a blacklist shape, and a blacklist is
44
+ * what a determined command walks around: a path nobody thought of stays
45
+ * writable. So this profile does NOT claim bwrap's guarantee.
46
+ *
47
+ * What it does guarantee is narrower and still worth having: writes are refused
48
+ * to the workspace's parents' siblings, to `$HOME` outside the workspace, to
49
+ * `/System`, `/usr` (except the usual package caches), to `/Library`, and to
50
+ * `/private/etc`; network is refused outright when the policy says
51
+ * `restricted`. Both are enforced by the kernel and cannot be talked out of by
52
+ * a command line.
53
+ *
54
+ * The honest summary: on macOS the file bound is a strong blacklist, not a
55
+ * capability grant, and `describe()` says so rather than printing the same
56
+ * sentence it prints on Linux.
57
+ */
58
+
59
+ const fs = require('node:fs');
60
+ const path = require('node:path');
61
+
62
+ /** Candidate paths for the Seatbelt runner, best first. */
63
+ function candidates(env = process.env) {
64
+ const out = [];
65
+ if (env && env.AEGIS_SANDBOX_SEATBELT) out.push(String(env.AEGIS_SANDBOX_SEATBELT));
66
+ out.push('/usr/bin/sandbox-exec');
67
+ return out;
68
+ }
69
+
70
+ /** First existing executable candidate, or null. */
71
+ function findSeatbelt(env) {
72
+ for (const c of candidates(env)) {
73
+ try {
74
+ const st = fs.statSync(c);
75
+ if (st.isFile()) {
76
+ fs.accessSync(c, fs.constants.X_OK);
77
+ return c;
78
+ }
79
+ } catch {
80
+ /* try the next candidate */
81
+ }
82
+ }
83
+ return null;
84
+ }
85
+
86
+ /**
87
+ * Execute the probe for real. Never throws.
88
+ *
89
+ * `-p '(version 1)(allow default)'` is the cheapest profile that still proves
90
+ * the runner will compile a profile and exec a child: it exercises the parse
91
+ * and the spawn, not just "the binary exists". A binary present but unable to
92
+ * compile a profile (SIP disabled in a way that broke it, a replaced shim, a
93
+ * future removal) must be reported as unavailable rather than assumed working.
94
+ *
95
+ * @returns {{ available: boolean, path: string|null, reason: string|null, probed: boolean }}
96
+ */
97
+ function detect({ env = process.env, platform = process.platform, probe } = {}) {
98
+ if (platform !== 'darwin') {
99
+ return {
100
+ available: false,
101
+ path: null,
102
+ reason: `no darwin mechanism on ${platform}`,
103
+ probed: false,
104
+ };
105
+ }
106
+ const bin = findSeatbelt(env);
107
+ if (!bin) {
108
+ return { available: false, path: null, reason: 'sandbox-exec not found', probed: false };
109
+ }
110
+ const run = typeof probe === 'function' ? probe : defaultProbe;
111
+ const res = run(bin);
112
+ if (res && res.ok) {
113
+ return {
114
+ available: true,
115
+ path: bin,
116
+ reason: null,
117
+ probed: true,
118
+ // Recorded so `describe()` and the transcript can say what actually ran.
119
+ mechanism: 'seatbelt',
120
+ };
121
+ }
122
+ return {
123
+ available: false,
124
+ path: bin,
125
+ reason: (res && res.reason) || 'sandbox-exec probe failed',
126
+ probed: true,
127
+ };
128
+ }
129
+
130
+ function defaultProbe(bin) {
131
+ const { spawnSync } = require('node:child_process');
132
+ try {
133
+ const r = spawnSync(bin, ['-p', '(version 1)(allow default)', '/usr/bin/true'], {
134
+ timeout: 5000,
135
+ encoding: 'utf8',
136
+ stdio: ['ignore', 'pipe', 'pipe'],
137
+ });
138
+ if (r.error) return { ok: false, reason: `sandbox-exec probe error: ${r.error.message}` };
139
+ if (r.status !== 0) {
140
+ const why = String(r.stderr || '').trim().split('\n')[0];
141
+ return { ok: false, reason: why || `sandbox-exec probe exited ${r.status}` };
142
+ }
143
+ return { ok: true };
144
+ } catch (e) {
145
+ return { ok: false, reason: `sandbox-exec probe threw: ${e.message}` };
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Quote one path for a Seatbelt profile string.
151
+ *
152
+ * Profiles are S-expressions, so a path is a quoted string literal and the
153
+ * escape rules are its own: `\` and `"` must be escaped, and a raw newline
154
+ * would end the literal and let a path inject profile syntax. Paths containing
155
+ * either are REFUSED by the caller rather than escaped, because a path that
156
+ * needs escaping is a path this code never sees in practice and silencing the
157
+ * question is how injection bugs get shipped. This function exists so that the
158
+ * refusal has one place to happen and is not reinvented per call site.
159
+ */
160
+ function quotePath(p) {
161
+ const s = String(p);
162
+ if (/["\\\n\r]/.test(s)) return null;
163
+ return `(subpath "${s}")`;
164
+ }
165
+
166
+ /** Literal form — matches exactly one path, not its subtree. */
167
+ function quoteLiteral(p) {
168
+ const s = String(p);
169
+ if (/["\\\n\r]/.test(s)) return null;
170
+ return `(literal "${s}")`;
171
+ }
172
+
173
+ /**
174
+ * Read-only paths that a normal toolchain still needs to write nothing into:
175
+ * `/usr`, `/System`, `/Library`, `/private/etc`. Denying writes there is what
176
+ * stops a command from "fixing" a system binary inside an approved turn.
177
+ *
178
+ * Deliberately NOT denied: `/tmp`, `/private/tmp`, `/var/folders` (the real
179
+ * per-user temp root on macOS, which every build tool uses), and the
180
+ * package-manager caches — denying those breaks `npm install`, `pip`, `brew`
181
+ * and cargo, which is the common case rather than the attack.
182
+ */
183
+ const SYSTEM_READONLY = Object.freeze(['/System', '/usr', '/Library', '/private/etc', '/bin', '/sbin']);
184
+
185
+ /**
186
+ * Device nodes every process legitimately writes.
187
+ *
188
+ * A sandbox that denies `/dev/null` is a sandbox that breaks the shell it is
189
+ * meant to protect: `2>/dev/null` is in half of all one-liners, and a failed
190
+ * redirect kills the whole command rather than the command's error output.
191
+ */
192
+ const DEVICE_WRITES = Object.freeze(
193
+ '(allow file-write* (literal "/dev/null") (literal "/dev/stdout") (literal "/dev/stderr") (literal "/dev/zero") (literal "/dev/dtracehelper"))'
194
+ );
195
+
196
+ /** Is `child` inside `parent`? (`path.sep`-aware, so `/a/bc` is not in `/a/b`.) */
197
+ function ps(child, parent) {
198
+ return child === parent || child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep);
199
+ }
200
+
201
+ /**
202
+ * Build the `sandbox-exec` argv for one command.
203
+ *
204
+ * Takes the ALREADY-NORMALISED policy from `sandbox.js` (`normalize()`), so the
205
+ * mode bound (`read-only` cannot carry a write grant) is enforced in one place
206
+ * and this file cannot re-open it by accident.
207
+ *
208
+ * Returns `{ ok: true, argv, profile, guarantee }` or `{ ok: false, reason }`.
209
+ * `guarantee` is 'blacklist' — the caller must surface it, because claiming a
210
+ * capability grant here would be false.
211
+ */
212
+ function wrap(policyInput, command, opts = {}) {
213
+ const { seatbelt, workspace, argv = [] } = opts;
214
+ if (!seatbelt) return { ok: false, reason: 'no sandbox-exec binary' };
215
+ const policy = policyInput || {};
216
+ if (policy.mode === 'off') return { ok: false, reason: 'sandbox disabled by policy' };
217
+
218
+ const ws = workspace ? path.resolve(workspace) : null;
219
+ const lines = ['(version 1)', '(allow default)'];
220
+
221
+ // Network: denied outright. macOS has no per-interface unshare, so `open`
222
+ // means "this profile says nothing about network" — which is exactly right:
223
+ // an allow-by-default profile with no network rule is open.
224
+ if (policy.network === 'restricted') {
225
+ lines.push('(deny network*)');
226
+ }
227
+
228
+ // A write grant on the filesystem root is refused here for the same reason
229
+ // bwrap refuses it: honouring it would make the sandbox a no-op while the
230
+ // state still reports an active mode.
231
+ const entries = (policy.fileSystem && Array.isArray(policy.fileSystem.entries))
232
+ ? policy.fileSystem.entries
233
+ : [];
234
+ for (const e of entries) {
235
+ if (!e || e.access !== 'write') continue;
236
+ const p = e.path;
237
+ if (p && p.type === 'special' && p.value && p.value.kind === 'root') {
238
+ return {
239
+ ok: false,
240
+ policyFault: true,
241
+ reason: 'policy grants write to the filesystem root, which a sandbox cannot honour',
242
+ };
243
+ }
244
+ }
245
+
246
+ // In `read-only` there is no write to re-open at all — deny, and stop.
247
+ if (policy.mode === 'read-only') {
248
+ lines.push('(deny file-write*)');
249
+ // Device sinks must stay writable even in read-only: `2>/dev/null` and
250
+ // stdout/stderr redirection are not filesystem writes the policy is trying
251
+ // to prevent, and denying them makes almost every program fail obscurely.
252
+ // bwrap gets this for free by mounting `--dev /dev`; Seatbelt does not.
253
+ lines.push(DEVICE_WRITES);
254
+ // Mach IPC is how a process talks to the window server and to launchd;
255
+ // denying it wholesale breaks `fork` in ways that read as unrelated bugs.
256
+ lines.push('(allow mach-lookup)');
257
+ } else {
258
+ // workspace-write: deny writes everywhere, then re-allow the grants.
259
+ lines.push('(deny file-write*)');
260
+ lines.push(DEVICE_WRITES);
261
+ const specials = [];
262
+ for (const e of entries) {
263
+ if (!e || e.access !== 'write') continue;
264
+ const p = e.path;
265
+ if (!p) continue;
266
+ if (p.type === 'special') {
267
+ const kind = p.value && p.value.kind;
268
+ if (kind === 'slash_tmp') specials.push('/tmp', '/private/tmp');
269
+ continue;
270
+ }
271
+ if (p.type !== 'path' || typeof p.path !== 'string' || !p.path) continue;
272
+ const abs = path.resolve(p.path);
273
+ // `missingPathBehavior: 'skip'` means "grant it if it exists" — a grant to
274
+ // a nonexistent path is harmless to emit, but skipping keeps the profile
275
+ // readable and matches the bwrap branch's behaviour.
276
+ if (e.missingPathBehavior === 'skip') {
277
+ try {
278
+ fs.statSync(abs);
279
+ } catch {
280
+ continue;
281
+ }
282
+ }
283
+ const sub = quotePath(abs);
284
+ const lit = quoteLiteral(abs);
285
+ if (!sub || !lit) {
286
+ return { ok: false, policyFault: true, reason: `sandbox path cannot be expressed in a profile: ${abs}` };
287
+ }
288
+ // `subpath` covers the subtree; `literal` covers the directory inode
289
+ // itself (creating a file inside a dir needs write on both).
290
+ specials.push(sub, lit);
291
+ }
292
+ if (specials.length) lines.push(`(allow file-write* ${specials.join(' ')})`);
293
+
294
+ // The workspace, when the mode says so and the policy did not already name
295
+ // it — the belt to defaultPolicy's braces, same as bwrap's branch.
296
+ if (ws) {
297
+ let already = false;
298
+ for (const e of entries) {
299
+ if (e && e.access === 'write' && e.path && e.path.type === 'path' && path.resolve(e.path.path) === ws) {
300
+ already = true;
301
+ }
302
+ }
303
+ if (!already) {
304
+ const sub = quotePath(ws);
305
+ const lit = quoteLiteral(ws);
306
+ if (!sub || !lit) {
307
+ return { ok: false, policyFault: true, reason: `workspace path cannot be expressed in a profile: ${ws}` };
308
+ }
309
+ lines.push(`(allow file-write* ${sub} ${lit})`);
310
+ }
311
+ }
312
+
313
+ // `$HOME` is the one an injected turn actually wants, and it is NOT inside
314
+ // the workspace. Denying it explicitly after the allows means an allow that
315
+ // happened to name something under $HOME still cannot widen to the rest of
316
+ // it — Seatbelt's last matching rule wins for denies emitted after.
317
+ const home = process.env.HOME || '';
318
+ const homeAbs = home ? path.resolve(home) : '';
319
+ // Only deny $HOME when the workspace is NOT inside it — otherwise the deny
320
+ // would shadow the workspace allow and a repo under ~/ would be read-only.
321
+ const wsInsideHome = Boolean(ws && homeAbs && ps(ws, homeAbs));
322
+ if (homeAbs && homeAbs !== ws && !wsInsideHome) {
323
+ const sub = quotePath(path.resolve(home));
324
+ if (sub) lines.push(`(deny file-write* ${sub})`);
325
+ }
326
+
327
+ // System trees stay read-only even inside a broad grant.
328
+ for (const sys of SYSTEM_READONLY) {
329
+ const sub = quotePath(sys);
330
+ if (sub) lines.push(`(deny file-write* ${sub})`);
331
+ }
332
+ lines.push('(allow mach-lookup)');
333
+ }
334
+
335
+ const profile = lines.join('\n');
336
+ // The profile is passed with `-p` rather than `-f`: `-f` wants a file, and
337
+ // writing a temp profile per spawn would put the rules on disk for a
338
+ // concurrent reader. `-p` takes the text directly, as ONE argv element, so no
339
+ // shell ever parses it.
340
+ const out = [seatbelt, '-p', profile];
341
+ // `sandbox-exec` has no `--chdir` flag — the caller sets cwd on the spawn
342
+ // itself, which is why `cwd` is accepted but unused here.
343
+ for (const a of argv) out.push(String(a));
344
+ out.push(String(command));
345
+ return { ok: true, argv: out, profile, guarantee: 'blacklist' };
346
+ }
347
+
348
+ /**
349
+ * The sentence the UI prints for this platform.
350
+ *
351
+ * Says 'blacklist' out loud. `sandbox.js` prints bwrap's capability-grant line
352
+ * on Linux; printing the same words here would claim a guarantee this mechanism
353
+ * does not provide, which is the one failure the sandbox is not allowed to have.
354
+ */
355
+ function describe(state, policy) {
356
+ if (!state || !state.available) {
357
+ return `sandbox: OFF — ${(state && state.reason) || 'unavailable'} (commands run with full user access)`;
358
+ }
359
+ const mode = (policy && policy.mode) || 'workspace-write';
360
+ const net = (policy && policy.network) === 'open' ? 'network open' : 'network restricted';
361
+ return `sandbox: ${mode} via Seatbelt — ${net} (strong blacklist: system trees and $HOME outside the workspace are write-denied; not a capability grant)`;
362
+ }
363
+
364
+ module.exports = {
365
+ name: 'darwin',
366
+ mechanism: 'seatbelt',
367
+ guarantee: 'blacklist',
368
+ candidates,
369
+ findSeatbelt,
370
+ detect,
371
+ wrap,
372
+ describe,
373
+ // Exported for tests: the profile builder is pure, so both halves of the
374
+ // read-only/workspace-write split can be asserted on any host.
375
+ quotePath,
376
+ quoteLiteral,
377
+ SYSTEM_READONLY,
378
+ DEVICE_WRITES,
379
+ ps,
380
+ };