barebox 0.0.0-stage → 0.2.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/CHANGELOG.md +37 -0
- package/LICENSE +201 -0
- package/README.md +154 -2
- package/barebox.context.md +76 -0
- package/package.json +49 -4
- package/primitives.json +23 -0
- package/src/certs.js +108 -0
- package/src/cli.js +48 -0
- package/src/holds.js +164 -0
- package/src/index.js +3 -0
- package/src/launcher.js +173 -0
- package/src/proxy.js +768 -0
- package/types/certs.d.ts +24 -0
- package/types/cli.d.ts +2 -0
- package/types/holds.d.ts +104 -0
- package/types/index.d.ts +2 -0
- package/types/launcher.d.ts +44 -0
- package/types/proxy.d.ts +244 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// sbx — second-terminal CLI for the hold queue:
|
|
3
|
+
// sbx pending | approve <id> | deny <id> [reason]
|
|
4
|
+
// Talks to the proxy over its unix control socket. The socket path comes
|
|
5
|
+
// from SBX_SOCK, else from SBX_RUNTIME as `<runtime>/ctl.sock`. There is no
|
|
6
|
+
// cwd-relative default: missing both is a usage error (exit 2).
|
|
7
|
+
import net from 'node:net';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
const USAGE = 'usage: sbx [--help] | pending | approve <id> | deny <id> [reason]';
|
|
11
|
+
// Exit codes: 0 ok, 1 unknown id / refused / socket failure, 2 usage.
|
|
12
|
+
const [cmd, ...args] = process.argv.slice(2);
|
|
13
|
+
if (!cmd || cmd === '--help' || cmd === '-h') {
|
|
14
|
+
console.log(USAGE);
|
|
15
|
+
process.exit(cmd ? 0 : 2);
|
|
16
|
+
}
|
|
17
|
+
if (!['pending', 'approve', 'deny'].includes(cmd) || (cmd !== 'pending' && !args[0])) {
|
|
18
|
+
console.log(USAGE);
|
|
19
|
+
process.exit(2);
|
|
20
|
+
}
|
|
21
|
+
const sockPath = process.env.SBX_SOCK
|
|
22
|
+
|| (process.env.SBX_RUNTIME ? path.join(process.env.SBX_RUNTIME, 'ctl.sock') : null);
|
|
23
|
+
if (!sockPath) {
|
|
24
|
+
console.log(USAGE);
|
|
25
|
+
process.exit(2);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const s = net.connect(sockPath, () => { s.write([cmd, ...args].join(' ') + '\n'); });
|
|
29
|
+
s.setTimeout(5000, () => {
|
|
30
|
+
console.log('ctl timed out waiting for the proxy');
|
|
31
|
+
s.destroy();
|
|
32
|
+
process.exit(1);
|
|
33
|
+
});
|
|
34
|
+
let out = '';
|
|
35
|
+
s.on('data', (ch) => { out += ch.toString('latin1'); });
|
|
36
|
+
s.on('end', () => {
|
|
37
|
+
if (cmd === 'pending') {
|
|
38
|
+
const items = JSON.parse(out || '[]');
|
|
39
|
+
if (!items.length) { console.log('nothing held'); return; }
|
|
40
|
+
for (const h of items) {
|
|
41
|
+
console.log(`${h.id} ${h.agent} ${h.method} ${h.url} (${h.waitingSec}s) body=${h.body}`);
|
|
42
|
+
}
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
console.log(out.trim());
|
|
46
|
+
if (/^unknown /.test(out.trim())) process.exit(1);
|
|
47
|
+
});
|
|
48
|
+
s.on('error', (e) => { console.log(`ctl failed: ${e.message}`); process.exit(1); });
|
package/src/holds.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// holds.js — the ONLY writer of the hold queue.
|
|
2
|
+
//
|
|
3
|
+
// A held request parks with its client socket open until a human approves,
|
|
4
|
+
// denies, or the deadline / client / proxy goes away first. Approving a hold
|
|
5
|
+
// whose client is gone must be impossible: `abandon()` removes the entry, so
|
|
6
|
+
// a later `approve` answers `unknown <id>` and nothing is forwarded.
|
|
7
|
+
import net from 'node:net';
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A parked request, as returned by {@link pending}. Plain objects only —
|
|
12
|
+
* the queue itself never leaves this module.
|
|
13
|
+
*
|
|
14
|
+
* @typedef {object} HeldRequest
|
|
15
|
+
* @property {string} id hold id (`h<n>`)
|
|
16
|
+
* @property {string} agent agent name (its socket), never `c<n>`
|
|
17
|
+
* @property {string} method HTTP method
|
|
18
|
+
* @property {string} url full URL
|
|
19
|
+
* @property {string} body request body so far (utf8)
|
|
20
|
+
* @property {number} waitingSec seconds since the hold parked
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Decide whether a request parks. Return a human-readable reason, or null
|
|
25
|
+
* to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
|
|
26
|
+
*
|
|
27
|
+
* @typedef {(req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null} ShouldHold
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Create the hold queue.
|
|
32
|
+
*
|
|
33
|
+
* @param {object} opts
|
|
34
|
+
* @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
|
|
35
|
+
* @param {ShouldHold} [opts.shouldHold] decision function (default: path-substring `match`)
|
|
36
|
+
* @param {string} [opts.match] path substring that parks a request (default impl when `shouldHold` is absent)
|
|
37
|
+
* @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
|
|
38
|
+
* @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default 1048576)
|
|
39
|
+
* @param {string|null} [opts.controlSocket] unix socket path for `pending | approve | deny`
|
|
40
|
+
* @param {(entry: object) => void} opts.onApprove forward the parked request upstream
|
|
41
|
+
* @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
|
|
42
|
+
* @returns {{ add: (entry: object) => string, decide: (req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null, approve: (id: string) => string, deny: (id: string, reason: string) => string, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], size: () => number, close: () => void }} queue handle
|
|
43
|
+
*/
|
|
44
|
+
export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
|
|
45
|
+
maxBody = 1048576, controlSocket = null, onApprove, onDeny }) {
|
|
46
|
+
const decide = shouldHold
|
|
47
|
+
?? ((req) => (match && new URL(req.url).pathname.includes(match) ? `path matches ${match}` : null));
|
|
48
|
+
/** @returns {number|null} */
|
|
49
|
+
const deadlineMs = () => {
|
|
50
|
+
if (timeoutMs === 'never') return null;
|
|
51
|
+
const ms = timeoutMs ?? 120000;
|
|
52
|
+
return typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? ms : 120000;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
let n = 0;
|
|
56
|
+
/** @type {Map<string, object>} */
|
|
57
|
+
const queue = new Map();
|
|
58
|
+
|
|
59
|
+
const pub = (h) => ({
|
|
60
|
+
id: h.id, agent: h.agent, method: h.method, url: h.url,
|
|
61
|
+
body: h.body.toString('utf8'), waitingSec: Math.round((Date.now() - h.t0) / 1000),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
function settle(id, approve, reason) {
|
|
65
|
+
const h = queue.get(id);
|
|
66
|
+
if (!h) return `unknown ${id}`;
|
|
67
|
+
queue.delete(id);
|
|
68
|
+
if (h.timer) clearTimeout(h.timer);
|
|
69
|
+
if (approve) {
|
|
70
|
+
log({ ev: 'decide', id, agent: h.agent, decision: 'approve', reason: reason || undefined });
|
|
71
|
+
onApprove(h);
|
|
72
|
+
return `approved ${id}`;
|
|
73
|
+
}
|
|
74
|
+
log({ ev: 'decide', id, agent: h.agent, decision: 'deny', reason });
|
|
75
|
+
onDeny(h, reason);
|
|
76
|
+
return `denied ${id}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const holds = {
|
|
80
|
+
add({ agent, method, url, headers, body, sock, cres, note }) {
|
|
81
|
+
const id = `h${++n}`;
|
|
82
|
+
const ms = deadlineMs();
|
|
83
|
+
const entry = {
|
|
84
|
+
id, agent, method, url, headers, body, sock, cres, t0: Date.now(),
|
|
85
|
+
timer: ms === null ? null
|
|
86
|
+
: setTimeout(() => settle(id, false, 'hold timeout'), ms),
|
|
87
|
+
};
|
|
88
|
+
// Unref: a parked `never` hold must not keep the process alive by itself.
|
|
89
|
+
if (entry.timer?.unref) entry.timer.unref();
|
|
90
|
+
queue.set(id, entry);
|
|
91
|
+
log({ ev: 'hold', id, agent, method, url, reason: note ?? undefined,
|
|
92
|
+
timeoutMs: ms, waiting: queue.size });
|
|
93
|
+
return id;
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
approve(id) { return settle(id, true, ''); },
|
|
97
|
+
deny(id, reason) { return settle(id, false, reason || 'denied by user'); },
|
|
98
|
+
|
|
99
|
+
// The client went away: drop its holds so no later approve can forward
|
|
100
|
+
// a request nobody is listening for.
|
|
101
|
+
abandon(id) {
|
|
102
|
+
const h = queue.get(id);
|
|
103
|
+
if (!h) return;
|
|
104
|
+
queue.delete(id);
|
|
105
|
+
if (h.timer) clearTimeout(h.timer);
|
|
106
|
+
log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
|
|
107
|
+
onDeny(h, 'client gone');
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
abandonSocket(sock) {
|
|
111
|
+
for (const [id, h] of queue) {
|
|
112
|
+
if (h.sock === sock) holds.abandon(id);
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
decide(req) { return decide(req); },
|
|
117
|
+
|
|
118
|
+
pending() { return [...queue.values()].map(pub); },
|
|
119
|
+
size() { return queue.size; },
|
|
120
|
+
|
|
121
|
+
close() {
|
|
122
|
+
for (const [id] of queue) settle(id, false, 'proxy closing');
|
|
123
|
+
ctl?.close();
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
let ctl = null;
|
|
128
|
+
if (controlSocket) {
|
|
129
|
+
try { fs.unlinkSync(controlSocket); } catch {}
|
|
130
|
+
ctl = net.createServer((sock) => {
|
|
131
|
+
let line = '';
|
|
132
|
+
sock.on('data', (ch) => {
|
|
133
|
+
line += ch.toString('latin1');
|
|
134
|
+
const i = line.indexOf('\n');
|
|
135
|
+
if (i < 0) return;
|
|
136
|
+
const [cmd, arg, ...rest] = line.slice(0, i).trim().split(' ');
|
|
137
|
+
let out = '';
|
|
138
|
+
if (cmd === 'pending') out = JSON.stringify(holds.pending());
|
|
139
|
+
else if (cmd === 'approve' && arg) out = holds.approve(arg);
|
|
140
|
+
else if (cmd === 'deny' && arg) out = holds.deny(arg, rest.join(' '));
|
|
141
|
+
else out = 'usage: pending | approve <id> | deny <id> [reason]';
|
|
142
|
+
sock.end(out + '\n');
|
|
143
|
+
});
|
|
144
|
+
sock.on('error', () => {});
|
|
145
|
+
});
|
|
146
|
+
ctl.on('error', () => {});
|
|
147
|
+
ctl.listen(controlSocket, () => {
|
|
148
|
+
// Anyone who can connect can approve payments.
|
|
149
|
+
try { fs.chmodSync(controlSocket, 0o600); } catch {}
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return holds;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Default decision: park requests whose path contains `match`.
|
|
158
|
+
*
|
|
159
|
+
* @param {string} match path substring
|
|
160
|
+
* @returns {ShouldHold} decision function
|
|
161
|
+
*/
|
|
162
|
+
export function matchPath(match) {
|
|
163
|
+
return (req) => (new URL(req.url).pathname.includes(match) ? `path matches ${match}` : null);
|
|
164
|
+
}
|
package/src/index.js
ADDED
package/src/launcher.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Launcher: one sandboxed agent (bwrap walls + socat front-door bridge).
|
|
2
|
+
// Port of poc/m0/launch.sh, minus the throwaway red-team hooks: secure
|
|
3
|
+
// defaults are baked in, not switchable. No overlay (M4).
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { join, relative, isAbsolute } from 'node:path';
|
|
7
|
+
import { socketPathForAgent, assertAgentName, realPathOf } from './proxy.js';
|
|
8
|
+
|
|
9
|
+
// Locked drawers: masked with an empty tmpfs wherever they exist.
|
|
10
|
+
const LOCKED_PATHS = [
|
|
11
|
+
'.ssh',
|
|
12
|
+
'secrets',
|
|
13
|
+
'.mozilla',
|
|
14
|
+
'.config/chromium',
|
|
15
|
+
'.gnupg',
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
// System bundle locations the combined CA file is built from (first hit wins).
|
|
19
|
+
const SYSTEM_BUNDLES = [
|
|
20
|
+
'/etc/ssl/certs/ca-certificates.crt', // Debian/Ubuntu
|
|
21
|
+
'/etc/pki/tls/certs/ca-bundle.crt', // Fedora/RHEL
|
|
22
|
+
'/etc/ssl/cert.pem', // Alpine
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
// Proxy trust variables: every TLS stack worth having reads one of these.
|
|
26
|
+
const CA_ENV_VARS = ['SSL_CERT_FILE', 'NODE_EXTRA_CA_CERTS', 'REQUESTS_CA_BUNDLE',
|
|
27
|
+
'CURL_CA_BUNDLE', 'GIT_SSL_CAINFO'];
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Build the CA bundle the sandbox trusts: system roots plus the barebox CA,
|
|
31
|
+
* so public hosts verify as usual and the proxy's minted certs verify too.
|
|
32
|
+
* Only ever reads `caFile` (the CA *cert*); the key stays outside.
|
|
33
|
+
* `SSL_CERT_FILE` *replaces* the system bundle, hence the combine.
|
|
34
|
+
*
|
|
35
|
+
* @param {string} runtime runtime dir the bundle is written into
|
|
36
|
+
* @param {string} caFile barebox CA cert path (from `proxy.caFile`)
|
|
37
|
+
* @returns {string} path of the combined bundle inside `runtime`
|
|
38
|
+
*/
|
|
39
|
+
export function buildCaBundle(runtime, caFile) {
|
|
40
|
+
const ca = readFileSync(caFile, 'utf8');
|
|
41
|
+
if (!ca.includes('BEGIN CERTIFICATE')) throw new Error(`buildCaBundle: no cert in ${caFile}`);
|
|
42
|
+
let sys = '';
|
|
43
|
+
for (const p of SYSTEM_BUNDLES) {
|
|
44
|
+
if (existsSync(p)) { sys = readFileSync(p, 'utf8'); break; }
|
|
45
|
+
}
|
|
46
|
+
const out = join(runtime, 'ca-bundle.pem');
|
|
47
|
+
mkdirSync(runtime, { recursive: true });
|
|
48
|
+
writeFileSync(out, `${sys}${sys.endsWith('\n') || !sys ? '' : '\n'}${ca}`);
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Start one sandboxed agent. The agent sees a read-only `/usr` and `/etc`,
|
|
54
|
+
* its project and home read-only, the locked drawers masked, no network of
|
|
55
|
+
* its own, and a single front door: anything sent to `localhost:<proxyPort>`
|
|
56
|
+
* is carried out through this agent's socket to the proxy.
|
|
57
|
+
*
|
|
58
|
+
* @param {object} opts
|
|
59
|
+
* @param {string} opts.runtime where the runtime tree lives (`socks/` is created inside)
|
|
60
|
+
* @param {string} opts.agent per-agent name; the outside socket is `<runtime>/socks/<agent>.sock` and must already be listening
|
|
61
|
+
* @param {string} opts.proj project directory, bound read-only
|
|
62
|
+
* @param {string[]} opts.command argv to run inside, for example `["python3", "agent.py"]`
|
|
63
|
+
* @param {number} [opts.proxyPort] front-door port inside the sandbox (default 3128)
|
|
64
|
+
* @param {object} [opts.extraEnv] extra environment entries for the inside
|
|
65
|
+
* @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
|
|
66
|
+
* @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
|
|
67
|
+
* @returns {import('node:child_process').ChildProcess} the bwrap child (stdio piped); `close` gives its exit code
|
|
68
|
+
* @when Reach for this to HARNESS-ONLY start one sandboxed agent run: it creates the sandbox the agent lives in. It does not decide anything; combine with the proxy for the front door and the gate (M3) for policy.
|
|
69
|
+
* @fails Throws synchronously on a missing/empty `runtime`, `agent`, `proj`, or `command`, on a bad agent name, on an over-long socket path, when `socket` disagrees with `<runtime>/socks/<agent>.sock`, or when `runtime` IS `HOME` or the project dir (its sockets could not be hidden from the agent). The child fails at runtime (nonzero exit) when `bwrap` or `socat` is missing inside, or when nothing listens on the agent socket.
|
|
70
|
+
* @example
|
|
71
|
+
* import { launch } from "barebox";
|
|
72
|
+
* const child = launch({ runtime: "/tmp/sbx", agent: "fx", proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
|
|
73
|
+
* await new Promise((r) => child.on("close", r)); // child.exitCode === 0
|
|
74
|
+
*/
|
|
75
|
+
export function launch({ runtime, agent, proj, command, proxyPort = 3128,
|
|
76
|
+
extraEnv = {}, socket = null, caFile = null }) {
|
|
77
|
+
for (const [k, v] of Object.entries({ runtime, agent, proj })) {
|
|
78
|
+
if (typeof v !== 'string' || !v) throw new Error(`launch: ${k} must be a non-empty string`);
|
|
79
|
+
}
|
|
80
|
+
if (!Array.isArray(command) || !command.length) throw new Error('launch: command must be a non-empty argv array');
|
|
81
|
+
assertAgentName(agent);
|
|
82
|
+
// The socket IS the identity: both sides must name the same path.
|
|
83
|
+
const expected = socketPathForAgent(runtime, agent);
|
|
84
|
+
const sock = socket ?? expected;
|
|
85
|
+
if (sock !== expected) throw new Error(`launch: socket ${sock} disagrees with ${expected}`);
|
|
86
|
+
mkdirSync(join(runtime, 'socks'), { recursive: true });
|
|
87
|
+
const home = process.env.HOME || '/root';
|
|
88
|
+
const args = [
|
|
89
|
+
'--unshare-pid', '--unshare-uts', '--unshare-ipc', '--unshare-net',
|
|
90
|
+
'--die-with-parent',
|
|
91
|
+
'--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp',
|
|
92
|
+
'--ro-bind', '/usr', '/usr',
|
|
93
|
+
'--symlink', 'usr/lib64', '/lib64',
|
|
94
|
+
'--ro-bind', '/etc', '/etc',
|
|
95
|
+
'--ro-bind', proj, proj,
|
|
96
|
+
'--ro-bind', home, home,
|
|
97
|
+
];
|
|
98
|
+
for (const p of LOCKED_PATHS) {
|
|
99
|
+
if (existsSync(`${home}/${p}`)) args.push('--tmpfs', `${home}/${p}`);
|
|
100
|
+
}
|
|
101
|
+
// The runtime tree holds the control socket (approve/deny) and every
|
|
102
|
+
// agent's socket (identity). A read-only bind does NOT stop connect(2)
|
|
103
|
+
// to a unix socket, so wherever the runtime would show through the home
|
|
104
|
+
// or project binds, mask it with an empty tmpfs. (The agent's own socket
|
|
105
|
+
// is bound from the host side to /run/sbx/agent.sock, so masking the
|
|
106
|
+
// sandbox-side runtime path does not close the front door.)
|
|
107
|
+
{
|
|
108
|
+
// Lexical on purpose: bwrap sees these same spellings, so the mask
|
|
109
|
+
// lands on the path the sandbox actually shows. (`resolve` would
|
|
110
|
+
// follow symlinks and can name a path the sandbox never displays.)
|
|
111
|
+
const rt = join(runtime);
|
|
112
|
+
const hm = join(home);
|
|
113
|
+
const pr = join(proj);
|
|
114
|
+
if (rt === hm || rt === pr) {
|
|
115
|
+
throw new Error(`launch: runtime must not be ${rt === hm ? 'HOME' : 'the project dir'} itself (its sockets cannot be hidden there)`);
|
|
116
|
+
}
|
|
117
|
+
const inside = (base) => {
|
|
118
|
+
const rel = relative(base, rt);
|
|
119
|
+
return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
|
|
120
|
+
};
|
|
121
|
+
if (inside(hm) || inside(pr)) args.push('--tmpfs', rt);
|
|
122
|
+
// Real-tree mask as well: the sandbox shows the REAL tree (symlinks
|
|
123
|
+
// resolved), so a runtime passed as a symlink from outside $HOME/proj
|
|
124
|
+
// can still land inside it and stay visible through the ro-binds. The
|
|
125
|
+
// lexical mask above covers the spelling bwrap is given; this one covers
|
|
126
|
+
// the sandbox-visible spelling join(home, relative(realHome, realRt))
|
|
127
|
+
// (likewise proj). Both masks are cheap; keep both.
|
|
128
|
+
const realRt = realPathOf(rt);
|
|
129
|
+
const realHm = realPathOf(hm);
|
|
130
|
+
const realPr = realPathOf(pr);
|
|
131
|
+
if (realRt === realHm || realRt === realPr) {
|
|
132
|
+
throw new Error(`launch: runtime must not be ${realRt === realHm ? 'HOME' : 'the project dir'} itself (its sockets cannot be hidden there)`);
|
|
133
|
+
}
|
|
134
|
+
const realInside = (realBase, baseSpelling) => {
|
|
135
|
+
const rel = relative(realBase, realRt);
|
|
136
|
+
if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null;
|
|
137
|
+
return join(baseSpelling, rel);
|
|
138
|
+
};
|
|
139
|
+
for (const m of [realInside(realHm, hm), realInside(realPr, pr)]) {
|
|
140
|
+
if (m && !args.includes(m)) args.push('--tmpfs', m);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
args.push(
|
|
144
|
+
'--dir', '/run',
|
|
145
|
+
'--tmpfs', '/run/sbx',
|
|
146
|
+
'--bind', sock, '/run/sbx/agent.sock',
|
|
147
|
+
);
|
|
148
|
+
/** @type {string|null} */
|
|
149
|
+
let caBundle = null;
|
|
150
|
+
if (caFile) {
|
|
151
|
+
caBundle = buildCaBundle(runtime, caFile);
|
|
152
|
+
args.push('--ro-bind', caBundle, '/run/sbx/ca-bundle.pem');
|
|
153
|
+
}
|
|
154
|
+
args.push(
|
|
155
|
+
'--setenv', 'HOME', home,
|
|
156
|
+
'--setenv', 'PATH', '/usr/bin:/bin:/usr/sbin',
|
|
157
|
+
'--setenv', 'HTTP_PROXY', `http://127.0.0.1:${proxyPort}`,
|
|
158
|
+
'--setenv', 'HTTPS_PROXY', `http://127.0.0.1:${proxyPort}`,
|
|
159
|
+
'--setenv', 'http_proxy', `http://127.0.0.1:${proxyPort}`,
|
|
160
|
+
'--setenv', 'https_proxy', `http://127.0.0.1:${proxyPort}`,
|
|
161
|
+
);
|
|
162
|
+
if (caBundle) {
|
|
163
|
+
for (const v of CA_ENV_VARS) args.push('--setenv', v, '/run/sbx/ca-bundle.pem');
|
|
164
|
+
}
|
|
165
|
+
for (const [k, v] of Object.entries(extraEnv)) args.push('--setenv', k, String(v));
|
|
166
|
+
const door = String(proxyPort);
|
|
167
|
+
const inner = 'ip link set lo up 2>/dev/null; ' +
|
|
168
|
+
`socat TCP-LISTEN:${door},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:/run/sbx/agent.sock & ` +
|
|
169
|
+
`ok=; for i in $(seq 1 50); do (echo > /dev/tcp/127.0.0.1/${door}) 2>/dev/null && { ok=1; break; }; sleep 0.1; done; ` +
|
|
170
|
+
'[ -n "$ok" ] || exit 99; exec "$@"';
|
|
171
|
+
return spawn('bwrap', [...args, '/usr/bin/bash', '-c', inner, 'bash', ...command],
|
|
172
|
+
{ stdio: ['ignore', 'pipe', 'pipe'] });
|
|
173
|
+
}
|