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.
- package/LICENSE +21 -0
- package/README.md +139 -2
- package/bin/hazbox.mjs +67 -0
- package/package.json +34 -4
- package/src/check.mjs +266 -0
- package/src/prune.mjs +62 -0
- package/src/run.mjs +623 -0
- package/src/seccomp.mjs +74 -0
- package/src/x.mjs +102 -0
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,140 @@
|
|
|
1
|
-
#
|
|
1
|
+
# hazbox
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Your packages and agents see the project. Nothing else.
|
|
4
|
+
|
|
5
|
+
Every `npm install`, `npm run dev` or `npx something` runs code from hundreds of strangers with full access to your machine. That code can read your SSH keys, your npm and GitHub tokens, your AI tool logins and your browser cookies, and it can talk to Docker, which is root. hazbox runs the command in a box where your home directory is empty and only the project is there.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
The secrets in the demo are fake, planted in a throwaway home, and the demo package sends nothing anywhere. `demo/record.sh` rebuilds it.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npx hazbox check # what could code running here steal? (Linux, macOS)
|
|
13
|
+
hazbox npm install # run anything in the box (Linux)
|
|
14
|
+
hazbox npm run dev
|
|
15
|
+
hazbox x create-vite # see who published a package, then run it in the box
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## See your exposure first
|
|
19
|
+
|
|
20
|
+
`npx hazbox check` lists what code running in your terminal can reach right now. It prints names only, never contents. Its only network call is one empty `HEAD` request to example.com, to see whether the network is reachable. On the machine I built this on it found 28 things, among them the SSH keys behind the ssh-agent, Docker, both D-Bus buses, 55 other daemon sockets (on 2026-12-01), and Claude, Codex and GitHub logins.
|
|
21
|
+
|
|
22
|
+
## What the box blocks
|
|
23
|
+
|
|
24
|
+
Every row is backed by a test in `test/box.test.mjs`, which plants fake secrets in a throwaway home and runs on every push. For each protection I also checked that turning it off makes its test fail.
|
|
25
|
+
|
|
26
|
+
| Inside the box | |
|
|
27
|
+
|---|---|
|
|
28
|
+
| SSH keys, npm, GitHub, cloud, Docker, Cargo and PyPI credentials, GPG, Claude and Codex logins, browser profiles, Slack, Discord, keyrings | hidden. Your home is replaced by an empty per-project home |
|
|
29
|
+
| ssh-agent, Docker, D-Bus (session and system), and every other unix socket under `/run`, `/tmp`, `/var/tmp` and `/dev/shm` | absent, with or without `--offline` |
|
|
30
|
+
| services listening on your localhost (databases, dev tools, local AI proxies), abstract unix sockets, this machine's other addresses, and containers or anything else on its other networks (Docker bridges, VPNs) | unreachable when `passt` is installed: the box gets its own network from pasta. `--localhost 5432` lets one port through. Without passt, hazbox says so once. If passt is installed but can't start, hazbox warns on every run and `hazbox check` shows the fix |
|
|
31
|
+
| secret env vars | removed. Only a short allowlist passes, plus anything you add with `--env NAME`. Values you pass are never put on a command line, where other users on the machine could read them |
|
|
32
|
+
| other processes and their env, including the sandbox helper's own | invisible (separate PID namespace, helper starts with an empty env) |
|
|
33
|
+
| open files and sockets the calling program left open (editors, agents, terminal multiplexers, CI runners) | replaced with `/dev/null` before the command starts. stdin, stdout and stderr pass through as they are |
|
|
34
|
+
| your other projects | invisible |
|
|
35
|
+
| `.git` | read-only. Code inside can't plant a hook, a `core.fsmonitor` command or a `commondir` redirect, and can't rename or replace `.git`. A git command that tries to write says so and points to `--git-write` |
|
|
36
|
+
| git metadata planted by an earlier run (`core.worktree`, a `.git` file pointing at another repo) | can't widen the next run. hazbox reads the project and its git dirs from disk instead of asking git, and refuses pointers that aren't this project's worktree or submodule |
|
|
37
|
+
| the kernel session keyring, and typing into your terminal (`TIOCSTI`, `TIOCLINUX`) | blocked by a seccomp filter (x86-64 and arm64) |
|
|
38
|
+
| Node, Python, Rust, Go and other toolchains in your home | read-only, so nothing can replace a CLI you later run outside. uv's credential store isn't mounted |
|
|
39
|
+
| Claude Code | runs inside. Its installed versions are read-only, so nothing in the box can replace the `claude` you run outside. Your real `~/.claude` and `~/.claude.json` stay hidden |
|
|
40
|
+
| your agent instructions and skills | `hazbox claude` gets `~/.claude/CLAUDE.md`, `skills`, `agents` and `commands` read-only, and `hazbox codex` gets `~/.codex/AGENTS.md`, `prompts` and `skills`. Never their logins, settings or MCP config, and other commands get none of it |
|
|
41
|
+
| mounted drives (`/media`, `/mnt`) | hidden |
|
|
42
|
+
| `/etc/shadow`, `/etc/gshadow` | replaced with an empty file, in case the host's permissions are wrong |
|
|
43
|
+
| the project | read-write, as normal. hazbox adds no files to it |
|
|
44
|
+
| git | status, diff and log work. Commits need `--git-write`, which keeps hooks and config read-only. Worktrees and submodules work |
|
|
45
|
+
| dev servers | reachable from your browser at `localhost` or `127.0.0.1`. Stopping hazbox stops them |
|
|
46
|
+
| the box after hazbox stops | gone. If hazbox is killed outright, the box goes with it; a command that ignores SIGTERM is killed 5 seconds later |
|
|
47
|
+
| `--offline` | no network at all, localhost and abstract unix sockets included |
|
|
48
|
+
| your home, `~/.ssh`, `~/.config` and other credential folders, system folders, `/tmp` and `/var/tmp` themselves | refused as a project. An empty folder works as is (for scaffolders). A folder with files but no git repo or project file needs `--here` |
|
|
49
|
+
|
|
50
|
+
## Compared with other sandboxes
|
|
51
|
+
|
|
52
|
+
Measured with `scripts/compare.sh` on Ubuntu 26.04, kernel 7.0, 2026-12-01. Run it on your machine to check.
|
|
53
|
+
|
|
54
|
+
| | exposed |
|
|
55
|
+
|---|---|
|
|
56
|
+
| no sandbox | 28 |
|
|
57
|
+
| **hazbox 0.1.0** | **1** (outbound network) |
|
|
58
|
+
| nono 0.82.0, `run --allow . --read <node>` | 6: secret env vars, ssh-agent, Docker, D-Bus session, D-Bus system bus, network |
|
|
59
|
+
| srt 0.0.83 (Anthropic sandbox-runtime), default settings | did not start. Ubuntu's AppArmor user-namespace restriction blocks its seccomp helper |
|
|
60
|
+
|
|
61
|
+
nono also needed `--read` for an fnm-installed Node before it would start. I confirmed nono's gaps with real calls: the Docker API answered, `ssh-add -l` listed the keys, and the token was in the environment.
|
|
62
|
+
|
|
63
|
+
## Speed
|
|
64
|
+
|
|
65
|
+
hazbox adds a fixed cost to each command: about 0.15 to 0.2 s on my laptop, of which roughly 60 to 80 ms is pasta setting up the box's network. On anything that runs longer than a few seconds it's noise.
|
|
66
|
+
|
|
67
|
+
Measured with `scripts/bench.mjs` (median of alternating bare and boxed runs) on a laptop with an i7-8650U in its balanced power profile, Ubuntu 26.04, Node 22.17.1, bwrap 0.11.1, passt 2026-01-20, 2026-12-01. The laptop was busy with other work (load average about 3.5); I expect a quiet machine to do better, but that is a guess:
|
|
68
|
+
|
|
69
|
+
| command | bare | hazbox |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| `node -e 0` | 41 ms | 241 ms |
|
|
72
|
+
| `npm --version` | 190 ms | 348 ms |
|
|
73
|
+
| `npm run build` (new Vite + React app) | 1.08 s | 1.16 s |
|
|
74
|
+
|
|
75
|
+
The first install in a project takes as long as it does without hazbox. The box reads your npm cache through an overlay, and anything it writes goes to a separate layer for that project, so your cache and other projects never see it. Three rounds of `npm ci` in a fresh project took 17.1 to 17.6 s boxed and 17.4 to 19.5 s bare. Without the overlay the first install took 58 s, because the box started with an empty cache. The overlay needs bwrap 0.10 or newer. Ubuntu 22.04 and 24.04 ship older versions, so there the first install in each project downloads everything once.
|
|
76
|
+
|
|
77
|
+
Packages the box downloads stay in that project's layer, never in your real cache, so a second project downloads them again. Sharing them would let one project plant packages another one installs. `hazbox prune` cleans up.
|
|
78
|
+
|
|
79
|
+
pnpm's store works the same way. Measured once each on the same laptop, installing 151 packages from a lockfile with a warm store took 3.3 s in a new project and 1.3 s after that, against 1.0 s bare. Before the overlay, the first boxed install downloaded everything and took 59 s.
|
|
80
|
+
|
|
81
|
+
## Compatibility
|
|
82
|
+
|
|
83
|
+
I ran install, typecheck, lint, test and build for 9 of my own projects inside the box with `scripts/real-projects.sh`: 4 Vite + React apps, 2 Next.js sites and 3 TypeScript projects, one of them on pnpm. On the latest run (2026-12-01, with pasta networking), 28 of 30 steps passed. The other 2 failed the same way outside the box. One test suite has a test that already fails (6144 pass and 1 fails, in and out of the box), and one project has no ESLint config. No step failed only in the box.
|
|
84
|
+
|
|
85
|
+
## Coding agents
|
|
86
|
+
|
|
87
|
+
Claude Code 2.1.332 and Codex 0.172.0 both run in the box. I tested each on 2026-12-01 with a real model call. Codex talked to a Claude model through a local OpenAI-compatible proxy, since I had no OpenAI key to hand. Each ran shell commands, wrote a file in the project, and got "No such file or directory" for `~/.ssh`.
|
|
88
|
+
|
|
89
|
+
hazbox never reads, stores or forwards your agent login. The box can't see `~/.claude` or `~/.codex`, so an agent starts logged out, with its first-run setup screens. Your instructions and skills come along read-only (see the table above). You have two ways in:
|
|
90
|
+
|
|
91
|
+
- Pass a token yourself with `--env`. This is how I tested, with `hazbox --localhost 8317 --env ANTHROPIC_BASE_URL --env ANTHROPIC_AUTH_TOKEN claude` against a model proxy on my localhost. Code that runs during that command can read the token, so use one you can revoke.
|
|
92
|
+
- Log in inside the box. The login is saved in that project's box home, so you do it once per project. But every later run in that project can read it, a plain `hazbox npm install` included. I haven't tested logging in this way.
|
|
93
|
+
|
|
94
|
+
Turn off the agent's own sandbox. On Ubuntu 26.04, AppArmor stops a bubblewrap sandbox from starting inside another one, so Codex refuses to run commands until you use `--dangerously-bypass-approvals-and-sandbox`. hazbox is the sandbox there. Claude Code's sandbox is off by default.
|
|
95
|
+
|
|
96
|
+
## Limits
|
|
97
|
+
|
|
98
|
+
Read these before you trust it.
|
|
99
|
+
|
|
100
|
+
- **The internet is open** unless you pass `--offline`. Code in the box can't read your secrets, but it can send the project's own files, `.env` included, anywhere, and it can reach other machines on your network. A domain allowlist is next.
|
|
101
|
+
- **Without `passt` installed, your localhost is open too.** Code in the box can then reach services listening on localhost and abstract unix sockets, X11 among them (which matters only if your X server lets same-user clients in without a cookie; `hazbox check` tests for that). hazbox tells you once.
|
|
102
|
+
- **With passt, networks that appear after the box starts aren't blocked**, such as a VPN you connect mid-run. The next run picks them up.
|
|
103
|
+
- **With passt, the box is IPv4 only, and ports it listens on are forwarded to your localhost**, so dev servers work. Code in the box could listen on a free port that a program outside expects to find its own service on, such as 5432 while your Postgres is stopped.
|
|
104
|
+
- **Project files are fair game.** The box protects everything outside the project. Inside it, code can read and change anything, including `.env`, `package.json` scripts, `.vscode/` settings that your editor may run later, and `.claude/settings.json` hooks that Claude Code runs when you next use it outside the box. That includes git: in a folder that isn't a repo, or in a nested repo inside the project, code can write a `.git` whose config your editor's git integration would then run outside the box.
|
|
105
|
+
- **`--git-write` makes the git dir writable.** Hooks and config stay read-only, but code inside can add a file like `.git/commondir` that points host git at another config. The next `hazbox` run refuses to start if it finds one, but git commands you run before that will follow it. Use `--git-write` for agents you'd let commit anyway.
|
|
106
|
+
- **The box can read your npm cache and pnpm store** (`~/.npm/_cacache`, `~/.local/share/pnpm/store`), which hold every package you've installed, including private ones from other projects. It can't change them. Nothing else in `~/.npm` is visible.
|
|
107
|
+
- **Anything you pass with `--env` is visible to all code in the project.** That includes code an earlier run left in `node_modules` or in the project's box home, which persists between runs so caches stay warm.
|
|
108
|
+
- **`hazbox <command>` needs Linux and bubblewrap.** macOS support is in progress. On macOS, `hazbox check` works and `hazbox <command>` refuses to run instead of running unprotected.
|
|
109
|
+
- **The rest of the system is readable**, read-only: `/usr`, `/etc`, `/opt`, `/var/lib` and the like, as for any program you run. Your home, `/tmp`, `/run` and mounted drives are not.
|
|
110
|
+
- **It is not a VM.** A kernel exploit escapes it, as it escapes every container-style sandbox.
|
|
111
|
+
- **`hazbox check` looks for Docker only at its standard socket paths.**
|
|
112
|
+
|
|
113
|
+
## Install
|
|
114
|
+
|
|
115
|
+
```sh
|
|
116
|
+
npm i -g hazbox # or use npx hazbox ...
|
|
117
|
+
sudo apt install bubblewrap passt # Debian/Ubuntu; dnf/pacman have both too
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
passt is optional but recommended: without it, code in the box can reach services on your localhost.
|
|
121
|
+
|
|
122
|
+
Requires Node 18.17 or newer.
|
|
123
|
+
|
|
124
|
+
Ubuntu 23.10 and later block the user namespaces bwrap needs unless an AppArmor profile allows it. Ubuntu 24.04's bubblewrap package has no such profile. If yours is missing one, hazbox runs nothing and prints the one-time `sudo` command that adds it. Ubuntu 24.04's passt package has the same gap for pasta; there hazbox runs without pasta, and says so once with the matching command. CI applies both printed commands on Ubuntu 24.04 and checks that hazbox works, with pasta, afterwards. Each profile lets any program use that tool (bwrap or pasta) to create user namespaces, which is the thing Ubuntu restricts by default; nothing else changes.
|
|
125
|
+
|
|
126
|
+
## Cleaning up
|
|
127
|
+
|
|
128
|
+
Each project's box home and cache layers live in `~/.local/share/hazbox/projects`. `hazbox prune` deletes those of projects that no longer exist. `hazbox prune --all` deletes them all, agent logins made inside the box included.
|
|
129
|
+
|
|
130
|
+
## Package cards
|
|
131
|
+
|
|
132
|
+
`hazbox x <package>` shows the version, publish date and publisher, weekly downloads, size, dependency count, install scripts, and whether it was built in CI with provenance or trusted publishing. It warns on versions under 7 days old, packages under 30 days old, a publisher change since the previous version, install scripts, hand-published releases and low usage. Then it asks before running that exact version in the box. `--json` prints the card for scripts and agents.
|
|
133
|
+
|
|
134
|
+
## Sponsor
|
|
135
|
+
|
|
136
|
+
If hazbox saved you a bad day, [sponsor it](https://github.com/sponsors/MohibShaikh).
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
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.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
}
|