hazbox 0.0.0-stage → 0.1.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.

Potentially problematic release.


This version of hazbox might be problematic. Click here for more details.

package/src/run.mjs ADDED
@@ -0,0 +1,623 @@
1
+ // hazbox run: run a command where only the current project is visible.
2
+ // Linux, via bubblewrap.
3
+ //
4
+ // Hidden: the real home, all of /run (ssh-agent, D-Bus system and session
5
+ // buses, docker, snapd, CUPS and every other daemon socket), /tmp, /var/tmp,
6
+ // /dev/shm, other processes, and every env var not on a short allowlist.
7
+ // Mounted back: the project (read-write), its .git (read-only unless
8
+ // --git-write), toolchains (read-only), DNS config.
9
+ import fs from 'node:fs'
10
+ import os from 'node:os'
11
+ import path from 'node:path'
12
+ import crypto from 'node:crypto'
13
+ import { spawn, spawnSync } from 'node:child_process'
14
+ import { seccompFilter } from './seccomp.mjs'
15
+
16
+ // Agents' own instructions and skills, mounted read-only when the command
17
+ // is that agent, so it behaves as it does outside. Never their logins,
18
+ // settings (hooks) or MCP config.
19
+ const AGENT_FILES = {
20
+ claude: ['.claude/CLAUDE.md', '.claude/skills', '.claude/agents', '.claude/commands', '.codex/AGENTS.md'],
21
+ codex: ['.codex/AGENTS.md', '.codex/prompts', '.codex/skills'],
22
+ }
23
+ const ENV_ALLOW = ['USER', 'LOGNAME', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM', 'COLORTERM', 'NO_COLOR', 'FORCE_COLOR', 'TZ', 'NODE_ENV', 'CI', 'EDITOR']
24
+ // Toolchains that live in $HOME. Read-only, so code inside can't replace a
25
+ // CLI you later run outside. Only these dirs, never their parents
26
+ // (~/.cargo also holds credentials.toml).
27
+ const TOOL_DIRS = ['.local/bin', '.local/share/fnm', '.nvm/versions', '.volta', '.local/share/pnpm', '.bun/bin', '.deno/bin',
28
+ '.pyenv', '.local/share/uv/python', '.local/share/uv/tools', '.local/share/claude/versions', '.local/share/fastshim', '.cargo/bin', '.rustup', 'go/bin', '.local/go', '.sdkman/candidates']
29
+ // Never treat these as a project: mounting them read-write would hand the
30
+ // box the secrets they hold.
31
+ const HOME_DENY = ['.ssh', '.gnupg', '.aws', '.azure', '.config', '.kube', '.docker', '.npm', '.cargo', '.codex', '.claude',
32
+ '.local', '.password-store', '.mozilla', '.pki', '.var', '.cache']
33
+ const SYSTEM_DENY = ['/etc', '/usr', '/bin', '/sbin', '/lib', '/lib32', '/lib64', '/boot', '/proc', '/sys', '/dev', '/run', '/var', '/root', '/snap']
34
+ const MARKERS = ['package.json', 'Cargo.toml', 'pyproject.toml', 'go.mod', 'deno.json', 'deno.jsonc', 'requirements.txt',
35
+ 'Gemfile', 'composer.json', 'pom.xml', 'build.gradle', 'build.gradle.kts', 'CMakeLists.txt', 'Makefile', 'flake.nix']
36
+
37
+ export class HazboxError extends Error {}
38
+
39
+ function git(args, cwd) {
40
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8' })
41
+ return r.status === 0 ? r.stdout.trim() : ''
42
+ }
43
+
44
+ function within(p, dir) { return p === dir || p.startsWith(dir + path.sep) }
45
+ function exists(p) { try { fs.lstatSync(p); return true } catch { return false } }
46
+ function readTrim(p) { try { return fs.readFileSync(p, 'utf8').trim() } catch { return '' } }
47
+ function real(p) { try { return fs.realpathSync(p) } catch { return '' } }
48
+ function isEmptyDir(p) { try { return fs.readdirSync(p).length === 0 } catch { return false } }
49
+
50
+ // hazbox's own state, outside anything the box can write. Not
51
+ // XDG_DATA_HOME: an env var could put it inside a project, where code in
52
+ // the box could swap the box home for a link to the real one.
53
+ export function dataDir() { return path.join(os.homedir(), '.local/share/hazbox') }
54
+ export function stateDir(project) {
55
+ return path.join(dataDir(), 'projects', crypto.createHash('sha256').update(project).digest('hex').slice(0, 16))
56
+ }
57
+ // mkdir -p, then refuse anything that isn't a plain directory: hazbox
58
+ // mounts these, so a symlink would mount wherever it points.
59
+ function ownDir(p) {
60
+ fs.mkdirSync(p, { recursive: true })
61
+ if (!fs.lstatSync(p).isDirectory()) throw new HazboxError(`${p} is not a plain directory. Refusing to mount it.`)
62
+ return p
63
+ }
64
+
65
+ // The project is the nearest folder above cwd (below home) that holds a .git,
66
+ // else the nearest one with a project file. Without either, the caller must
67
+ // say --here. This deliberately doesn't ask git: its answer follows
68
+ // core.worktree, which code in an earlier run could have written.
69
+ export function findProject(cwd, HOME, here = false) {
70
+ cwd = fs.realpathSync(cwd)
71
+ const home = fs.realpathSync(HOME)
72
+ let project = '', marker = ''
73
+ for (let d = cwd; d !== home && d !== '/'; d = path.dirname(d)) {
74
+ if (exists(path.join(d, '.git'))) { project = d; break }
75
+ if (!marker && MARKERS.some(m => exists(path.join(d, m)))) marker = d
76
+ }
77
+ project ||= marker
78
+ // An empty folder has nothing to expose, so it can be the project as is
79
+ // (scaffolders like create-vite start in one).
80
+ if (!project && (here || isEmptyDir(cwd))) project = cwd
81
+ if (!project) {
82
+ throw new HazboxError(`${cwd} doesn't look like a project (no git repo or project file such as package.json). Run from a project, or pass --here to use this folder.`)
83
+ }
84
+ if (['/tmp', '/var/tmp', '/dev/shm'].includes(project)) throw new HazboxError(`refusing to expose ${project}: it's shared by every program on this machine. Make a folder inside it.`)
85
+ // Where drives get mounted: a drive plugged in later would land inside.
86
+ if (['/mnt', '/media', path.join('/media', os.userInfo().username)].includes(project)) throw new HazboxError(`refusing to expose ${project}: drives get mounted there. Use a folder on the drive instead.`)
87
+ if (project === '/' || within(home, project)) throw new HazboxError(`refusing to expose ${project}: it contains your home directory`)
88
+ for (const d of HOME_DENY) {
89
+ const p = path.join(home, d)
90
+ if (within(project, p) || within(p, project)) throw new HazboxError(`refusing to expose ${project}: ~/${d} holds credentials or app data`)
91
+ }
92
+ for (const d of SYSTEM_DENY) if (within(project, d) && !within(project, '/var/tmp')) throw new HazboxError(`refusing to expose system directory ${project}`)
93
+ return project
94
+ }
95
+
96
+ // layers: where this run's cache overlay layers go. Normally the project's
97
+ // own, kept between runs; a throwaway dir while another run of the same
98
+ // project holds them (overlayfs doesn't allow two mounts on one upper).
99
+ export function buildArgs({ cwd = process.cwd(), offline = false, extraEnv = [], env = process.env, here = false, gitWrite = false, overlay = false, layers, pasta = false, agent = '' } = {}) {
100
+ if (process.platform !== 'linux') throw new HazboxError('hazbox run supports Linux today; macOS support is in progress. Nothing was run.')
101
+ const HOME = os.homedir()
102
+ const project = findProject(cwd, HOME, here)
103
+
104
+ // Per-project home and /tmp, kept between runs so caches stay warm (Node's
105
+ // compile cache lives in /tmp). Per project, so one project can't plant
106
+ // files another project's runs will load.
107
+ const data = real(ownDir(dataDir()))
108
+ if (within(data, project) || within(project, data)) throw new HazboxError(`refusing to run: hazbox keeps its state in ${data}, which overlaps the project ${project}`)
109
+ const state = ownDir(stateDir(project))
110
+ const fakeHome = ownDir(path.join(state, 'home'))
111
+ const fakeTmp = ownDir(path.join(state, 'tmp'))
112
+ // So `hazbox prune` knows which project this state belongs to.
113
+ if (readTrim(path.join(state, 'project')) !== project) fs.writeFileSync(path.join(state, 'project'), project)
114
+ layers ??= state
115
+
116
+ const a = [
117
+ '--ro-bind', '/', '/',
118
+ '--dev', '/dev',
119
+ '--proc', '/proc',
120
+ // Every daemon socket on the machine lives under /run (or /var/run,
121
+ // which points there). A read-only mount doesn't stop connect(), so
122
+ // replace the whole tree and put back only what name lookups need.
123
+ '--tmpfs', '/run',
124
+ '--bind', fakeTmp, '/tmp',
125
+ '--tmpfs', '/var/tmp',
126
+ '--tmpfs', '/home',
127
+ // Mounted drives (USB sticks, other disks).
128
+ ...['/media', '/mnt'].filter(d => fs.existsSync(d)).flatMap(d => ['--tmpfs', d]),
129
+ '--bind', fakeHome, HOME,
130
+ ]
131
+ for (const f of ['/etc/resolv.conf', '/etc/hosts', '/etc/nsswitch.conf']) {
132
+ try {
133
+ const real = fs.realpathSync(f)
134
+ // In pasta's network, your loopback resolver (often 127.0.0.53) isn't
135
+ // reachable; `pasta` is the list of nameservers to use instead.
136
+ if (pasta && f === '/etc/resolv.conf') {
137
+ const own = path.join(state, 'resolv.conf')
138
+ const keep = readTrim(real).split('\n').filter(l => /^\s*(search|domain|options)\b/.test(l))
139
+ fs.writeFileSync(own, [...pasta.map(a => `nameserver ${a}`), ...keep, ''].join('\n'))
140
+ a.push('--ro-bind', own, real)
141
+ } else if (within(real, '/run')) a.push('--ro-bind', real, real)
142
+ } catch {}
143
+ }
144
+ // Normally root-only; hide them in case the host's permissions are wrong.
145
+ for (const f of ['/etc/shadow', '/etc/gshadow', '/etc/shadow-', '/etc/gshadow-']) if (fs.existsSync(f)) a.push('--ro-bind', '/dev/null', f)
146
+
147
+ const nodeRoot = path.dirname(path.dirname(process.execPath))
148
+ if (within(nodeRoot, '/home') || within(nodeRoot, '/tmp') || within(nodeRoot, '/run') || within(nodeRoot, '/var/tmp')) a.push('--ro-bind', nodeRoot, nodeRoot)
149
+ const bins = [path.dirname(process.execPath)]
150
+ for (const d of TOOL_DIRS) {
151
+ const p = path.join(HOME, d)
152
+ if (fs.existsSync(p)) a.push('--ro-bind', p, p)
153
+ }
154
+ // Package caches: the box reads your warm cache through an overlay, and
155
+ // its writes go to a per-project layer, so nothing it writes reaches your
156
+ // cache or another project. Needs bwrap 0.10+.
157
+ const cache = (dir, name) => {
158
+ ownDir(layers)
159
+ const upper = ownDir(path.join(ownDir(path.join(layers, name)), 'upper'))
160
+ const work = ownDir(path.join(layers, name, 'work'))
161
+ a.push('--overlay-src', dir, '--overlay', upper, work, dir)
162
+ }
163
+ const npmCache = path.join(HOME, '.npm/_cacache')
164
+ if (overlay && fs.existsSync(npmCache)) cache(npmCache, 'npm-cache')
165
+ // pnpm keeps its store inside its (read-only) home, so it always needs a
166
+ // writable store there: an overlay on yours, else an empty one per project.
167
+ const pnpmStore = path.join(HOME, '.local/share/pnpm/store')
168
+ if (fs.existsSync(path.dirname(pnpmStore))) {
169
+ fs.mkdirSync(pnpmStore, { recursive: true })
170
+ if (overlay) cache(pnpmStore, 'pnpm-cache')
171
+ else {
172
+ const own = ownDir(path.join(state, 'pnpm-store'))
173
+ a.push('--bind', own, pnpmStore)
174
+ }
175
+ }
176
+ // Keep PATH entries that are visible inside: system dirs and the toolchain
177
+ // dirs above. Drop per-shell dirs under /run and anything else in $HOME.
178
+ for (const p of (env.PATH || '').split(':')) {
179
+ if (!p || bins.includes(p)) continue
180
+ const tool = TOOL_DIRS.some(d => within(p, path.join(HOME, d)))
181
+ if (!tool && (within(p, HOME) || within(p, '/run') || within(p, '/tmp') || within(p, '/var/tmp'))) continue
182
+ bins.push(p)
183
+ }
184
+ for (const p of ['/usr/local/bin', '/usr/bin', '/bin']) if (!bins.includes(p)) bins.push(p)
185
+
186
+ for (const f of AGENT_FILES[agent] ?? []) {
187
+ const p = path.join(HOME, f)
188
+ if (fs.existsSync(p)) a.push('--ro-bind', p, p)
189
+ }
190
+
191
+ a.push('--bind', project, project)
192
+ const gm = gitMounts(project, gitWrite)
193
+ a.push(...gm)
194
+ // git refuses to write a read-only .git with a bare "Read-only file
195
+ // system". A wrapper says why and what to do, which agents need most.
196
+ const realGit = !gitWrite && gm.length && findGit(bins, project)
197
+ if (realGit) {
198
+ const dir = ownDir(path.join(state, 'bin'))
199
+ fs.writeFileSync(path.join(dir, 'git'), `#!/bin/sh
200
+ ${JSON.stringify(realGit)} "$@"; s=$?
201
+ if [ $s -ne 0 ]; then for a in "$@"; do case "$a" in
202
+ add|commit|checkout|switch|restore|stash|merge|rebase|reset|pull|fetch|cherry-pick|revert|tag|branch|am|apply|rm|mv|clean|gc|prune|worktree|submodule)
203
+ echo "hazbox: .git is read-only in the box, so git can't change it. To let commands inside commit, run: hazbox --git-write <command>" >&2; break;;
204
+ esac; done; fi
205
+ exit $s
206
+ `, { mode: 0o755 })
207
+ a.push('--ro-bind', dir, '/run/hazbox/bin')
208
+ bins.unshift('/run/hazbox/bin')
209
+ }
210
+
211
+ a.push('--chdir', fs.realpathSync(cwd), '--unshare-pid', '--unshare-ipc', '--unshare-uts', '--die-with-parent')
212
+ // The box's environment goes to bwrap as its environment, not as
213
+ // --setenv arguments: a process's arguments are readable by every user
214
+ // on the machine, its environment only by you.
215
+ const boxEnv = { HOME, PATH: bins.join(':'), HAZBOX: '1' }
216
+ for (const k of [...ENV_ALLOW, ...extraEnv]) if (env[k] != null) boxEnv[k] = env[k]
217
+ // A fresh box home has no npm state, so npm would announce updates on
218
+ // every first run.
219
+ if (!extraEnv.includes('NPM_CONFIG_UPDATE_NOTIFIER')) boxEnv.NPM_CONFIG_UPDATE_NOTIFIER = 'false'
220
+ // Commits made inside keep your identity without exposing ~/.gitconfig
221
+ // (which can hold credential helpers and include other files).
222
+ const name = git(['config', 'user.name'], project)
223
+ const email = git(['config', 'user.email'], project)
224
+ if (name) Object.assign(boxEnv, { GIT_AUTHOR_NAME: name, GIT_COMMITTER_NAME: name })
225
+ if (email) Object.assign(boxEnv, { GIT_AUTHOR_EMAIL: email, GIT_COMMITTER_EMAIL: email })
226
+ if (offline) a.push('--unshare-net')
227
+ // Inside pasta's namespace we're root; map back to your own uid and gid.
228
+ else if (pasta) a.push('--unshare-user', '--uid', String(process.getuid()), '--gid', String(process.getgid()))
229
+ return { args: a, project, state, env: boxEnv }
230
+ }
231
+
232
+ // Host git later runs whatever .git tells it to: hooks, core.fsmonitor and
233
+ // other config commands, or a whole other git dir through `commondir`. So by
234
+ // default every git dir the project uses is read-only inside the box, and
235
+ // `.git` is a mount point, which also stops it being renamed and replaced.
236
+ // git status, diff and log still work; commits need --git-write.
237
+ function gitMounts(project, gitWrite) {
238
+ const m = []
239
+ const found = gitDirs(project)
240
+ if (!found) return m
241
+ const { dotgit, dirs } = found
242
+ if (!gitWrite) {
243
+ m.push('--ro-bind', dotgit, dotgit)
244
+ for (const g of dirs) if (!within(g, project)) m.push('--ro-bind', g, g)
245
+ return m
246
+ }
247
+ // --git-write: git dirs are writable, but stay mount points (no rename),
248
+ // and hooks and config stay read-only.
249
+ if (fs.statSync(dotgit).isDirectory()) m.push('--bind', dotgit, dotgit)
250
+ else m.push('--ro-bind', dotgit, dotgit)
251
+ for (const g of dirs) {
252
+ if (!within(g, project)) m.push('--bind', g, g)
253
+ const hooks = path.join(g, 'hooks')
254
+ fs.mkdirSync(hooks, { recursive: true })
255
+ m.push('--ro-bind', hooks, hooks)
256
+ const config = path.join(g, 'config')
257
+ if (fs.existsSync(config)) m.push('--ro-bind', config, config)
258
+ }
259
+ return m
260
+ }
261
+
262
+ // The git dirs the project uses, read from the files rather than from git,
263
+ // and checked: a `.git` file written by an earlier run could point at any
264
+ // other repo on the machine.
265
+ function gitDirs(project) {
266
+ const dotgit = path.join(project, '.git')
267
+ let st
268
+ try { st = fs.lstatSync(dotgit) } catch { return null }
269
+ if (st.isDirectory()) {
270
+ if (exists(path.join(dotgit, 'commondir'))) throw new HazboxError(`${dotgit}/commondir exists. git only puts that file in worktree dirs, and it can send git to another repo's config. Check it and remove it, then rerun.`)
271
+ return { dotgit, dirs: [dotgit] }
272
+ }
273
+ if (!st.isFile()) throw new HazboxError(`${dotgit} is a symlink; refusing to guess where it leads.`)
274
+ const ptr = readTrim(dotgit).match(/^gitdir: (.+)$/)?.[1]
275
+ const gd = ptr && real(path.resolve(project, ptr))
276
+ if (!gd) throw new HazboxError(`${dotgit} doesn't point at a git dir.`)
277
+ // A worktree: its git dir names this .git file as its own, and sits in the
278
+ // worktrees/ folder of the repo it names as common.
279
+ const back = readTrim(path.join(gd, 'gitdir'))
280
+ if (back && real(path.resolve(gd, back)) === real(dotgit)) {
281
+ const common = real(path.resolve(gd, readTrim(path.join(gd, 'commondir')) || '..'))
282
+ if (common && within(gd, path.join(common, 'worktrees'))) return { dotgit, dirs: [gd, common] }
283
+ }
284
+ // A submodule: its git dir sits inside the .git/modules of a folder
285
+ // above, and its own config (which git writes when it adds the
286
+ // submodule) names this project as its worktree. A .git file planted by
287
+ // an earlier run can point anywhere, but can't change that config.
288
+ const wt = spawnSync('git', ['config', '--file', path.join(gd, 'config'), 'core.worktree'], { encoding: 'utf8' }).stdout.trim()
289
+ const ownsProject = wt && real(path.resolve(gd, wt)) === real(project)
290
+ for (let d = path.dirname(project); d !== '/'; d = path.dirname(d)) {
291
+ const modules = path.join(real(d), '.git', 'modules')
292
+ if (gd !== modules && within(gd, modules) && ownsProject) return { dotgit, dirs: [gd] }
293
+ }
294
+ throw new HazboxError(`${dotgit} points at ${gd}, which isn't a worktree or submodule of this project. Refusing.`)
295
+ }
296
+
297
+ // The git the box would run anyway, from the PATH entries the box keeps
298
+ // (system dirs and read-only toolchains), never one the box can replace.
299
+ function findGit(bins, project) {
300
+ for (const d of bins) {
301
+ const g = path.join(d, 'git')
302
+ if (path.isAbsolute(d) && !within(d, project) && !d.startsWith('/run/') && /^[\w/.+-]+$/.test(g) && fs.existsSync(g)) return g
303
+ }
304
+ return null
305
+ }
306
+ function findBin(name, dirs = ['/usr/bin', '/usr/local/bin', '/bin']) {
307
+ for (const d of dirs) if (fs.existsSync(`${d}/${name}`)) return `${d}/${name}`
308
+ return null
309
+ }
310
+ const findBwrap = () => findBin('bwrap')
311
+
312
+ // The box's own network, from pasta (the passt package): the internet works,
313
+ // but nothing listening on your localhost is reachable, abstract unix
314
+ // sockets are separate, and ports the box listens on (dev servers) are
315
+ // forwarded to your localhost. IPv4 only: with IPv6 too, a browser's try on
316
+ // ::1 reaches pasta and gets dropped instead of falling back to 127.0.0.1.
317
+ const PASTA_DNS = '169.254.1.1'
318
+ // Older pasta (Ubuntu 24.04 ships one from 2024-02) lacks --dns-host and
319
+ // --host-lo-to-ns-lo; use them only where they exist.
320
+ function pastaFeatures(bin) {
321
+ const h = spawnSync(bin, ['--help'], { encoding: 'utf8', env: { PATH: '/usr/bin:/bin' } })
322
+ const text = `${h.stdout}${h.stderr}`
323
+ return { dnsHost: text.includes('--dns-host'), hostLo: text.includes('--host-lo-to-ns-lo') }
324
+ }
325
+ const nameservers = file => [...readTrim(file).matchAll(/^\s*nameserver\s+(\d+\.\d+\.\d+\.\d+)\s*$/gm)].map(m => m[1])
326
+ // DNS inside pasta's network. With --dns-host, queries to PASTA_DNS go to
327
+ // your own resolver (often systemd-resolved on 127.0.0.53), which keeps
328
+ // per-network DNS working. Without it, the box asks your upstream servers
329
+ // directly, since nothing on your loopback is reachable from the box.
330
+ function boxNameservers(feat) {
331
+ if (feat.dnsHost) return [PASTA_DNS]
332
+ const direct = nameservers('/etc/resolv.conf').filter(a => !a.startsWith('127.'))
333
+ return direct.length ? direct : nameservers('/run/systemd/resolve/resolv.conf').filter(a => !a.startsWith('127.'))
334
+ }
335
+ function pastaArgs(feat, localPorts = [], forward = 'auto') {
336
+ const dns = nameservers('/etc/resolv.conf')[0]
337
+ return ['-4', '--config-net', '--quiet', '-t', forward, '-u', 'none', '-T', localPorts.length ? localPorts.join(',') : 'none', '-U', 'none',
338
+ '--no-map-gw', ...(feat.hostLo ? ['--host-lo-to-ns-lo'] : []),
339
+ // Without --dns-host, naming the upstream server also stops pasta
340
+ // printing "Couldn't get any nameserver address" on every run.
341
+ ...(feat.dnsHost ? ['--dns-forward', PASTA_DNS, ...(dns ? ['--dns-host', dns] : [])] : boxNameservers(feat).slice(0, 1).flatMap(a => ['-D', a]))]
342
+ }
343
+ // Services bound to all interfaces would still answer on this machine's
344
+ // other addresses, and containers on its bridges at theirs. Inside pasta's
345
+ // namespace, before the box starts, those get routed nowhere: every local
346
+ // address, including interfaces that are down, and the whole subnet of
347
+ // every interface except the one with the default route (your LAN, which
348
+ // stays reachable like the internet). Code in the box can't change routes:
349
+ // it has no capabilities in that namespace. Addresses that appear after
350
+ // the box starts (a VPN connecting) aren't covered.
351
+ function hostBlocks(ip) {
352
+ if (!ip) return []
353
+ const out = spawnSync(ip, ['-4', '-o', 'addr', 'show'], { encoding: 'utf8' }).stdout || ''
354
+ const def = readTrim('/proc/net/route').split('\n').slice(1).map(l => l.trim().split(/\s+/)).find(f => f[1] === '00000000')?.[0]
355
+ const blocks = new Set()
356
+ for (const line of out.split('\n')) {
357
+ const m = line.match(/^\d+:\s+(\S+)\s+inet\s+(\d+\.\d+\.\d+\.\d+)\/(\d+)/)
358
+ if (!m || m[2].startsWith('127.')) continue
359
+ const [, dev, addr, len] = m
360
+ blocks.add(`${addr}/32`)
361
+ if (dev !== def && +len > 0) {
362
+ const n = addr.split('.').reduce((v, o) => v * 256 + +o, 0)
363
+ const net = n - (n % 2 ** (32 - len))
364
+ blocks.add(`${[24, 16, 8, 0].map(sh => Math.floor(net / 2 ** sh) % 256).join('.')}/${len}`)
365
+ }
366
+ }
367
+ return [...blocks]
368
+ }
369
+
370
+ export function run(cmd, opts = {}) {
371
+ if (process.platform !== 'linux') throw new HazboxError('hazbox run supports Linux today; macOS support is in progress. Nothing was run.')
372
+ const bwrap = findBwrap()
373
+ if (!bwrap) throw new HazboxError('bubblewrap is not installed. Install it with your package manager, e.g.\n sudo apt install bubblewrap # Debian/Ubuntu\n sudo dnf install bubblewrap # Fedora\n sudo pacman -S bubblewrap # Arch\nNothing was run.')
374
+ const info = bwrapInfo(bwrap)
375
+ const { overlay } = info
376
+ const pasta = !opts.offline && info.pasta ? findBin('pasta') : null
377
+ // No passt: say so once. passt installed but failing: say so every run
378
+ // (the full fix the first time, and always in `hazbox check`).
379
+ if (!opts.offline && !pasta && !info.pastaError) noticeOnce('no-passt', `hazbox: ${NO_PASST}. This note shows once.`)
380
+ if (!opts.offline && !pasta && info.pastaError) {
381
+ if (!noticeOnce('pasta-failed', `hazbox: pasta is installed but can't start here (${info.pastaError}), so code in the box can reach services on your localhost.${/uid_map|namespace/i.test(info.pastaError) ? userNsHint('pasta', `${findBin('pasta')}{,.avx2}`) : ''}`))
382
+ console.error(`hazbox: pasta can't start here (${info.pastaError}), so the box can reach your localhost. \`hazbox check\` shows the fix.`)
383
+ }
384
+ const claim = overlay ? claimLayers(stateDir(findProject(opts.cwd ?? process.cwd(), os.homedir(), opts.here))) : null
385
+ let built
386
+ try { built = buildArgs({ ...opts, overlay, layers: claim?.layers, pasta: pasta ? boxNameservers(info.pastaFeat) : false, agent: path.basename(cmd[0]) }) } catch (e) { claim?.release(); throw e }
387
+ const { args, state, env: boxEnv } = built
388
+
389
+ // fd 3: the seccomp filter, which bwrap reads before running cmd.
390
+ // Every other fd this process inherited (from a terminal multiplexer, an
391
+ // editor, an agent or CI) is pointed at /dev/null, so none reach the box.
392
+ const devnull = fs.openSync('/dev/null', 'r')
393
+ const stdio = ['inherit', 'inherit', 'inherit', devnull]
394
+ const filter = seccompFilter()
395
+ // A file per run, so parallel runs can't truncate it under each other.
396
+ const seccompFile = path.join(state, `seccomp.${process.pid}.bpf`)
397
+ if (filter) {
398
+ fs.writeFileSync(seccompFile, filter)
399
+ stdio[3] = fs.openSync(seccompFile, 'r')
400
+ args.push('--seccomp', '3')
401
+ }
402
+ // Only fds without close-on-exec would cross into bwrap; Node's own have it.
403
+ const O_CLOEXEC = 0o2000000
404
+ const inherited = fs.readdirSync('/proc/self/fd').map(Number).filter(n => n > 3 && n !== devnull && n !== stdio[3]).filter(n => {
405
+ const flags = readTrim(`/proc/self/fdinfo/${n}`).match(/^flags:\s+([0-7]+)/m)?.[1]
406
+ return flags !== undefined && !(parseInt(flags, 8) & O_CLOEXEC)
407
+ })
408
+ for (let n = stdio.length; n <= Math.max(0, ...inherited); n++) stdio.push(inherited.includes(n) ? devnull : 'ignore')
409
+
410
+ return new Promise(resolve => {
411
+ // bwrap starts with an empty environment: its helper process stays as
412
+ // pid 1 inside the sandbox, and /proc/1/environ would expose every token.
413
+ let file = bwrap, argv = [...args, '--', ...cmd], watch = null, watchFd = null
414
+ if (pasta) {
415
+ // A shell in pasta's namespace (its pid 1) routes this machine's
416
+ // other addresses nowhere, refusing to run if that fails; reopens the
417
+ // seccomp filter as fd 3 (pasta closes inherited fds); runs bwrap;
418
+ // and kills it if hazbox goes away for any reason, which it notices
419
+ // as end-of-file on a FIFO only hazbox holds open. Nothing else ties
420
+ // the box to hazbox: pasta outlives its parent, and bwrap's
421
+ // parent-death hook doesn't survive its switch into pasta's user
422
+ // namespace. When pid 1 exits, the kernel kills the rest.
423
+ const ip = findBin('ip', ['/usr/sbin', '/sbin', '/usr/bin', '/bin'])
424
+ const blocks = hostBlocks(ip)
425
+ watch = path.join(state, `watch.${process.pid}`)
426
+ fs.rmSync(watch, { force: true })
427
+ if (spawnSync('mkfifo', ['-m', '600', watch]).status !== 0) throw new HazboxError(`couldn't create ${watch}. Nothing was run.`)
428
+ watchFd = fs.openSync(watch, 'r+')
429
+ file = pasta
430
+ argv = [...pastaArgs(info.pastaFeat, opts.localhost), '--', '/bin/sh', '-c', `f=$1; w=$2; shift 2
431
+ ${blocks.length ? `printf 'route add unreachable %s\\n' ${blocks.join(' ')} | ${ip} -batch - || { echo "hazbox: couldn't make this machine's other addresses unreachable, so nothing was run." >&2; exit 125; }` : ''}
432
+ "$@" 3<"$f" &
433
+ b=$!
434
+ (cat "$w" >/dev/null; kill -KILL $b) 2>/dev/null &
435
+ wait $b`, 'sh', filter ? seccompFile : '/dev/null', watch, bwrap, ...args, '--', ...cmd]
436
+ }
437
+ // The same fd map for pasta: newer pasta closes inherited fds itself,
438
+ // but older ones (Ubuntu 24.04's) pass them on.
439
+ const child = spawn(file, argv, { stdio, env: boxEnv })
440
+ const done = code => {
441
+ claim?.release()
442
+ fs.rmSync(seccompFile, { force: true })
443
+ if (watch) { try { fs.closeSync(watchFd) } catch {} fs.rmSync(watch, { force: true }) }
444
+ resolve(code)
445
+ }
446
+ // Ctrl-C reaches the child through the terminal; don't die before it does.
447
+ const ignore = () => {}
448
+ process.on('SIGINT', ignore)
449
+ process.on('SIGQUIT', ignore)
450
+ // Under pasta, pasta exits without passing signals on, and pid 1 of its
451
+ // namespace (the shell above) only takes SIGKILL from out here. So
452
+ // signal the command itself, below the bwrap processes. If the box is
453
+ // still there 5 s later (the command ignored it), kill pid 1, which
454
+ // takes the whole box down. pasta reports a killed child as exit 0,
455
+ // so remember the signal.
456
+ let forwarded = null, exited = false
457
+ const fwd = sig => {
458
+ forwarded = sig
459
+ if (!pasta) return child.kill(sig)
460
+ const pid1 = childrenOf(child.pid)
461
+ let level = pid1.flatMap(childrenOf).filter(p => readTrim(`/proc/${p}/comm`) === 'bwrap')
462
+ while (level.length && level.every(p => readTrim(`/proc/${p}/comm`) === 'bwrap')) level = level.flatMap(childrenOf)
463
+ for (const p of level) try { process.kill(p, sig) } catch {}
464
+ setTimeout(() => { if (!exited) for (const p of pid1) try { process.kill(p, 'SIGKILL') } catch {} }, level.length ? 5000 : 0).unref()
465
+ }
466
+ process.on('SIGTERM', fwd)
467
+ process.on('SIGHUP', fwd)
468
+ child.on('error', e => { console.error(`hazbox: ${e.message}`); done(127) })
469
+ child.on('exit', (code, sig) => {
470
+ exited = true
471
+ sig ??= code === 0 ? forwarded : null
472
+ done(sig ? 128 + (os.constants.signals[sig] ?? 1) : code)
473
+ })
474
+ })
475
+ }
476
+
477
+ function childrenOf(pid) {
478
+ try { return fs.readdirSync(`/proc/${pid}/task`).flatMap(t => readTrim(`/proc/${pid}/task/${t}/children`).split(/\s+/).filter(Boolean).map(Number)) } catch { return [] }
479
+ }
480
+
481
+ // Prints text the first time only; returns whether it printed.
482
+ function noticeOnce(name, text) {
483
+ const flag = path.join(ownDir(dataDir()), `noticed-${name}`)
484
+ if (fs.existsSync(flag)) return false
485
+ console.error(text)
486
+ try { fs.writeFileSync(flag, '') } catch {}
487
+ return true
488
+ }
489
+
490
+ // The project's cache layers, unless another live run of it holds them; then
491
+ // a throwaway set for this run. Two runs that both find a stale lock at the
492
+ // same instant can still end up sharing; that only risks this project's own
493
+ // cache layer.
494
+ function claimLayers(state) {
495
+ ownDir(state)
496
+ const lock = path.join(state, 'layers.lock')
497
+ const runs = path.join(state, 'runs')
498
+ const alive = pid => { try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } }
499
+ for (let i = 0; i < 2; i++) {
500
+ try {
501
+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx' })
502
+ for (const d of fs.existsSync(runs) ? fs.readdirSync(runs) : []) if (!alive(+d)) fs.rmSync(path.join(runs, d), { recursive: true, force: true })
503
+ return { layers: state, release: () => { if (readTrim(lock) === String(process.pid)) fs.rmSync(lock, { force: true }) } }
504
+ } catch (e) {
505
+ if (e.code !== 'EEXIST') throw e
506
+ const pid = +readTrim(lock)
507
+ if (pid && alive(pid)) break
508
+ fs.rmSync(lock, { force: true })
509
+ }
510
+ }
511
+ const layers = path.join(runs, String(process.pid))
512
+ fs.rmSync(layers, { recursive: true, force: true })
513
+ return { layers, release: () => fs.rmSync(layers, { recursive: true, force: true }) }
514
+ }
515
+
516
+ // What this bwrap can do here, checked once and cached by the binary's size
517
+ // and mtime (checking costs ~10 ms). A failed check isn't cached, so fixing
518
+ // the system and rerunning works.
519
+ function bwrapInfo(bwrap) {
520
+ const data = ownDir(dataDir())
521
+ const file = path.join(data, 'bwrap.json')
522
+ const st = fs.statSync(bwrap)
523
+ // The caches hazbox would overlay; a new one means checking again.
524
+ const lowers = [path.join(os.homedir(), '.npm/_cacache'), path.join(os.homedir(), '.local/share/pnpm/store')].filter(p => fs.existsSync(p))
525
+ const pastaBin = findBin('pasta')
526
+ const pst = pastaBin && fs.statSync(pastaBin)
527
+ // v2: records pasta's features. A new AppArmor profile means checking
528
+ // again, so the printed fix takes effect on the next run.
529
+ let aa = ''
530
+ try { aa = String(fs.statSync('/etc/apparmor.d').mtimeMs) } catch {}
531
+ const key = `v2:${aa}:${bwrap}:${st.size}:${st.mtimeMs}:${lowers.join(':')}:${pst ? `${pst.size}:${pst.mtimeMs}` : 'no-pasta'}`
532
+ try {
533
+ const c = JSON.parse(fs.readFileSync(file, 'utf8'))
534
+ // A pasta failure is checked again on every run until it works, so
535
+ // one bad moment can't switch the network isolation off for good.
536
+ if (c.key === key && c.pastaError) {
537
+ Object.assign(c, probePasta(pastaBin, bwrap))
538
+ if (c.pasta) writeAtomic(file, c)
539
+ }
540
+ if (c.key === key) return c
541
+ } catch {}
542
+
543
+ const env = { PATH: '/usr/bin:/bin' }
544
+ const base = ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--unshare-pid']
545
+ const ok = spawnSync(bwrap, [...base, 'true'], { env, encoding: 'utf8' })
546
+ if (ok.status !== 0) throw new HazboxError(`bubblewrap can't create a sandbox on this system: ${ok.stderr.trim() || `exit ${ok.status}`}. Nothing was run.${userNsHint('bwrap', bwrap)}`)
547
+
548
+ // Cache overlays need bwrap 0.10+ and overlayfs in a user namespace over
549
+ // each cache, with the upper layer on the filesystem hazbox keeps state on.
550
+ // If the check itself breaks (rather than bwrap saying no), run without
551
+ // overlays this time and check again next run.
552
+ let overlay = false, settled = true
553
+ const v = spawnSync(bwrap, ['--version'], { env, encoding: 'utf8' }).stdout.match(/(\d+)\.(\d+)/)
554
+ if (v && (+v[1] > 0 || +v[2] >= 10) && lowers.length) {
555
+ let probe
556
+ try {
557
+ probe = fs.mkdtempSync(path.join(data, 'overlay-probe-'))
558
+ const mounts = lowers.flatMap((lower, i) => {
559
+ const upper = path.join(probe, `${i}/upper`), work = path.join(probe, `${i}/work`)
560
+ fs.mkdirSync(upper, { recursive: true })
561
+ fs.mkdirSync(work, { recursive: true })
562
+ return ['--overlay-src', lower, '--overlay', upper, work, lower]
563
+ })
564
+ overlay = spawnSync(bwrap, [...base, ...mounts, 'true'], { env }).status === 0
565
+ } catch { settled = false }
566
+ try { if (probe) fs.rmSync(probe, { recursive: true, force: true }) } catch {}
567
+ }
568
+ // pasta needs its own user namespace, which AppArmor or an old passt
569
+ // package may refuse; then hazbox runs on the host network and says so.
570
+ const info = { key, overlay, ...probePasta(pastaBin, bwrap) }
571
+ if (settled) {
572
+ writeAtomic(file, info)
573
+ }
574
+ return info
575
+ }
576
+
577
+ // Written whole, then renamed, so a parallel run never reads half of it.
578
+ function writeAtomic(file, obj) {
579
+ const tmp = `${file}.${process.pid}`
580
+ try { fs.writeFileSync(tmp, JSON.stringify(obj)); fs.renameSync(tmp, file) } catch { try { fs.rmSync(tmp, { force: true }) } catch {} }
581
+ }
582
+
583
+ function probePasta(pastaBin, bwrap) {
584
+ if (!pastaBin) return { pasta: false, pastaError: '', pastaFeat: null }
585
+ if (!findBin('ip', ['/usr/sbin', '/sbin', '/usr/bin', '/bin'])) return { pasta: false, pastaError: 'the ip command (iproute2) is missing', pastaFeat: null }
586
+ const pastaFeat = pastaFeatures(pastaBin)
587
+ const base = ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--unshare-pid', '--unshare-user', '--uid', String(process.getuid()), '--gid', String(process.getgid())]
588
+ const r = spawnSync(pastaBin, [...pastaArgs(pastaFeat, [], 'none'), '--', bwrap, ...base, 'true'], { env: { PATH: '/usr/bin:/bin' }, encoding: 'utf8', timeout: 20000 })
589
+ const ok = r.status === 0
590
+ return { pasta: ok, pastaError: ok ? '' : (r.stderr || '').trim().split('\n')[0] || `exit ${r.status}`, pastaFeat }
591
+ }
592
+
593
+ const NO_PASST = 'Code in the box can reach services listening on your localhost (databases, dev tools, local AI proxies).\nInstall passt to close that: sudo apt install passt (dnf/pacman: passt)'
594
+ // What hazbox tells you when the box shares your localhost.
595
+ export function networkAdvice() {
596
+ const pastaBin = findBin('pasta')
597
+ if (!pastaBin) return NO_PASST
598
+ const { pasta, pastaError } = probePasta(pastaBin, findBwrap() ?? 'bwrap')
599
+ if (pasta) return ''
600
+ return `pasta is installed but can't start here (${pastaError}), so code in the box can reach services on your localhost.${/uid_map|namespace/i.test(pastaError) ? userNsHint('pasta', `${pastaBin}{,.avx2}`) : ''}`
601
+ }
602
+
603
+ // Ubuntu 23.10+ blocks unprivileged user namespaces unless an AppArmor
604
+ // profile allows the program. 24.04's bwrap package has no such profile.
605
+ function userNsHint(name, attach) {
606
+ if (readTrim('/proc/sys/kernel/apparmor_restrict_unprivileged_userns') !== '1') return ''
607
+ return `
608
+
609
+ Your system restricts user namespaces (kernel.apparmor_restrict_unprivileged_userns=1)
610
+ and ${name} has no AppArmor profile that allows them. Add one, once:
611
+
612
+ sudo tee /etc/apparmor.d/${name} >/dev/null <<'EOF'
613
+ abi <abi/4.0>,
614
+ include <tunables/global>
615
+ profile ${name} ${attach} flags=(unconfined) {
616
+ userns,
617
+ include if exists <local/${name}>
618
+ }
619
+ EOF
620
+ sudo apparmor_parser -r /etc/apparmor.d/${name}
621
+
622
+ This lets ${name}, and only ${name}, create user namespaces.`
623
+ }