hazbox 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohib Shaikh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # hazbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Your packages and agents see the project. Nothing else.
4
+
5
+ Every `npm install`, `npx something` or coding agent runs code from strangers with your full permissions. That code can read your SSH keys, your npm, GitHub and cloud tokens and your AI tool logins, and it can talk to Docker, which is root. hazbox runs the command in a box where only the project is there.
6
+
7
+ ![An install script grabs an SSH key, an npm token, AWS and GitHub logins and a token in the environment. The same install under hazbox finds nothing.](https://raw.githubusercontent.com/MohibShaikh/hazbox/main/demo/demo.gif)
8
+
9
+ The secrets in the demo are fake and the demo package sends nothing. `demo/record.sh` rebuilds it.
10
+
11
+ ## Try it
12
+
13
+ ```sh
14
+ npx hazbox check # what can code running here reach? (Linux, macOS)
15
+
16
+ npm i -g hazbox # Node 18.17+
17
+ sudo apt install bubblewrap passt # dnf and pacman have both too
18
+ hazbox npm install
19
+ hazbox npm run dev
20
+ hazbox claude
21
+ ```
22
+
23
+ `hazbox check` prints names only, never contents. On my laptop it found 28 things. Inside the box it finds 1: the internet.
24
+
25
+ ## What the box blocks
26
+
27
+ - **Your home.** SSH keys, npm, GitHub and cloud tokens, Claude and Codex logins, browser profiles. The box gets an empty home of its own for each project.
28
+ - **Daemon sockets.** ssh-agent, Docker, D-Bus and every other socket under `/run` and `/tmp`.
29
+ - **Your localhost and Docker networks** (with passt installed). `--localhost 5432` lets one port through.
30
+ - **Secret env vars, other processes and your other projects.**
31
+ - **`.git` hooks and config.** `.git` is read-only; `--git-write` allows commits and keeps hooks and config read-only.
32
+ - **Typing into your terminal and the kernel keyring**, through a seccomp filter.
33
+
34
+ Your dev server still opens in the browser. With bwrap 0.10 or newer, npm and pnpm read your warm cache, so installs aren't slower. Each command costs about 0.15 to 0.2 s.
35
+
36
+ Every item above has a test that plants fake secrets, and each test fails when its protection is removed. [The full list, the numbers and a comparison with other sandboxes →](https://github.com/MohibShaikh/hazbox/blob/main/docs/DETAILS.md)
37
+
38
+ ## Limits
39
+
40
+ - **The internet is open.** Code in the box can't read your secrets, but it can still send the project's own files, `.env` included. A domain allowlist is next.
41
+ - **Files inside the project are fair game**, including `.vscode/` settings and `.claude/settings.json` hooks that your tools run later.
42
+ - **Linux only for now.** On macOS, `check` works and `hazbox <command>` refuses to run rather than run unprotected.
43
+ - **It is not a VM.** A kernel exploit gets out of it, as it gets out of any container.
44
+
45
+ [All the limits →](https://github.com/MohibShaikh/hazbox/blob/main/docs/DETAILS.md#limits)
46
+
47
+ ## License
48
+
49
+ MIT
package/bin/hazbox.mjs ADDED
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs'
3
+ import { HazboxError, run } from '../src/run.mjs'
4
+
5
+ const HELP = `hazbox: run commands and agents where they can see your project and nothing else.
6
+
7
+ hazbox <command> [args] run a command in the box (Linux)
8
+ hazbox check [--json] show what code running here could steal
9
+ hazbox x <pkg>[@ver] [args] show who published a package, then run it in the box
10
+ hazbox prune [--all] delete box state of projects that no longer exist
11
+ hazbox --version
12
+
13
+ Run options (before the command):
14
+ --offline no network at all
15
+ --localhost PORT let the box reach one service on your localhost, e.g. 5432 (repeatable, or 5432,6379)
16
+ --env NAME pass one more environment variable through (repeatable)
17
+ --git-write allow git commits inside (hooks and config stay read-only)
18
+ --here use this folder as the project even without a project file
19
+
20
+ Examples:
21
+ hazbox npm install
22
+ hazbox npm run dev
23
+ hazbox --localhost 5432 --env DATABASE_URL npm test
24
+ hazbox claude
25
+ npx hazbox check
26
+ `
27
+
28
+ async function main(argv) {
29
+ const cmd = argv[0]
30
+ if (!cmd || cmd === '-h' || cmd === '--help' || cmd === 'help') { process.stdout.write(HELP); return cmd ? 0 : 2 }
31
+ if (cmd === '--version' || cmd === '-v') {
32
+ console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url))).version)
33
+ return 0
34
+ }
35
+ if (cmd === 'check') return (await import('../src/check.mjs')).main(argv.slice(1))
36
+ if (cmd === 'prune') return (await import('../src/prune.mjs')).main(argv.slice(1))
37
+ if (cmd === 'x') return (await import('../src/x.mjs')).main(argv.slice(1))
38
+
39
+ const opts = { offline: false, extraEnv: [], here: false, gitWrite: false, localhost: [] }
40
+ const rest = [...argv]
41
+ if (rest[0] === 'run') rest.shift()
42
+ while (rest[0]?.startsWith('--')) {
43
+ const a = rest.shift()
44
+ if (a === '--') break
45
+ if (a === '--offline') opts.offline = true
46
+ else if (a === '--env') {
47
+ const name = rest.shift()
48
+ if (!name || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new HazboxError('--env needs a variable name')
49
+ opts.extraEnv.push(name)
50
+ }
51
+ else if (a === '--here') opts.here = true
52
+ else if (a === '--git-write') opts.gitWrite = true
53
+ else if (a === '--localhost') {
54
+ const ports = (rest.shift() ?? '').split(',')
55
+ if (!ports.every(p => /^\d+$/.test(p) && +p > 0 && +p < 65536)) throw new HazboxError('--localhost needs a port or ports, like --localhost 5432 or --localhost 5432,6379')
56
+ opts.localhost.push(...ports.map(Number))
57
+ }
58
+ else throw new HazboxError(`unknown option ${a}`)
59
+ }
60
+ if (!rest.length) throw new HazboxError('no command given. Try: hazbox npm install')
61
+ return run(rest, opts)
62
+ }
63
+
64
+ main(process.argv.slice(2)).then(code => process.exit(code ?? 0), e => {
65
+ console.error(e instanceof HazboxError ? `hazbox: ${e.message}` : e)
66
+ process.exit(e instanceof HazboxError ? 2 : 1)
67
+ })
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "hazbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Run commands and coding agents where they can see your project and nothing else.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/MohibShaikh/hazbox.git"
8
+ },
9
+ "homepage": "https://github.com/MohibShaikh/hazbox#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/MohibShaikh/hazbox/issues"
12
+ },
13
+ "type": "module",
14
+ "bin": {
15
+ "hazbox": "bin/hazbox.mjs"
16
+ },
17
+ "files": [
18
+ "bin",
19
+ "src"
20
+ ],
21
+ "engines": {
22
+ "node": ">=18.17"
23
+ },
24
+ "scripts": {
25
+ "test": "node --test test/*.test.mjs"
26
+ },
27
+ "keywords": [
28
+ "sandbox",
29
+ "security",
30
+ "npm",
31
+ "supply-chain",
32
+ "agents",
33
+ "bubblewrap"
34
+ ],
35
+ "license": "MIT"
36
+ }
package/src/check.mjs ADDED
@@ -0,0 +1,266 @@
1
+ // hazbox check: what could code running here steal?
2
+ // Reports names and yes/no only. Never prints file contents or env values.
3
+ import fs from 'node:fs'
4
+ import net from 'node:net'
5
+ import os from 'node:os'
6
+ import path from 'node:path'
7
+ import { spawnSync } from 'node:child_process'
8
+
9
+ const HOME = os.homedir()
10
+ const LINUX = process.platform === 'linux'
11
+ const MAC = process.platform === 'darwin'
12
+
13
+ const SECRET_FILES = [
14
+ ['SSH private keys', '.ssh', { sshKeys: true }],
15
+ ['npm token', '.npmrc'],
16
+ ['Yarn token', '.yarnrc.yml'],
17
+ ['GitHub CLI login', '.config/gh/hosts.yml'],
18
+ ['git credentials', '.git-credentials'],
19
+ ['.netrc logins', '.netrc'],
20
+ ['AWS credentials', '.aws/credentials'],
21
+ ['Google Cloud credentials', '.config/gcloud'],
22
+ ['Azure credentials', '.azure'],
23
+ ['Kubernetes config', '.kube/config'],
24
+ ['Docker registry logins', '.docker/config.json'],
25
+ ['Cargo token', '.cargo/credentials.toml'],
26
+ ['PyPI token', '.pypirc'],
27
+ ['GPG keys', '.gnupg'],
28
+ ['Claude Code login', '.claude/.credentials.json'],
29
+ ['Claude Code config', '.claude.json'],
30
+ ['Codex login', '.codex/auth.json'],
31
+ ['shell history', '.bash_history'],
32
+ ['shell history', '.zsh_history'],
33
+ ...(LINUX ? [
34
+ ['Chrome profile', '.config/google-chrome'],
35
+ ['Chromium profile', '.config/chromium'],
36
+ ['Brave profile', '.config/BraveSoftware'],
37
+ ['Firefox profile', '.mozilla/firefox'],
38
+ ['Slack session', '.config/Slack'],
39
+ ['Discord session', '.config/discord'],
40
+ ['system keyring', '.local/share/keyrings'],
41
+ ] : []),
42
+ ...(MAC ? [
43
+ ['macOS keychains', 'Library/Keychains'],
44
+ ['Chrome profile', 'Library/Application Support/Google/Chrome'],
45
+ ['Firefox profile', 'Library/Application Support/Firefox'],
46
+ ['Slack session', 'Library/Application Support/Slack'],
47
+ ['Safari cookies', 'Library/Cookies'],
48
+ ] : []),
49
+ ]
50
+
51
+ function readable(p, { sshKeys } = {}) {
52
+ try {
53
+ const st = fs.statSync(p)
54
+ if (!st.isDirectory()) { fs.closeSync(fs.openSync(p, 'r')); return true }
55
+ const names = fs.readdirSync(p)
56
+ if (!sshKeys) return names.length > 0
57
+ // A private key is any file that isn't a public key or ssh metadata.
58
+ return names.some(n => {
59
+ if (/\.pub$|^known_hosts|^config$|^authorized_keys|^agent$/.test(n)) return false
60
+ try { fs.closeSync(fs.openSync(path.join(p, n), 'r')); return fs.statSync(path.join(p, n)).isFile() } catch { return false }
61
+ })
62
+ } catch { return false }
63
+ }
64
+
65
+ // Databases, Chrome DevTools, Docker over TCP, local LLM servers, Jupyter.
66
+ const LOCAL_PORTS = [2375, 3306, 5432, 5984, 6379, 8888, 9200, 9222, 11434, 27017]
67
+
68
+ // Every TCP port listening on loopback or on all addresses, from the
69
+ // kernel's socket tables (Linux), plus the common ones above.
70
+ function listeningPorts() {
71
+ const ports = new Set(LOCAL_PORTS)
72
+ for (const f of ['/proc/net/tcp', '/proc/net/tcp6']) {
73
+ let rows = []
74
+ try { rows = fs.readFileSync(f, 'utf8').trim().split('\n').slice(1) } catch {}
75
+ for (const r of rows) {
76
+ const [, local, , st] = r.trim().split(/\s+/)
77
+ if (st !== '0A') continue
78
+ const [addr, port] = local.split(':')
79
+ const any = /^0+$/.test(addr)
80
+ const lo4 = addr.length === 8 && addr.endsWith('7F')
81
+ const lo6 = addr === '00000000000000000000000001000000'
82
+ if (any || lo4 || lo6) ports.add(parseInt(port, 16))
83
+ }
84
+ }
85
+ return [...ports].sort((a, b) => a - b)
86
+ }
87
+
88
+ function canConnectTcp(port, host = '127.0.0.1') {
89
+ return new Promise(resolve => {
90
+ const s = net.connect(port, host)
91
+ const done = v => { s.destroy(); resolve(v) }
92
+ s.on('connect', () => done(true))
93
+ s.on('error', () => done(false))
94
+ setTimeout(() => done(false), 800)
95
+ })
96
+ }
97
+
98
+ function findSockets(roots, depth) {
99
+ const out = new Set()
100
+ const walk = (d, n) => {
101
+ let ents
102
+ try { ents = fs.readdirSync(d, { withFileTypes: true }) } catch { return }
103
+ for (const e of ents) {
104
+ const p = path.join(d, e.name)
105
+ if (e.isSocket()) out.add(fs.realpathSync.native ? safeReal(p) : p)
106
+ else if (e.isDirectory() && n > 0 && !p.startsWith('/run/user')) walk(p, n - 1)
107
+ }
108
+ }
109
+ for (const r of roots) walk(r, depth)
110
+ return [...out].filter(p => p !== '/run/dbus/system_bus_socket' && !/docker\.sock$/.test(p))
111
+ }
112
+ function safeReal(p) { try { return fs.realpathSync(p) } catch { return p } }
113
+
114
+ function canConnect(p) {
115
+ return new Promise(resolve => {
116
+ if (!p) return resolve(false)
117
+ const s = net.connect(p)
118
+ const done = v => { s.destroy(); resolve(v) }
119
+ s.on('connect', () => done(true))
120
+ s.on('error', () => done(false))
121
+ setTimeout(() => done(false), 1500)
122
+ })
123
+ }
124
+
125
+ // X11 connection setup without auth data. Reply byte 1 = accepted,
126
+ // 0 = refused (needs a cookie), no connection = closed.
127
+ function x11Open(p) {
128
+ return new Promise(resolve => {
129
+ const s = net.connect(p)
130
+ const done = v => { s.destroy(); resolve(v) }
131
+ s.on('connect', () => { const b = Buffer.alloc(12); b[0] = 0x6c; b.writeUInt16LE(11, 2); s.write(b) })
132
+ s.once('data', d => done(d[0] === 1 ? 'open' : 'needs-cookie'))
133
+ s.on('error', () => done('closed'))
134
+ s.on('close', () => done('closed'))
135
+ setTimeout(() => done('closed'), 1500)
136
+ })
137
+ }
138
+
139
+ const SECRET_NAME = /token|secret|passw|api_?key|private_?key|credential|(^|_)auth(_|$)/i
140
+ const isSecretName = k => SECRET_NAME.test(k) && k !== 'SSH_AUTH_SOCK' && k !== 'XAUTHORITY'
141
+
142
+ function otherProcessSecrets() {
143
+ if (!LINUX) return 0
144
+ let n = 0
145
+ const self = String(process.pid)
146
+ for (const pid of fs.readdirSync('/proc')) {
147
+ if (!/^\d+$/.test(pid) || pid === self) continue
148
+ try {
149
+ const env = fs.readFileSync(`/proc/${pid}/environ`, 'latin1').split('\0')
150
+ if (env.some(kv => isSecretName(kv.split('=')[0]))) n++
151
+ } catch {}
152
+ }
153
+ return n
154
+ }
155
+
156
+ function projectRoot() {
157
+ const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' })
158
+ return r.status === 0 ? r.stdout.trim() : process.cwd()
159
+ }
160
+
161
+ export async function check() {
162
+ const items = []
163
+ const add = (group, name, exposed, detail = '') => items.push({ group, name, exposed, detail })
164
+
165
+ const seen = new Set()
166
+ for (const [name, rel, opts] of SECRET_FILES) {
167
+ const hit = readable(path.join(HOME, rel), opts)
168
+ if (hit && seen.has(name)) continue
169
+ if (hit) seen.add(name)
170
+ add('files', name, hit, `~/${rel}`)
171
+ }
172
+
173
+ const envNames = Object.keys(process.env).filter(isSecretName)
174
+ add('env', 'secret-looking env vars', envNames.length > 0, envNames.join(', '))
175
+ const procs = otherProcessSecrets()
176
+ add('env', 'other processes\' env vars', procs > 0, procs ? `${procs} processes with secret-looking vars` : '')
177
+
178
+ const uid = os.userInfo().uid
179
+ add('sockets', 'ssh-agent (push and sign as you)', await canConnect(process.env.SSH_AUTH_SOCK), process.env.SSH_AUTH_SOCK ?? '')
180
+ const dockerPaths = ['/var/run/docker.sock', `${HOME}/.docker/run/docker.sock`, `${HOME}/.colima/default/docker.sock`, `${HOME}/.orbstack/run/docker.sock`]
181
+ let docker = ''
182
+ for (const p of dockerPaths) if (await canConnect(p)) { docker = p; break }
183
+ add('sockets', 'Docker (root on this machine)', Boolean(docker), docker)
184
+ if (LINUX) {
185
+ const bus = process.env.DBUS_SESSION_BUS_ADDRESS?.match(/unix:path=([^,;]+)/)?.[1] ?? `/run/user/${uid}/bus`
186
+ add('sockets', 'D-Bus session (keyring, desktop)', await canConnect(bus), bus)
187
+ add('sockets', 'D-Bus system bus (root services: systemd, NetworkManager, ...)', await canConnect('/run/dbus/system_bus_socket'), '/run/dbus/system_bus_socket')
188
+ const daemons = []
189
+ for (const p of findSockets(['/run', '/var/run', '/tmp', '/var/tmp'], 5)) if (await canConnect(p)) daemons.push(p)
190
+ add('sockets', 'any other daemon socket (snapd, CUPS, ...)', daemons.length > 0, daemons.length ? `${daemons.length}: ${daemons.slice(0, 6).join(', ')}${daemons.length > 6 ? ', ...' : ''}` : '')
191
+ // X11 lets a client in with no cookie (xhost +local:, SI:localuser), or
192
+ // with the cookie file if code here can read it.
193
+ const cookie = [process.env.XAUTHORITY, path.join(HOME, '.Xauthority')].some(p => p && readable(p))
194
+ const x11 = []
195
+ for (const n of [0, 1, 2]) {
196
+ for (const p of [`\0/tmp/.X11-unix/X${n}`, `/tmp/.X11-unix/X${n}`]) {
197
+ const v = await x11Open(p)
198
+ if (v === 'open' || (v === 'needs-cookie' && cookie)) { x11.push(`X${n}${v === 'open' ? ' (no cookie needed)' : ' (cookie readable)'}`); break }
199
+ }
200
+ }
201
+ add('sockets', 'X11 display (keystrokes, screen)', x11.length > 0, x11.join(', '))
202
+ }
203
+ const ports = []
204
+ for (const port of listeningPorts()) if (await canConnectTcp(port) || await canConnectTcp(port, '::1')) ports.push(port)
205
+ add('sockets', 'services listening on localhost', ports.length > 0, ports.length ? `ports ${ports.join(', ')}` : '')
206
+
207
+ const root = projectRoot()
208
+ let siblings = 0, where = path.dirname(root)
209
+ // Inside hazbox, a project that sits directly in $HOME has the per-project
210
+ // throwaway home as its parent; that isn't another project.
211
+ const parentIsBoxHome = process.env.HAZBOX === '1' && path.dirname(root) === HOME
212
+ // Run from your home itself (or above it), everything in it is in reach.
213
+ if (root === HOME || HOME.startsWith(root + path.sep) || root === '/') where = HOME
214
+ try { if (!parentIsBoxHome) siblings = fs.readdirSync(where).filter(n => where === HOME && root === HOME ? true : n !== path.basename(root)).length } catch {}
215
+ add('reach', 'other projects next to this one', siblings > 0, siblings ? `${siblings} entries in ${where}` : '')
216
+
217
+ // Host git runs what the git dir says: hooks, config commands, or a whole
218
+ // other git dir through `commondir`. Writable git dir = code runs outside.
219
+ let gitWrite = false
220
+ const gitDir = spawnSync('git', ['rev-parse', '--absolute-git-dir'], { encoding: 'utf8' })
221
+ if (gitDir.status === 0) {
222
+ for (const d of [gitDir.stdout.trim(), path.join(gitDir.stdout.trim(), 'hooks')]) {
223
+ const probe = path.join(d, `.hazbox-probe-${process.pid}`)
224
+ try { fs.writeFileSync(probe, ''); fs.unlinkSync(probe); gitWrite = true } catch {}
225
+ }
226
+ }
227
+ add('reach', 'git dir (hooks, config, commondir run by git outside)', gitWrite)
228
+
229
+ let homeWrite = false
230
+ const marker = path.join(HOME, `.hazbox-probe-${process.pid}`)
231
+ try { fs.writeFileSync(marker, ''); fs.unlinkSync(marker); homeWrite = true } catch {}
232
+ const sandboxedHome = process.env.HAZBOX === '1'
233
+ add('reach', sandboxedHome ? 'write to home (throwaway per-project home)' : 'write to your home (persistence, e.g. shell rc)', homeWrite && !sandboxedHome)
234
+
235
+ let netOk = false
236
+ try { await fetch('https://example.com', { method: 'HEAD', signal: AbortSignal.timeout(4000) }); netOk = true } catch {}
237
+ add('network', 'outbound internet (send data out)', netOk)
238
+
239
+ return { platform: process.platform, sandboxed: sandboxedHome, items, exposed: items.filter(i => i.exposed).length }
240
+ }
241
+
242
+ export async function main(args) {
243
+ const r = await check()
244
+ if (args.includes('--json')) { console.log(JSON.stringify(r, null, 2)); return r.exposed ? 1 : 0 }
245
+ const color = process.stdout.isTTY && !process.env.NO_COLOR
246
+ const red = s => color ? `\x1b[31m${s}\x1b[0m` : s
247
+ const green = s => color ? `\x1b[32m${s}\x1b[0m` : s
248
+ console.log(`\nhazbox check: what code running here can reach${r.sandboxed ? ' (inside hazbox)' : ''}\n`)
249
+ for (const i of r.items) {
250
+ if (!i.exposed && i.group === 'files') continue
251
+ const mark = i.exposed ? red('EXPOSED') : green('blocked')
252
+ console.log(` ${mark} ${i.name}${i.exposed && i.detail ? ` (${i.detail})` : ''}`)
253
+ }
254
+ const files = r.items.filter(i => i.group === 'files')
255
+ const hiddenFiles = files.filter(i => !i.exposed).length
256
+ console.log(` ${green('blocked')} ${hiddenFiles} other secret locations (not readable or not present)`)
257
+ console.log(`\n ${r.exposed} exposed.`)
258
+ if (r.exposed && !r.sandboxed) console.log(` Run your commands as \`hazbox <command>\` to hide all of this.${LINUX ? '' : ' (Linux today, macOS in progress.)'}`)
259
+ console.log(' Nothing was sent anywhere; the network test only contacts example.com.\n')
260
+ // Whether `hazbox <command>` can keep the box off your localhost here.
261
+ if (LINUX && !r.sandboxed) {
262
+ const advice = (await import('./run.mjs')).networkAdvice()
263
+ if (advice) console.log(` Note for hazbox runs: ${advice}\n`)
264
+ }
265
+ return r.exposed ? 1 : 0
266
+ }
package/src/prune.mjs ADDED
@@ -0,0 +1,62 @@
1
+ // hazbox prune: delete the box state (home, caches, tmp) of projects that
2
+ // no longer exist, or of every project with --all.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { spawnSync } from 'node:child_process'
6
+ import { dataDir } from './run.mjs'
7
+
8
+ // Code in the box can leave folders without permissions in its box home;
9
+ // restore them so removal can't be stopped.
10
+ function remove(dir) {
11
+ try { fs.rmSync(dir, { recursive: true, force: true }) } catch {
12
+ spawnSync('chmod', ['-R', 'u+rwx', dir])
13
+ fs.rmSync(dir, { recursive: true, force: true })
14
+ }
15
+ }
16
+
17
+ function du(p) {
18
+ let n = 0
19
+ const walk = d => {
20
+ let ents
21
+ try { ents = fs.readdirSync(d, { withFileTypes: true }) } catch { return }
22
+ for (const e of ents) {
23
+ const f = path.join(d, e.name)
24
+ if (e.isDirectory()) walk(f)
25
+ else try { n += fs.lstatSync(f).blocks * 512 } catch {}
26
+ }
27
+ }
28
+ walk(p)
29
+ return n
30
+ }
31
+ const mb = n => `${(n / 1e6).toFixed(0)} MB`
32
+
33
+ export function main(args) {
34
+ const all = args.includes('--all')
35
+ const dry = args.includes('--dry-run')
36
+ const bad = args.filter(a => a !== '--all' && a !== '--dry-run')
37
+ if (bad.length) { console.error(`usage: hazbox prune [--all] [--dry-run]`); return 2 }
38
+ const root = path.join(dataDir(), 'projects')
39
+ let freed = 0, n = 0, kept = 0, unknown = 0, failed = 0
40
+ for (const h of fs.existsSync(root) ? fs.readdirSync(root) : []) {
41
+ const dir = path.join(root, h)
42
+ let project = ''
43
+ try { project = fs.readFileSync(path.join(dir, 'project'), 'utf8').trim() } catch {}
44
+ // State from before hazbox recorded its project is kept: it may belong
45
+ // to a project that still exists.
46
+ if (!project) unknown++
47
+ const gone = project && !fs.existsSync(project)
48
+ if (!all && !gone) { kept++; continue }
49
+ if (fs.existsSync(path.join(dir, 'layers.lock'))) { kept++; continue }
50
+ const size = du(dir)
51
+ const label = project || `(unknown project) ${h}`
52
+ if (!dry) {
53
+ try { remove(dir) } catch (e) { console.error(`couldn't remove ${dir}: ${e.message}`); failed++; continue }
54
+ }
55
+ console.log(`${dry ? 'would remove' : 'removed'} ${mb(size).padStart(7)} ${label}`)
56
+ freed += size
57
+ n++
58
+ }
59
+ console.log(`${dry ? 'would free' : 'freed'} ${mb(freed)} from ${n} project${n === 1 ? '' : 's'}${all ? '' : ' that no longer exist'}; kept ${kept}${failed ? `; ${failed} couldn't be removed` : ''}`)
60
+ if (!all && kept) console.log(`kept: projects still on disk${unknown ? `, and ${unknown} from an older hazbox that didn't record its project` : ''}. --all removes every project's box state, agent logins included.`)
61
+ return failed ? 1 : 0
62
+ }
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
+ }
@@ -0,0 +1,74 @@
1
+ // A small seccomp filter for bwrap --seccomp. It refuses, with EPERM:
2
+ // - keyctl, add_key, request_key: the kernel session keyring is shared with
3
+ // the parent shell, and tools keep tickets and keys there.
4
+ // - ioctl TIOCSTI and TIOCLINUX: push keystrokes into the terminal, which
5
+ // the shell outside reads after the box exits.
6
+ // Everything else is allowed. Returns null on CPUs it doesn't know.
7
+
8
+ const ERRNO_EPERM = 0x00050001
9
+ const ALLOW = 0x7fff0000
10
+ const TIOCSTI = 0x5412
11
+ const TIOCLINUX = 0x541c
12
+
13
+ // AUDIT_ARCH value -> syscall numbers. The 32-bit ABIs are included because a
14
+ // 64-bit kernel accepts them too.
15
+ const ARCHES = {
16
+ x64: [
17
+ { arch: 0xc000003e, keyctl: 250, add_key: 248, request_key: 249, ioctl: 16, x32: true },
18
+ { arch: 0x40000003, keyctl: 288, add_key: 286, request_key: 287, ioctl: 54 }, // i386
19
+ ],
20
+ arm64: [
21
+ { arch: 0xc00000b7, keyctl: 219, add_key: 217, request_key: 218, ioctl: 29 },
22
+ { arch: 0x40000028, keyctl: 311, add_key: 309, request_key: 310, ioctl: 54 }, // arm
23
+ ],
24
+ }
25
+
26
+ // seccomp_data: int nr; u32 arch; u64 ip; u64 args[6]. The kernel reads
27
+ // ioctl's cmd as 32 bits, so compare only the low half of args[1].
28
+ const NR = 0, ARCH = 4, ARG1_LO = 24
29
+
30
+ export function seccompFilter(cpu = process.arch) {
31
+ const arches = ARCHES[cpu]
32
+ if (!arches) return null
33
+ const prog = [] // [code, jt, jf, k] with jt/jf as labels or 0
34
+ const LD = k => prog.push([0x20, 0, 0, k])
35
+ const JEQ = (k, jt, jf = 0) => prog.push([0x15, jt, jf, k])
36
+ const JGE = (k, jt, jf = 0) => prog.push([0x35, jt, jf, k])
37
+ const RET = k => prog.push([0x06, 0, 0, k])
38
+ const labels = {}
39
+ const label = name => { labels[name] = prog.length }
40
+
41
+ LD(ARCH)
42
+ arches.forEach((a, i) => JEQ(a.arch, `arch${i}`))
43
+ RET(ERRNO_EPERM) // an ABI this filter doesn't cover
44
+ arches.forEach((a, i) => {
45
+ label(`arch${i}`)
46
+ LD(NR)
47
+ if (a.x32) JGE(0x40000000, 'deny') // x32 ABI on x86-64
48
+ for (const n of [a.keyctl, a.add_key, a.request_key]) JEQ(n, 'deny')
49
+ JEQ(a.ioctl, 'ioctl')
50
+ RET(ALLOW)
51
+ })
52
+ label('ioctl')
53
+ LD(ARG1_LO)
54
+ JEQ(TIOCSTI, 'deny')
55
+ JEQ(TIOCLINUX, 'deny')
56
+ RET(ALLOW)
57
+ label('deny')
58
+ RET(ERRNO_EPERM)
59
+
60
+ const buf = Buffer.alloc(prog.length * 8)
61
+ prog.forEach(([code, jt, jf, k], pc) => {
62
+ const off = t => {
63
+ if (t === 0) return 0
64
+ const d = labels[t] - pc - 1
65
+ if (!(d >= 0 && d < 256)) throw new Error(`seccomp: bad jump to ${t}`)
66
+ return d
67
+ }
68
+ buf.writeUInt16LE(code, pc * 8)
69
+ buf.writeUInt8(off(jt), pc * 8 + 2)
70
+ buf.writeUInt8(off(jf), pc * 8 + 3)
71
+ buf.writeUInt32LE(k >>> 0, pc * 8 + 4)
72
+ })
73
+ return buf
74
+ }
package/src/x.mjs ADDED
@@ -0,0 +1,102 @@
1
+ // hazbox x: npx with a card. Shows who published what you're about to run,
2
+ // then runs that exact version inside the box.
3
+ import readline from 'node:readline/promises'
4
+ import os from 'node:os'
5
+ import { run, findProject, HazboxError } from './run.mjs'
6
+
7
+ const DAY = 86400e3
8
+
9
+ export async function card(spec) {
10
+ const at = spec.lastIndexOf('@')
11
+ const name = at > 0 ? spec.slice(0, at) : spec
12
+ const want = at > 0 ? spec.slice(at + 1) : 'latest'
13
+ const res = await fetch(`https://registry.npmjs.org/${name.replace('/', '%2f')}`, { signal: AbortSignal.timeout(15000) })
14
+ if (!res.ok) throw new HazboxError(`${name} not found on npm (HTTP ${res.status})`)
15
+ const doc = await res.json()
16
+ const version = doc['dist-tags']?.[want] ?? want
17
+ const v = doc.versions?.[version]
18
+ if (!v) throw new HazboxError(`${name}@${want} not found`)
19
+
20
+ const now = Date.now()
21
+ const ordered = Object.keys(doc.versions).filter(k => doc.time?.[k]).sort((a, b) => new Date(doc.time[a]) - new Date(doc.time[b]))
22
+ const prev = doc.versions[ordered[ordered.indexOf(version) - 1]]
23
+ const scripts = ['preinstall', 'install', 'postinstall'].filter(s => v.scripts?.[s])
24
+ const dl = await fetch(`https://api.npmjs.org/downloads/point/last-week/${name}`, { signal: AbortSignal.timeout(10000) })
25
+ .then(r => r.json()).catch(() => ({}))
26
+
27
+ const c = {
28
+ package: name, version,
29
+ published: doc.time?.[version]?.slice(0, 10) ?? null,
30
+ ageDays: doc.time?.[version] ? Math.floor((now - new Date(doc.time[version])) / DAY) : null,
31
+ packageAgeDays: doc.time?.created ? Math.floor((now - new Date(doc.time.created)) / DAY) : null,
32
+ publisher: v._npmUser?.name ?? null,
33
+ previousPublisher: prev?._npmUser?.name ?? null,
34
+ weeklyDownloads: dl.downloads ?? null,
35
+ unpackedSize: v.dist?.unpackedSize ?? null,
36
+ dependencies: Object.keys(v.dependencies ?? {}).length,
37
+ installScripts: scripts,
38
+ provenance: Boolean(v.dist?.attestations?.provenance),
39
+ trustedPublisher: v._npmUser?.trustedPublisher?.id ?? null,
40
+ deprecated: v.deprecated ?? null,
41
+ repository: typeof v.repository === 'string' ? v.repository : v.repository?.url ?? null,
42
+ }
43
+ const w = []
44
+ if (c.ageDays !== null && c.ageDays < 7) w.push(`this version is ${c.ageDays} day(s) old; brand-new releases carry the most risk`)
45
+ if (c.packageAgeDays !== null && c.packageAgeDays < 30) w.push(`the package itself is only ${c.packageAgeDays} day(s) old`)
46
+ if (c.previousPublisher && c.publisher && c.previousPublisher !== c.publisher) w.push(`published by ${c.publisher}; the previous version was published by ${c.previousPublisher}`)
47
+ if (scripts.length) w.push(`runs install scripts: ${scripts.join(', ')}`)
48
+ if (!c.provenance && !c.trustedPublisher) w.push('published from a personal machine or token (no provenance, no trusted publishing)')
49
+ if (c.weeklyDownloads !== null && c.weeklyDownloads < 1000) w.push(`low usage: ${c.weeklyDownloads} downloads last week`)
50
+ if (c.deprecated) w.push(`deprecated: ${c.deprecated}`)
51
+ c.warnings = w
52
+ return c
53
+ }
54
+
55
+ // Every string here comes from the registry, where anyone can publish
56
+ // anything. Strip control characters so text can't move the cursor and
57
+ // overwrite the warnings above the prompt.
58
+ export const clean = v => typeof v === 'string' ? v.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ')
59
+ : Array.isArray(v) ? v.map(clean)
60
+ : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, clean(x)]))
61
+ : v
62
+
63
+ const size = n => n == null ? '?' : n > 1e6 ? `${(n / 1e6).toFixed(1)} MB` : `${Math.round(n / 1e3)} kB`
64
+
65
+ export async function main(argv) {
66
+ const f = { yes: false, json: false, offline: false, here: false }
67
+ while (argv[0]?.startsWith('-')) {
68
+ const a = argv.shift()
69
+ if (a === '-y' || a === '--yes') f.yes = true
70
+ else if (a === '--json') f.json = true
71
+ else if (a === '--offline') f.offline = true
72
+ else if (a === '--here') f.here = true
73
+ else throw new HazboxError(`unknown flag ${a}`)
74
+ }
75
+ const spec = argv.shift()
76
+ if (!spec) throw new HazboxError('usage: hazbox x [-y] [--json] [--offline] [--here] <package>[@version] [args...]')
77
+ // Check the folder before fetching anything, so a refusal comes first.
78
+ if (!f.json && process.platform === 'linux') findProject(process.cwd(), os.homedir(), f.here)
79
+ const c = clean(await card(spec))
80
+ if (f.json) { console.log(JSON.stringify(c, null, 2)); return 0 }
81
+
82
+ const src = c.provenance ? 'provenance ✓' : c.trustedPublisher ? `trusted publishing ✓ (${c.trustedPublisher})` : 'published by hand'
83
+ const linux = process.platform === 'linux'
84
+ process.stderr.write(`
85
+ ${c.package}@${c.version}
86
+ published ${c.published ?? '?'}${c.ageDays !== null ? ` (${c.ageDays}d ago)` : ''} by ${c.publisher ?? '?'}
87
+ usage ${c.weeklyDownloads?.toLocaleString('en-US') ?? '?'} downloads/week · ${size(c.unpackedSize)} · ${c.dependencies} deps
88
+ source ${src} · ${c.repository ?? 'no repo listed'}
89
+ it gets ${linux ? `this project only · no secrets · network: ${f.offline ? 'none' : 'yes'}` : 'NOT SANDBOXED (hazbox run is Linux-only for now)'}
90
+ ${c.warnings.length ? c.warnings.map(x => ` ⚠ ${x}`).join('\n') : ' no warnings'}
91
+
92
+ `)
93
+ if (!linux) return 0
94
+ if (!f.yes) {
95
+ if (!process.stdin.isTTY) throw new HazboxError('not a terminal; pass -y to run')
96
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr })
97
+ const ans = (await rl.question(' run it? [y/N] ')).trim().toLowerCase()
98
+ rl.close()
99
+ if (ans !== 'y' && ans !== 'yes') return 1
100
+ }
101
+ return run(['npx', '--yes', `${c.package}@${c.version}`, ...argv], { offline: f.offline, here: f.here })
102
+ }