korveniq 1.0.6 → 1.0.7

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,275 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * lib/pkg-install.js
5
+ * -----------------------------------------------------------------------------
6
+ * Which shell commands are a plain package installation that may be given the registry (after a person says yes), and
7
+ * the exact steps they are turned into. Only these forms, each on its own (optionally after one `cd <folder> &&`):
8
+ *
9
+ * npm install|i|add [names[@version]] [safe flags] npm ci [safe flags]
10
+ * <venv>/bin/pip install ... <venv>/bin/python -m pip install ...
11
+ * source <venv>/bin/activate && pip install ...
12
+ *
13
+ * Nothing the project provides runs while the network is open:
14
+ * npm step 1 (registry): npm itself, with install scripts OFF and the project's settings overridden
15
+ * step 2 (offline): npm rebuild, which runs the install scripts
16
+ * pip step 1 (registry): the system's Python and pip download ready-built wheels only (no setup.py runs)
17
+ * step 2 (offline): the virtual environment's pip installs the downloaded files
18
+ * Anything else (shell operators, URLs, git or file dependencies, other registries or index options, global installs)
19
+ * is not an "installation" here: it runs like any command, without network.
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const { spawnSync } = require('child_process');
25
+
26
+ const HOSTS = Object.freeze({ npm: Object.freeze(['registry.npmjs.org']), pip: Object.freeze(['pypi.org', 'files.pythonhosted.org']) });
27
+ const NPM_REGISTRY = 'https://registry.npmjs.org/';
28
+ const PYPI_INDEX = 'https://pypi.org/simple/';
29
+
30
+ const NPM_FLAGS = new Set(['-D', '--save-dev', '-S', '--save', '--save-prod', '-P', '-O', '--save-optional', '-E', '--save-exact', '--no-save', '--omit=dev', '--include=dev', '--production', '--legacy-peer-deps', '--no-audit', '--no-fund', '--no-package-lock']);
31
+ const NPM_SPEC = /^(@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*(@(\^|~|>=?|<=?|=)?[A-Za-z0-9.*x+-]+)?$/i;
32
+ const PIP_SPEC = /^[A-Za-z0-9][A-Za-z0-9._-]*(\[[A-Za-z0-9,._-]+\])?((===|==|>=|<=|~=|!=|>|<)\s*[A-Za-z0-9.*+!_-]+(\s*,\s*(==|>=|<=|~=|!=|>|<)\s*[A-Za-z0-9.*+!_-]+)*)?$/;
33
+ const PIP_FLAGS = new Set(['-U', '--upgrade', '-q', '--quiet']);
34
+
35
+ const shellQuote = (s) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`);
36
+
37
+ /**
38
+ * Split a command into words and "&&". null when it uses anything else a shell would act on.
39
+ * @returns {string[][]|null} the words of each "&&"-separated part
40
+ */
41
+ function words(command) {
42
+ const parts = [[]];
43
+ let word = null;
44
+ const end = () => {
45
+ if (word !== null) parts[parts.length - 1].push(word);
46
+ word = null;
47
+ };
48
+ for (let i = 0; i < command.length; i++) {
49
+ const c = command[i];
50
+ if (c === "'" || c === '"') {
51
+ const close = command.indexOf(c, i + 1);
52
+ if (close === -1) return null;
53
+ const inner = command.slice(i + 1, close);
54
+ if (/[\n\r]/.test(inner) || (c === '"' && /[$`\\]/.test(inner))) return null;
55
+ word = (word || '') + inner;
56
+ i = close;
57
+ } else if (c === ' ' || c === '\t') end();
58
+ else if (c === '&' && command[i + 1] === '&') {
59
+ end();
60
+ parts.push([]);
61
+ i++;
62
+ } else if (/[\n\r;&|<>`$(){}[\]*?!\\#~]/.test(c) && !(c === '~' && word !== null)) return null;
63
+ else word = (word || '') + c;
64
+ }
65
+ end();
66
+ return parts.every((p) => p.length) ? parts : null;
67
+ }
68
+
69
+ const within = (root, p) => p === root || p.startsWith(root + path.sep);
70
+
71
+ /** Does this command look like an installation at all? (Only used to explain why one was not accepted.) */
72
+ const looksLikeInstall = (command) => /(^|[\s;&|/])(npm\s+(install|i|add|ci)|pip3?\s+install|-m\s+pip\s+install)(\s|$)/.test(command);
73
+
74
+ function venvAt(dir, root) {
75
+ try {
76
+ const real = fs.realpathSync(dir);
77
+ return within(root, real) && fs.statSync(path.join(real, 'pyvenv.cfg')).isFile() ? real : null;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * @param {string} command
85
+ * @param {{ cwd: string, root: string }} where
86
+ * @returns {null | { reason: string } | { manager: 'npm'|'pip', dir: string, hosts: string[], args: string[], venv?: string, requirements?: string[] }}
87
+ * null: not an installation. { reason }: looks like one, but not in a form that may use the network.
88
+ */
89
+ function parse(command, { cwd, root }) {
90
+ if (!looksLikeInstall(command)) return null;
91
+ const no = (reason) => ({ reason });
92
+ const parts = words(command.trim());
93
+ if (!parts) return no('it combines the installation with other shell syntax');
94
+ const realRoot = fs.realpathSync(root);
95
+ let dir = fs.realpathSync(cwd);
96
+ let activated = null;
97
+ while (parts.length > 1) {
98
+ const [first, ...rest] = parts.shift();
99
+ if (first === 'cd' && rest.length === 1) {
100
+ try {
101
+ dir = fs.realpathSync(path.resolve(dir, rest[0]));
102
+ } catch {
103
+ return no('the folder to change into does not exist');
104
+ }
105
+ } else if ((first === 'source' || first === '.') && rest.length === 1 && /(^|\/)bin\/activate$/.test(rest[0])) {
106
+ activated = venvAt(path.resolve(dir, rest[0], '..', '..'), realRoot);
107
+ if (!activated) return no('the virtual environment must be inside the project');
108
+ } else return no('only "cd <folder>" or activating a virtual environment may come before the installation');
109
+ }
110
+ if (!within(realRoot, dir)) return no('it installs outside the project');
111
+ const [program, ...args] = parts[0];
112
+
113
+ if (program === 'npm') {
114
+ const [verb, ...rest] = args;
115
+ if (!['install', 'i', 'add', 'ci'].includes(verb)) return no('the npm command must start with "npm install" or "npm ci"');
116
+ for (const a of rest) {
117
+ if (a.startsWith('-') ? !NPM_FLAGS.has(a) : !NPM_SPEC.test(a) || verb === 'ci') return no(`"${a.slice(0, 60)}" is not allowed (only package names from the npm registry and common save flags)`);
118
+ }
119
+ return { manager: 'npm', dir, hosts: [...HOSTS.npm], args: [verb === 'ci' ? 'ci' : 'install', ...rest] };
120
+ }
121
+
122
+ let venv = null;
123
+ let rest = null;
124
+ const base = path.basename(program);
125
+ if (/^pip(3(\.\d+)?)?$/.test(base)) {
126
+ venv = program.includes('/') ? venvAt(path.resolve(dir, program, '..', '..'), realRoot) : activated;
127
+ rest = args;
128
+ } else if (/^python(3(\.\d+)?)?$/.test(base) && args[0] === '-m' && args[1] === 'pip') {
129
+ venv = program.includes('/') ? venvAt(path.resolve(dir, program, '..', '..'), realRoot) : activated;
130
+ rest = args.slice(2);
131
+ } else return no('only npm and pip installations are supported');
132
+ if (!venv) return no('Python packages are installed into a virtual environment inside the project: run "python3 -m venv .venv" and then ".venv/bin/pip install <names>"');
133
+ if (rest[0] !== 'install') return no('the pip command must be "pip install"');
134
+ const specs = [];
135
+ const flags = [];
136
+ const requirements = [];
137
+ for (let i = 1; i < rest.length; i++) {
138
+ const a = rest[i];
139
+ if (a === '-r' || a === '--requirement') {
140
+ const file = rest[++i];
141
+ let lines;
142
+ try {
143
+ const real = fs.realpathSync(path.resolve(dir, file));
144
+ if (!within(realRoot, real) || fs.statSync(real).size > 256 * 1024) throw new Error('outside');
145
+ lines = fs.readFileSync(real, 'utf8').split(/\r?\n/);
146
+ } catch {
147
+ return no('the requirements file must be a file inside the project');
148
+ }
149
+ for (const line of lines) {
150
+ const spec = line.replace(/(^|\s)#.*$/, '').trim();
151
+ if (!spec) continue;
152
+ if (!PIP_SPEC.test(spec)) return no(`the requirements line "${spec.slice(0, 60)}" is not a plain package from PyPI`);
153
+ specs.push(spec);
154
+ }
155
+ requirements.push(file);
156
+ } else if (a.startsWith('-')) {
157
+ if (!PIP_FLAGS.has(a)) return no(`the option "${a.slice(0, 40)}" is not allowed`);
158
+ flags.push(a);
159
+ } else if (PIP_SPEC.test(a)) specs.push(a);
160
+ else return no(`"${a.slice(0, 60)}" is not a plain package from PyPI`);
161
+ }
162
+ if (!specs.length) return no('no packages were named');
163
+ return { manager: 'pip', dir, hosts: [...HOSTS.pip], args: [...flags, ...specs], specs, flags, venv, requirements };
164
+ }
165
+
166
+ // ---------------------------------------------------------------------------
167
+ // The tools that run while the network is open: never anything from the project
168
+ // ---------------------------------------------------------------------------
169
+
170
+ /** PATH without relative entries and without folders inside the project. */
171
+ function trustedPath(root, value = process.env.PATH || '') {
172
+ const realRoot = fs.realpathSync(root);
173
+ return value
174
+ .split(path.delimiter)
175
+ .filter((d) => {
176
+ if (!path.isAbsolute(d)) return false;
177
+ try {
178
+ return !within(realRoot, fs.realpathSync(d));
179
+ } catch {
180
+ return false;
181
+ }
182
+ })
183
+ .join(path.delimiter);
184
+ }
185
+
186
+ function onPath(name, searchPath, root) {
187
+ const realRoot = fs.realpathSync(root);
188
+ for (const d of searchPath.split(path.delimiter)) {
189
+ try {
190
+ const full = path.join(d, name);
191
+ fs.accessSync(full, fs.constants.X_OK);
192
+ if (!within(realRoot, fs.realpathSync(full))) return full;
193
+ } catch {
194
+ /* next */
195
+ }
196
+ }
197
+ return null;
198
+ }
199
+
200
+ /** A system Python of the same version as the environment, and how to start its pip. */
201
+ function systemPip(venv, searchPath, root) {
202
+ let wanted = null;
203
+ try {
204
+ wanted = fs.readdirSync(path.join(venv, 'lib')).map((n) => /^python(\d+\.\d+)$/.exec(n)).filter(Boolean).map((m) => m[1])[0] || null;
205
+ } catch {
206
+ /* judged below */
207
+ }
208
+ for (const name of [wanted && `python${wanted}`, 'python3'].filter(Boolean)) {
209
+ const python = onPath(name, searchPath, root);
210
+ if (!python) continue;
211
+ const probe = (args) => spawnSync(python, ['-I', ...args], { encoding: 'utf8', timeout: 20_000, cwd: '/', env: { PATH: searchPath } });
212
+ const v = probe(['-c', 'import sys;print("%d.%d"%sys.version_info[:2])']);
213
+ if (v.status !== 0 || (wanted && v.stdout.trim() !== wanted)) continue;
214
+ if (probe(['-m', 'pip', '--version']).status === 0) return { argv: [python, '-I', '-m', 'pip'] };
215
+ // (Debian and Ubuntu ship pip only as a wheel next to venv support)
216
+ const wheel = probe(['-c', 'import ensurepip,glob,os;d=[os.path.join(os.path.dirname(ensurepip.__file__),"_bundled"),"/usr/share/python-wheels"];print(next(w for x in d for w in glob.glob(os.path.join(x,"pip-*.whl"))))']);
217
+ if (wheel.status === 0) return { argv: [python, '-I', path.join(wheel.stdout.trim(), 'pip')] };
218
+ }
219
+ return null;
220
+ }
221
+
222
+ /**
223
+ * The two steps of an installation.
224
+ * @returns {{ reason: string } | { online: { command: string, env: object }, offline: { command: string, env: object }|null, needsOffline: () => boolean, cleanup: () => void }}
225
+ */
226
+ function steps(plan, { root, proxyUrl }) {
227
+ const searchPath = trustedPath(root);
228
+ const proxy = { HTTPS_PROXY: proxyUrl, https_proxy: proxyUrl, HTTP_PROXY: proxyUrl, http_proxy: proxyUrl, NO_PROXY: '', no_proxy: '' };
229
+ const line = (argv) => argv.map(shellQuote).join(' ');
230
+ const at = `cd ${shellQuote(plan.dir)} && `;
231
+ if (plan.manager === 'npm') {
232
+ const npm = onPath('npm', searchPath, root);
233
+ if (!npm) return { reason: 'npm was not found outside the project' };
234
+ // Command-line settings win over the project's .npmrc.
235
+ const forced = [`--registry=${NPM_REGISTRY}`, '--ignore-scripts=true', '--git=/bin/false', '--strict-ssl=true', '--userconfig=/dev/null', '--no-audit', '--no-fund', '--no-update-notifier'];
236
+ const needsOffline = () => {
237
+ const lock = readJson(path.join(plan.dir, 'node_modules', '.package-lock.json'));
238
+ const pkg = readJson(path.join(plan.dir, 'package.json'));
239
+ return Object.values((lock && lock.packages) || {}).some((p) => p.hasInstallScript) || ['preinstall', 'install', 'postinstall', 'prepare'].some((s) => pkg && pkg.scripts && pkg.scripts[s]);
240
+ };
241
+ return {
242
+ online: { command: `${at}${line([npm, ...plan.args, ...forced])} --globalconfig="$TMPDIR/no-global-npmrc" --cache="$TMPDIR/npm-cache"`, env: { PATH: searchPath, ...proxy, npm_config_proxy: proxyUrl, npm_config_https_proxy: proxyUrl, npm_config_noproxy: '' } },
243
+ offline: { command: `${at}npm rebuild --no-audit --no-fund --no-update-notifier`, env: {} },
244
+ needsOffline,
245
+ cleanup: () => {},
246
+ };
247
+ }
248
+ const pip = systemPip(plan.venv, searchPath, root);
249
+ if (!pip) return { reason: 'no system Python with pip matches the virtual environment (install python3-pip / python3-venv)' };
250
+ const wheels = path.join(plan.dir, `.kq-wheels-${process.pid}-${Date.now().toString(36)}`);
251
+ const quiet = ['--disable-pip-version-check', '--no-input'];
252
+ return {
253
+ online: {
254
+ // (from "/", not the project: nothing in the project can be picked up by Python while the network is open)
255
+ command: `cd / && ${line([...pip.argv, '--isolated', 'download', ...quiet, '--no-cache-dir', '--only-binary=:all:', `--index-url=${PYPI_INDEX}`, '-d', wheels, ...plan.specs])}`,
256
+ env: { PATH: searchPath, ...proxy, PIP_CONFIG_FILE: '/dev/null' },
257
+ },
258
+ offline: {
259
+ command: `${at}${line([path.join(plan.venv, 'bin', 'python'), '-m', 'pip', 'install', ...quiet, '--no-index', '--find-links', wheels, '--only-binary=:all:', ...plan.args])}`,
260
+ env: { PIP_CONFIG_FILE: '/dev/null' },
261
+ },
262
+ needsOffline: () => true,
263
+ cleanup: () => fs.rmSync(wheels, { recursive: true, force: true }),
264
+ };
265
+ }
266
+
267
+ function readJson(file) {
268
+ try {
269
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
270
+ } catch {
271
+ return null;
272
+ }
273
+ }
274
+
275
+ module.exports = { HOSTS, parse, steps, words, looksLikeInstall, trustedPath };
package/lib/realtime.js CHANGED
@@ -11,6 +11,8 @@
11
11
  * reconnect, because the server forgets subscriptions when a socket drops.
12
12
  * - Routes chat:thinking / chat:delta / chat:completed / chat:failed to the
13
13
  * watcher registered for that requestRunId.
14
+ * - Remembers the sequence numbers of the tool_call steps announced by chat:step, and sends events that are
15
+ * acknowledged (chat:approval).
14
16
  *
15
17
  * Events can arrive before POST /messages has returned the requestRunId, so
16
18
  * events for runs nobody is watching yet are buffered and replayed by watch().
@@ -26,6 +28,8 @@ const CONNECT_TIMEOUT_MS = 8000;
26
28
  const SUBSCRIBE_ACK_TIMEOUT_MS = 5000;
27
29
  const MAX_BUFFERED_EVENTS = 5000;
28
30
  const MAX_FINISHED_RUNS = 200; // remembered so late events for them are dropped, not buffered
31
+ const MAX_STEP_RUNS = 50;
32
+ const MAX_STEPS_PER_RUN = 300;
29
33
  const RUN_EVENTS = ['chat:thinking', 'chat:delta', 'chat:completed', 'chat:failed'];
30
34
 
31
35
  class Realtime {
@@ -45,6 +49,7 @@ class Realtime {
45
49
  this.bufferedCount = 0;
46
50
  this.finished = new Set(); // runs whose watcher has stopped
47
51
  this.subscription = null; // { socketId, chatId, promise }: one subscribe per connection and chat
52
+ this.steps = new Map(); // requestRunId -> Map(seq -> tool name) of its tool_call steps
48
53
  }
49
54
 
50
55
  get connected() {
@@ -95,6 +100,7 @@ class Realtime {
95
100
  for (const event of RUN_EVENTS) {
96
101
  this.socket.on(event, (payload) => this._dispatch(event, payload));
97
102
  }
103
+ this.socket.on('chat:step', (payload) => this._noteStep(payload));
98
104
  return this._waitForConnect();
99
105
  }
100
106
 
@@ -170,6 +176,46 @@ class Realtime {
170
176
  });
171
177
  }
172
178
 
179
+ /**
180
+ * Keep what identifies a tool call from a chat:step event. The approval contract names the step ("tool_call", its
181
+ * `seq`); the envelope is not specified, so the step is read from the payload itself or from payload.step, and anything
182
+ * else is ignored.
183
+ */
184
+ _noteStep(payload) {
185
+ if (!payload || typeof payload !== 'object') return;
186
+ const step = payload.step && typeof payload.step === 'object' ? payload.step : payload;
187
+ const run = payload.requestRunId ?? step.requestRunId;
188
+ if ((typeof run !== 'string' && typeof run !== 'number') || run === '') return;
189
+ if (step.type !== 'tool_call' || !Number.isSafeInteger(step.seq) || typeof step.tool !== 'string') return;
190
+ const runId = String(run);
191
+ let steps = this.steps.get(runId);
192
+ if (!steps) {
193
+ steps = new Map();
194
+ this.steps.set(runId, steps);
195
+ if (this.steps.size > MAX_STEP_RUNS) this.steps.delete(this.steps.keys().next().value);
196
+ }
197
+ if (steps.size < MAX_STEPS_PER_RUN) steps.set(step.seq, step.tool);
198
+ }
199
+
200
+ /** The tool_call steps announced for a run, in order: [{ seq, tool }]. */
201
+ toolCallSteps(requestRunId) {
202
+ return [...(this.steps.get(String(requestRunId)) || [])].map(([seq, tool]) => ({ seq, tool })).sort((a, b) => a.seq - b.seq);
203
+ }
204
+
205
+ /** Emit an event and wait for its acknowledgement; null if there is none in time (or no connection). */
206
+ emitWithAck(event, payload, timeoutMs = this.ackTimeoutMs) {
207
+ const socket = this.socket;
208
+ if (!socket || !socket.connected) return Promise.resolve(null);
209
+ return new Promise((resolve) => {
210
+ const timer = setTimeout(() => resolve(null), timeoutMs);
211
+ timer.unref(); // waiting for an acknowledgement never keeps the CLI running
212
+ socket.emit(event, payload, (ack) => {
213
+ clearTimeout(timer);
214
+ resolve(ack === undefined ? null : ack);
215
+ });
216
+ });
217
+ }
218
+
173
219
  /**
174
220
  * Route one server event to its run. Events without a usable run id are
175
221
  * dropped (logged in debug mode); events for runs that already finished are
@@ -233,6 +279,7 @@ class Realtime {
233
279
  this.connecting = null;
234
280
  this.subscription = null;
235
281
  this.watchers.clear();
282
+ this.steps.clear();
236
283
  this.clearBuffer();
237
284
  }
238
285
  }
@@ -0,0 +1,243 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * lib/sandbox-net.js
5
+ * -----------------------------------------------------------------------------
6
+ * The "this computer only" network of the sandbox (Phase 3.20). External networking is not touched here: it stays off.
7
+ *
8
+ * Linux (bubblewrap): every sandbox has no route to anywhere. Commands share ONE private network namespace per CLI
9
+ * process, held open by a small bwrap process, so a server started by one command can be reached by the next. Only
10
+ * the loopback interface exists in it: services of the host, other machines and metadata addresses are unreachable,
11
+ * and "0.0.0.0" there means "this private namespace". Where the namespace cannot be joined, each command keeps its
12
+ * own (localhost then works only inside one command).
13
+ *
14
+ * macOS (seatbelt): the system sandbox has no private network and cannot limit LISTENING to the loopback address (its
15
+ * "localhost" rules also match 0.0.0.0, :: and the machine's LAN address). Local networking is therefore off until a
16
+ * person allows it, and then:
17
+ * - connections are allowed to this computer only, TCP only;
18
+ * - ports that something outside the sandbox was already listening on are denied (checked to work at run time);
19
+ * - a watchdog stops a command whose processes listen on anything but a loopback address. This reacts after the
20
+ * fact (a fraction of a second): it is a safeguard, not a kernel guarantee.
21
+ */
22
+
23
+ const fs = require('fs');
24
+ const os = require('os');
25
+ const net = require('net');
26
+ const path = require('path');
27
+ const { spawn, execFile } = require('child_process');
28
+
29
+ const LSOF = '/usr/sbin/lsof';
30
+ const NETSTAT = '/usr/sbin/netstat';
31
+ const WATCH_INTERVAL_MS = 150;
32
+
33
+ const run = (file, args, timeout = 5000) =>
34
+ new Promise((resolve) => execFile(file, args, { encoding: 'utf8', timeout, maxBuffer: 16 * 1024 * 1024 }, (err, stdout) => resolve({ ok: !err, stdout: stdout || '' })));
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // Linux: a network namespace of our own
38
+ // ---------------------------------------------------------------------------
39
+
40
+ function findNsenter() {
41
+ return ['/usr/bin/nsenter', '/bin/nsenter', '/usr/local/bin/nsenter'].find((p) => fs.existsSync(p)) || null;
42
+ }
43
+
44
+ /**
45
+ * Create a private network namespace (loopback only) and keep it until stop() or until this process ends.
46
+ * @param {string} bwrap path of the bubblewrap binary
47
+ * @returns {Promise<{ enter: (args: string[]) => { file: string, args: string[] }, bwrapArgs: string[], stop: () => void } | null>}
48
+ */
49
+ async function createNamespace(bwrap) {
50
+ const nsenter = findNsenter();
51
+ if (!nsenter) return null;
52
+ let holder;
53
+ try {
54
+ // (--uid 0 inside: older bubblewrap would otherwise add a second user namespace that cannot be joined from outside)
55
+ holder = spawn(
56
+ bwrap,
57
+ ['--unshare-user', '--uid', '0', '--gid', '0', '--unshare-net', '--unshare-pid', '--die-with-parent', '--ro-bind', '/', '/', '--proc', '/proc', '--info-fd', '3', '--', '/bin/sh', '-c', 'exec sleep 2147483647'],
58
+ { stdio: ['ignore', 'ignore', 'ignore', 'pipe'] },
59
+ );
60
+ } catch {
61
+ return null;
62
+ }
63
+ const stop = () => {
64
+ process.removeListener('exit', stop);
65
+ holder.kill('SIGKILL');
66
+ };
67
+ process.once('exit', stop);
68
+ const pid = await new Promise((resolve) => {
69
+ let info = '';
70
+ const timer = setTimeout(() => resolve(null), 5000);
71
+ const done = (v) => {
72
+ clearTimeout(timer);
73
+ resolve(v);
74
+ };
75
+ holder.stdio[3].on('data', (d) => {
76
+ info += d;
77
+ const m = /"child-pid"\s*:\s*(\d+)/.exec(info);
78
+ if (m) done(Number(m[1]));
79
+ });
80
+ holder.once('error', () => done(null));
81
+ holder.once('exit', () => done(null));
82
+ });
83
+ const enter = (args) => ({ file: nsenter, args: ['-t', String(pid), '-U', '-n', '--preserve-credentials', '--', ...args] });
84
+ // Inside the namespace's user namespace we appear as uid 0: bubblewrap maps the command back to the real user.
85
+ const bwrapArgs = ['--unshare-user', '--uid', String(process.getuid()), '--gid', String(process.getgid())];
86
+ if (pid) {
87
+ // (the namespace is ready a moment after its process id is known)
88
+ for (let attempt = 0; attempt < 20; attempt++) {
89
+ const trial = enter([bwrap, ...bwrapArgs, '--die-with-parent', '--ro-bind', '/', '/', '--proc', '/proc', '--', '/bin/true']);
90
+ if ((await run(trial.file, trial.args)).ok) {
91
+ holder.unref();
92
+ if (holder.stdio[3]) holder.stdio[3].destroy();
93
+ return { enter, bwrapArgs, stop };
94
+ }
95
+ await new Promise((r) => setTimeout(r, 50));
96
+ }
97
+ }
98
+ stop();
99
+ return null;
100
+ }
101
+
102
+ let shared = null;
103
+ /** The namespace this CLI process's commands share (created on first use); null where that is not possible. */
104
+ function sharedNamespace(bwrap) {
105
+ if (!shared) shared = createNamespace(bwrap);
106
+ return shared;
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // macOS: which ports are taken, and the watchdog
111
+ // ---------------------------------------------------------------------------
112
+
113
+ /**
114
+ * Local networking on macOS is OFF: seatbelt cannot limit listening to the loopback interface (its "localhost" matches
115
+ * every address of the machine), and watching for a violation is not isolation. The implementation is kept; there is
116
+ * deliberately no setting that turns it on. (Linux gives commands a private network and is not affected.)
117
+ */
118
+ const MAC_LOCAL_NETWORKING = false;
119
+
120
+ /** Every TCP port something is listening on (all users). null when it cannot be told: then local networking stays off. */
121
+ async function listeningPorts() {
122
+ const r = await run(NETSTAT, ['-an', '-p', 'tcp']);
123
+ if (!r.ok) return null;
124
+ const ports = new Set();
125
+ for (const line of r.stdout.split('\n')) {
126
+ const f = line.trim().split(/\s+/);
127
+ if (f[5] !== 'LISTEN') continue;
128
+ const port = Number(f[3].slice(f[3].lastIndexOf('.') + 1));
129
+ if (Number.isInteger(port) && port > 0) ports.add(port);
130
+ }
131
+ return ports;
132
+ }
133
+
134
+ /** [{ pid, address, port }] of the TCP listeners lsof can see (this user's processes). */
135
+ async function listeners() {
136
+ const r = await run(LSOF, ['-nP', '-iTCP', '-sTCP:LISTEN', '-Fpn']);
137
+ const out = [];
138
+ let pid = 0;
139
+ for (const line of r.stdout.split('\n')) {
140
+ if (line[0] === 'p') pid = Number(line.slice(1));
141
+ else if (line[0] === 'n') {
142
+ const at = line.lastIndexOf(':');
143
+ out.push({ pid, address: line.slice(1, at), port: Number(line.slice(at + 1)) });
144
+ }
145
+ }
146
+ return out;
147
+ }
148
+
149
+ const isLoopback = (address) => address === '[::1]' || /^127\./.test(address) || address === 'localhost';
150
+
151
+ /** Does process `pid` belong to the command with process group `pgid` and environment tag `tag`? */
152
+ async function belongs(pid, { pgid, tag }) {
153
+ const r = await run('/bin/ps', ['-E', '-ww', '-o', 'pgid=,command=', '-p', String(pid)]);
154
+ if (!r.ok) return false;
155
+ return Number(r.stdout.trim().split(/\s+/)[0]) === pgid || (Boolean(tag) && new RegExp(`(\\s|^)KORVENIQ_RUN_TAG=${tag}(\\s|$)`).test(r.stdout));
156
+ }
157
+
158
+ /**
159
+ * The ports to deny a command: everything already listening, except what earlier commands of this session listen on.
160
+ * @param {Array<{ pgid: number, tag: string }>} ours the session's running background commands
161
+ */
162
+ async function hostPorts(ours = []) {
163
+ const all = await listeningPorts();
164
+ if (!all) return null;
165
+ if (ours.length) {
166
+ for (const l of await listeners()) {
167
+ if (!all.has(l.port)) continue;
168
+ for (const command of ours) {
169
+ if (await belongs(l.pid, command)) {
170
+ all.delete(l.port);
171
+ break;
172
+ }
173
+ }
174
+ }
175
+ }
176
+ return [...all].sort((a, b) => a - b);
177
+ }
178
+
179
+ /**
180
+ * Watch a command that was allowed to listen: call onViolation({ pid, address, port }) once if any of its processes
181
+ * listens on something other than a loopback address. Returns the function that stops watching.
182
+ */
183
+ function watchListeners(command, onViolation, { intervalMs = WATCH_INTERVAL_MS } = {}) {
184
+ let stopped = false;
185
+ let timer = null;
186
+ const innocent = new Set(); // listeners that are not the command's
187
+ const tick = async () => {
188
+ try {
189
+ for (const l of await listeners()) {
190
+ if (stopped) return;
191
+ if (isLoopback(l.address)) continue;
192
+ const key = `${l.pid} ${l.address} ${l.port}`;
193
+ if (innocent.has(key)) continue;
194
+ if (await belongs(l.pid, command)) {
195
+ stopped = true;
196
+ onViolation(l);
197
+ return;
198
+ }
199
+ innocent.add(key);
200
+ }
201
+ } finally {
202
+ if (!stopped) {
203
+ timer = setTimeout(tick, intervalMs);
204
+ timer.unref();
205
+ }
206
+ }
207
+ };
208
+ tick();
209
+ return () => {
210
+ stopped = true;
211
+ clearTimeout(timer);
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Check on this machine that the profile rules really keep a sandbox away from a denied port while letting it reach
217
+ * another one. Local networking is not offered unless this holds.
218
+ */
219
+ async function verifyLocalRules(buildProfileFor) {
220
+ const servers = await Promise.all(
221
+ [0, 1].map(
222
+ () =>
223
+ new Promise((resolve) => {
224
+ const s = net.createServer((c) => c.destroy());
225
+ s.listen(0, '127.0.0.1', () => resolve(s));
226
+ }),
227
+ ),
228
+ );
229
+ try {
230
+ const [denied, open] = servers.map((s) => s.address().port);
231
+ const probe = `use IO::Socket::INET; sub c { IO::Socket::INET->new(PeerAddr => "127.0.0.1", PeerPort => $_[0], Timeout => 2) ? 1 : 0 } exit(!c(${denied}) && c(${open}) ? 0 : 1)`;
232
+ return (await run('/usr/bin/sandbox-exec', ['-p', buildProfileFor([denied]), '/usr/bin/perl', '-e', probe], 10_000)).ok;
233
+ } finally {
234
+ for (const s of servers) s.close();
235
+ }
236
+ }
237
+
238
+ /** A private folder for a unix socket (the Linux package proxy). */
239
+ function socketDir() {
240
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'kq-net-'));
241
+ }
242
+
243
+ module.exports = { MAC_LOCAL_NETWORKING, createNamespace, sharedNamespace, findNsenter, listeningPorts, listeners, hostPorts, watchListeners, verifyLocalRules, isLoopback, socketDir };