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.
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Create the CA in `dir` unless it already exists. Safe to call twice:
3
+ * an existing `ca.pem` is reused, never regenerated.
4
+ *
5
+ * @param {string} dir directory that holds `ca.key` / `ca.pem`
6
+ * @returns {Promise<{ keyPath: string, certPath: string }>} paths of the CA key and cert
7
+ */
8
+ export function ensureCA(dir: string): Promise<{
9
+ keyPath: string;
10
+ certPath: string;
11
+ }>;
12
+ /**
13
+ * Return the key/cert for `host`, minting and caching on disk on first use.
14
+ * Concurrent calls for the same host share one `openssl` run. Key files
15
+ * are created with mode `0600`.
16
+ *
17
+ * @param {string} dir directory holding the CA (see {@link ensureCA})
18
+ * @param {string} host hostname or IP from the CONNECT line
19
+ * @returns {Promise<{ key: Buffer, cert: Buffer }>} PEM buffers for `tls.createSecureContext`
20
+ */
21
+ export function certFor(dir: string, host: string): Promise<{
22
+ key: Buffer;
23
+ cert: Buffer;
24
+ }>;
package/types/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,104 @@
1
+ /**
2
+ * A parked request, as returned by {@link pending}. Plain objects only —
3
+ * the queue itself never leaves this module.
4
+ *
5
+ * @typedef {object} HeldRequest
6
+ * @property {string} id hold id (`h<n>`)
7
+ * @property {string} agent agent name (its socket), never `c<n>`
8
+ * @property {string} method HTTP method
9
+ * @property {string} url full URL
10
+ * @property {string} body request body so far (utf8)
11
+ * @property {number} waitingSec seconds since the hold parked
12
+ */
13
+ /**
14
+ * Decide whether a request parks. Return a human-readable reason, or null
15
+ * to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
16
+ *
17
+ * @typedef {(req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null} ShouldHold
18
+ */
19
+ /**
20
+ * Create the hold queue.
21
+ *
22
+ * @param {object} opts
23
+ * @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
24
+ * @param {ShouldHold} [opts.shouldHold] decision function (default: path-substring `match`)
25
+ * @param {string} [opts.match] path substring that parks a request (default impl when `shouldHold` is absent)
26
+ * @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
27
+ * @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default 1048576)
28
+ * @param {string|null} [opts.controlSocket] unix socket path for `pending | approve | deny`
29
+ * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
30
+ * @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
31
+ * @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
32
+ */
33
+ export function createHolds({ log, shouldHold, match, timeoutMs, maxBody, controlSocket, onApprove, onDeny }: {
34
+ log: (o: Record<string, unknown>) => void;
35
+ shouldHold?: ShouldHold | undefined;
36
+ match?: string | undefined;
37
+ timeoutMs?: string | number | undefined;
38
+ maxBody?: number | undefined;
39
+ controlSocket?: string | null | undefined;
40
+ onApprove: (entry: object) => void;
41
+ onDeny: (entry: object, reason: string) => void;
42
+ }): {
43
+ add: (entry: object) => string;
44
+ decide: (req: {
45
+ agent: string;
46
+ method: string;
47
+ url: string;
48
+ headers: Record<string, string | string[] | undefined>;
49
+ }) => string | null;
50
+ approve: (id: string) => string;
51
+ deny: (id: string, reason: string) => string;
52
+ abandon: (id: string) => void;
53
+ abandonSocket: (sock: object) => void;
54
+ pending: () => HeldRequest[];
55
+ size: () => number;
56
+ close: () => void;
57
+ };
58
+ /**
59
+ * Default decision: park requests whose path contains `match`.
60
+ *
61
+ * @param {string} match path substring
62
+ * @returns {ShouldHold} decision function
63
+ */
64
+ export function matchPath(match: string): ShouldHold;
65
+ /**
66
+ * A parked request, as returned by {@link pending}. Plain objects only —
67
+ * the queue itself never leaves this module.
68
+ */
69
+ export type HeldRequest = {
70
+ /**
71
+ * hold id (`h<n>`)
72
+ */
73
+ id: string;
74
+ /**
75
+ * agent name (its socket), never `c<n>`
76
+ */
77
+ agent: string;
78
+ /**
79
+ * HTTP method
80
+ */
81
+ method: string;
82
+ /**
83
+ * full URL
84
+ */
85
+ url: string;
86
+ /**
87
+ * request body so far (utf8)
88
+ */
89
+ body: string;
90
+ /**
91
+ * seconds since the hold parked
92
+ */
93
+ waitingSec: number;
94
+ };
95
+ /**
96
+ * Decide whether a request parks. Return a human-readable reason, or null
97
+ * to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
98
+ */
99
+ export type ShouldHold = (req: {
100
+ agent: string;
101
+ method: string;
102
+ url: string;
103
+ headers: Record<string, string | string[] | undefined>;
104
+ }) => string | null;
@@ -0,0 +1,2 @@
1
+ export { launch } from "./launcher.js";
2
+ export { createProxy } from "./proxy.js";
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Build the CA bundle the sandbox trusts: system roots plus the barebox CA,
3
+ * so public hosts verify as usual and the proxy's minted certs verify too.
4
+ * Only ever reads `caFile` (the CA *cert*); the key stays outside.
5
+ * `SSL_CERT_FILE` *replaces* the system bundle, hence the combine.
6
+ *
7
+ * @param {string} runtime runtime dir the bundle is written into
8
+ * @param {string} caFile barebox CA cert path (from `proxy.caFile`)
9
+ * @returns {string} path of the combined bundle inside `runtime`
10
+ */
11
+ export function buildCaBundle(runtime: string, caFile: string): string;
12
+ /**
13
+ * Start one sandboxed agent. The agent sees a read-only `/usr` and `/etc`,
14
+ * its project and home read-only, the locked drawers masked, no network of
15
+ * its own, and a single front door: anything sent to `localhost:<proxyPort>`
16
+ * is carried out through this agent's socket to the proxy.
17
+ *
18
+ * @param {object} opts
19
+ * @param {string} opts.runtime where the runtime tree lives (`socks/` is created inside)
20
+ * @param {string} opts.agent per-agent name; the outside socket is `<runtime>/socks/<agent>.sock` and must already be listening
21
+ * @param {string} opts.proj project directory, bound read-only
22
+ * @param {string[]} opts.command argv to run inside, for example `["python3", "agent.py"]`
23
+ * @param {number} [opts.proxyPort] front-door port inside the sandbox (default 3128)
24
+ * @param {object} [opts.extraEnv] extra environment entries for the inside
25
+ * @param {string|null} [opts.socket] agent socket path, as returned by `proxy.addAgent` (default `<runtime>/socks/<agent>.sock`; the two must agree)
26
+ * @param {string|null} [opts.caFile] barebox CA cert path (from `proxy.caFile`); when set, the sandbox trusts it for HTTPS alongside the system roots
27
+ * @returns {import('node:child_process').ChildProcess} the bwrap child (stdio piped); `close` gives its exit code
28
+ * @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.
29
+ * @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.
30
+ * @example
31
+ * import { launch } from "barebox";
32
+ * const child = launch({ runtime: "/tmp/sbx", agent: "fx", proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
33
+ * await new Promise((r) => child.on("close", r)); // child.exitCode === 0
34
+ */
35
+ export function launch({ runtime, agent, proj, command, proxyPort, extraEnv, socket, caFile }: {
36
+ runtime: string;
37
+ agent: string;
38
+ proj: string;
39
+ command: string[];
40
+ proxyPort?: number | undefined;
41
+ extraEnv?: object;
42
+ socket?: string | null | undefined;
43
+ caFile?: string | null | undefined;
44
+ }): import("node:child_process").ChildProcess;
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Why `ip` (already resolved) is denied, or null when it may go through.
3
+ *
4
+ * @param {string} rawIp resolved destination IP
5
+ * @param {boolean} allowLoopback test-only opt-in for loopback + unspecified
6
+ * @returns {string|null} `loopback` / `unspecified` / `link-local` / `host-local` / `private`, or null
7
+ */
8
+ export function denyReasonForIp(rawIp: string, allowLoopback: boolean): string | null;
9
+ /**
10
+ * Check an agent name before it reaches the filesystem.
11
+ *
12
+ * @param {string} name agent name
13
+ * @returns {void} throws on `../` and friends
14
+ */
15
+ export function assertAgentName(name: string): void;
16
+ /**
17
+ * Resolve symlinks through the nearest existing ancestor: socket paths may
18
+ * not exist yet, so `realpathSync` on the full path would throw. Walks up
19
+ * to the first existing ancestor, resolves that, then re-attaches the rest.
20
+ *
21
+ * @param {string} p any path, existing or not
22
+ * @returns {string} the real (symlink-free) spelling of `p`
23
+ */
24
+ export function realPathOf(p: string): string;
25
+ /**
26
+ * The one path both sides agree on: the proxy listens here, the launcher
27
+ * binds it into the sandbox. This function is the single writer of the shape.
28
+ *
29
+ * @param {string} runtime runtime dir
30
+ * @param {string} name agent name
31
+ * @returns {string} `<runtime>/socks/<name>.sock`
32
+ */
33
+ export function socketPathForAgent(runtime: string, name: string): string;
34
+ /**
35
+ * Options for {@link createProxy}.
36
+ *
37
+ * @typedef {object} ProxyOptions
38
+ * @property {string} logFile JSON-lines log path (`req`, `resp`, `deny`, `hold`, `decide`, `hold-abandoned`)
39
+ * @property {string} [certDir] dir for the CA + minted host certs (default `<runtime>/certs`).
40
+ * Must live inside `runtime` (compared via {@link realPathOf}, so symlinks
41
+ * cannot smuggle it out): anything else throws before any side effect.
42
+ * The CA private key lives here, and the sandbox bind-mounts only the
43
+ * runtime dir — an outside certDir would expose `ca.key` through the binds.
44
+ * @property {string} [runtime] runtime dir; required for `addAgent`, default parent of `certDir`
45
+ * @property {number} [port] opt-in TCP listener for tests, bound to 127.0.0.1 only (default: none)
46
+ * @property {string} [upstreamCa] extra PEM the proxy trusts for upstream TLS, on top of system roots
47
+ * @property {HoldOptions} [hold] hold queue config, or omit to forward everything
48
+ * @property {string|null} [controlSocket] unix socket path for `pending | approve | deny`.
49
+ * Must live inside `runtime` (compared via {@link realPathOf}, so symlinks
50
+ * cannot smuggle it out): anything else throws before any side effect.
51
+ * No default — omit it when no CLI decisions are needed.
52
+ * @property {number} [upstreamTimeoutMs] give up on an upstream response after this (default 120000)
53
+ * @property {boolean} [allowLoopback] TEST-ONLY opt-in: let loopback and unspecified
54
+ * destinations through (default false). Fixture servers listen on 127.0.0.1,
55
+ * so tests pass this; production never should.
56
+ * @property {(host: string, ip: string) => boolean} [allowUpstream] escape hatch,
57
+ * consulted after DNS with each resolved IP: return true to let through a
58
+ * destination the default wall would deny. Only tests use this.
59
+ * @property {(host: string) => Promise<string[] | string | null>} [resolveUpstream] TEST-ONLY
60
+ * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
61
+ * @property {number} [clientIdleMs] kill a client tunnel idle this long; never fires mid-request (default 60000)
62
+ * @property {number} [maxLogBody] log at most this many request-body bytes, then `truncated: true` (default 1048576)
63
+ * @property {(entry: Record<string, unknown>) => Record<string, unknown>} [redact] log redaction hook, applied after built-in secret scrubbing (default: identity)
64
+ */
65
+ /**
66
+ * Hold queue options (the decision seam lives in holds.js).
67
+ *
68
+ * @typedef {object} HoldOptions
69
+ * @property {string} [match] path substring that parks a request (default decision)
70
+ * @property {import('./holds.js').ShouldHold} [shouldHold] decision function; overrides `match`
71
+ * @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
72
+ * @property {number} [maxBody] bodies over this are denied at the door, never queued (default 1048576)
73
+ */
74
+ /**
75
+ * One upstream forwarding: buffered body (approve path) or live stream.
76
+ *
77
+ * @typedef {object} ForwardArgs
78
+ * @property {string} agent agent name (its socket)
79
+ * @property {string} method HTTP method
80
+ * @property {string} url full URL
81
+ * @property {Record<string, string | string[] | undefined>} headers
82
+ * @property {Buffer} [body] buffered body (approve path)
83
+ * @property {import('node:http').IncomingMessage} [stream] live body (direct path)
84
+ * @property {import('node:http').ServerResponse} cres parked or live client response
85
+ */
86
+ /**
87
+ * Live proxy. Let `tsc` infer the shape; adopters import the name.
88
+ *
89
+ * @typedef {ReturnType<typeof createProxy>} Proxy
90
+ */
91
+ /**
92
+ * Start the front-door proxy. Every request is logged with its method, URL,
93
+ * headers and body; bytes go upstream untouched. Requests the hold rule
94
+ * flags park for a human decision instead of forwarding.
95
+ *
96
+ * @param {ProxyOptions} opts
97
+ * @returns live proxy: `ready` resolves when listeners + CA are up; the shape is inferred, see `Proxy`
98
+ * @when Reach for this HARNESS-ONLY to run the front door: it terminates agent TLS, sees every request, and parks the ones a human must decide. It decides nothing itself; pair with the launcher for sandboxes and `sbx` for decisions.
99
+ * @fails Throws synchronously on a missing `logFile` (or neither `certDir` nor `runtime`). At runtime, dead upstreams, malformed input, over-cap and timed-out holds all become loud logged HTTP errors, never silence and never a crash. A second proxy on the same port rejects `ready`, never crashes the process.
100
+ * @example
101
+ * import { createProxy } from "barebox";
102
+ * const proxy = createProxy({ port: 0, certDir: "./certs", logFile: "./mitm.log" });
103
+ * const { port } = await proxy.ready;
104
+ * await proxy.close();
105
+ */
106
+ export function createProxy(opts: ProxyOptions): {
107
+ ready: Promise<{
108
+ port: number | null;
109
+ }>;
110
+ close: () => Promise<void>;
111
+ addAgent: (name: any) => string;
112
+ removeAgent: (name: any) => void;
113
+ pending: () => import("./holds.js").HeldRequest[];
114
+ readonly caFile: string;
115
+ };
116
+ /**
117
+ * Options for {@link createProxy}.
118
+ */
119
+ export type ProxyOptions = {
120
+ /**
121
+ * JSON-lines log path (`req`, `resp`, `deny`, `hold`, `decide`, `hold-abandoned`)
122
+ */
123
+ logFile: string;
124
+ /**
125
+ * dir for the CA + minted host certs (default `<runtime>/certs`).
126
+ * Must live inside `runtime` (compared via {@link realPathOf}, so symlinks
127
+ * cannot smuggle it out): anything else throws before any side effect.
128
+ * The CA private key lives here, and the sandbox bind-mounts only the
129
+ * runtime dir — an outside certDir would expose `ca.key` through the binds.
130
+ */
131
+ certDir?: string | undefined;
132
+ /**
133
+ * runtime dir; required for `addAgent`, default parent of `certDir`
134
+ */
135
+ runtime?: string | undefined;
136
+ /**
137
+ * opt-in TCP listener for tests, bound to 127.0.0.1 only (default: none)
138
+ */
139
+ port?: number | undefined;
140
+ /**
141
+ * extra PEM the proxy trusts for upstream TLS, on top of system roots
142
+ */
143
+ upstreamCa?: string | undefined;
144
+ /**
145
+ * hold queue config, or omit to forward everything
146
+ */
147
+ hold?: HoldOptions | undefined;
148
+ /**
149
+ * unix socket path for `pending | approve | deny`.
150
+ * Must live inside `runtime` (compared via {@link realPathOf}, so symlinks
151
+ * cannot smuggle it out): anything else throws before any side effect.
152
+ * No default — omit it when no CLI decisions are needed.
153
+ */
154
+ controlSocket?: string | null | undefined;
155
+ /**
156
+ * give up on an upstream response after this (default 120000)
157
+ */
158
+ upstreamTimeoutMs?: number | undefined;
159
+ /**
160
+ * TEST-ONLY opt-in: let loopback and unspecified
161
+ * destinations through (default false). Fixture servers listen on 127.0.0.1,
162
+ * so tests pass this; production never should.
163
+ */
164
+ allowLoopback?: boolean | undefined;
165
+ /**
166
+ * escape hatch,
167
+ * consulted after DNS with each resolved IP: return true to let through a
168
+ * destination the default wall would deny. Only tests use this.
169
+ */
170
+ allowUpstream?: ((host: string, ip: string) => boolean) | undefined;
171
+ /**
172
+ * TEST-ONLY
173
+ * DNS stub: replaces the wall's resolver so rebinding is testable. Production omits it.
174
+ */
175
+ resolveUpstream?: ((host: string) => Promise<string[] | string | null>) | undefined;
176
+ /**
177
+ * kill a client tunnel idle this long; never fires mid-request (default 60000)
178
+ */
179
+ clientIdleMs?: number | undefined;
180
+ /**
181
+ * log at most this many request-body bytes, then `truncated: true` (default 1048576)
182
+ */
183
+ maxLogBody?: number | undefined;
184
+ /**
185
+ * log redaction hook, applied after built-in secret scrubbing (default: identity)
186
+ */
187
+ redact?: ((entry: Record<string, unknown>) => Record<string, unknown>) | undefined;
188
+ };
189
+ /**
190
+ * Hold queue options (the decision seam lives in holds.js).
191
+ */
192
+ export type HoldOptions = {
193
+ /**
194
+ * path substring that parks a request (default decision)
195
+ */
196
+ match?: string | undefined;
197
+ /**
198
+ * decision function; overrides `match`
199
+ */
200
+ shouldHold?: import("./holds.js").ShouldHold | undefined;
201
+ /**
202
+ * hold deadline in ms, or `'never'` (default 120000)
203
+ */
204
+ timeoutMs?: string | number | undefined;
205
+ /**
206
+ * bodies over this are denied at the door, never queued (default 1048576)
207
+ */
208
+ maxBody?: number | undefined;
209
+ };
210
+ /**
211
+ * One upstream forwarding: buffered body (approve path) or live stream.
212
+ */
213
+ export type ForwardArgs = {
214
+ /**
215
+ * agent name (its socket)
216
+ */
217
+ agent: string;
218
+ /**
219
+ * HTTP method
220
+ */
221
+ method: string;
222
+ /**
223
+ * full URL
224
+ */
225
+ url: string;
226
+ headers: Record<string, string | string[] | undefined>;
227
+ /**
228
+ * buffered body (approve path)
229
+ */
230
+ body?: Buffer<ArrayBufferLike> | undefined;
231
+ /**
232
+ * live body (direct path)
233
+ */
234
+ stream?: http.IncomingMessage | undefined;
235
+ /**
236
+ * parked or live client response
237
+ */
238
+ cres: import("node:http").ServerResponse;
239
+ };
240
+ /**
241
+ * Live proxy. Let `tsc` infer the shape; adopters import the name.
242
+ */
243
+ export type Proxy = ReturnType<typeof createProxy>;
244
+ import http from 'node:http';