@infosupport/huddle-cli 0.0.0-experiment-160.121.1 → 0.0.0-experiment-147.123.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -14
- package/dist/index.js +31 -5
- package/dist/indexfolder.js +167 -0
- package/dist/init.js +5 -9
- package/dist/pipe/command.js +0 -1
- package/dist/pipe/protocol.js +7 -11
- package/dist/pipe/serve.js +4 -25
- package/package.json +1 -1
- package/dist/pipe/fs-list.js +0 -157
- package/dist/pipe/sbx-kit.js +0 -107
- package/dist/pipe/sbx-links.js +0 -147
- package/dist/pipe/tools.js +0 -227
package/README.md
CHANGED
|
@@ -44,25 +44,43 @@ huddle --ide vscode \
|
|
|
44
44
|
|
|
45
45
|
Default API URL: `http://localhost:3000`. Override it with `--url` or `HUDDLE_URL`.
|
|
46
46
|
|
|
47
|
-
##
|
|
47
|
+
## Making host folders selectable in the portal
|
|
48
48
|
|
|
49
|
-
Huddle's portal runs inside a container, so it cannot
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
49
|
+
Huddle's portal runs inside a container, so it cannot open a folder dialog on your
|
|
50
|
+
host: every host path had to be typed from memory. `huddle indexfolder` scans your
|
|
51
|
+
host once and stores what it finds, and every host-path field in the portal grows a
|
|
52
|
+
**Browse** button that opens those folders as a tree — starting a devcontainer, the
|
|
53
|
+
folder mappings, and the team-managed folders. Starting a devcontainer, Ctrl-click picks
|
|
54
|
+
several folders at once and each becomes its own worktree. Typing a path by hand keeps working:
|
|
55
|
+
the index is a snapshot, so a folder created after the last scan must not be
|
|
56
|
+
unreachable.
|
|
56
57
|
|
|
57
58
|
```bash
|
|
58
|
-
|
|
59
|
-
huddle
|
|
60
|
-
huddle
|
|
61
|
-
huddle
|
|
59
|
+
cd T:/projects
|
|
60
|
+
huddle indexfolder # this folder + 2 levels below it
|
|
61
|
+
huddle indexfolder T:/projects --depth 3
|
|
62
|
+
huddle indexfolder --all # also index node_modules, dist, target, ...
|
|
63
|
+
huddle indexfolder --replace # re-scan: drop the earlier entries under this folder first
|
|
64
|
+
huddle indexfolder --list # show what is indexed
|
|
65
|
+
huddle indexfolder --clear # empty the index (with a folder: only that subtree)
|
|
62
66
|
```
|
|
63
67
|
|
|
64
|
-
|
|
65
|
-
|
|
68
|
+
Hidden (dot) folders and the usual build folders (`node_modules`, `dist`, `target`,
|
|
69
|
+
`obj`, …) are skipped, which is what keeps a scan of a projects folder in the
|
|
70
|
+
hundreds instead of the tens of thousands; `--all` turns that off. The scan stops
|
|
71
|
+
at 1500 folders and the index holds at most 2000 — index a more specific folder if
|
|
72
|
+
you hit that.
|
|
73
|
+
|
|
74
|
+
The index is a **snapshot**, not a live view: the gateway cannot read your host, so
|
|
75
|
+
re-run the command after adding projects. Every input keeps accepting a typed path,
|
|
76
|
+
so a folder you created a minute ago works without re-indexing first. Windows paths
|
|
77
|
+
may be typed either way (`T:\projects\app` or `T:/projects/app`) — they are stored
|
|
78
|
+
in one canonical form, and the two spellings are the same entry.
|
|
79
|
+
|
|
80
|
+
Individual folders can also be added or removed under **Settings > Indexed
|
|
81
|
+
folders** in the portal. The index lives in Huddle's database, not in
|
|
82
|
+
`~/.huddle/config.json`: it describes this machine, so unlike the team-managed
|
|
83
|
+
settings it is not something to share in version control.
|
|
66
84
|
|
|
67
85
|
## Experiments
|
|
68
86
|
|
package/dist/index.js
CHANGED
|
@@ -12,14 +12,15 @@ const extension_1 = require("./extension");
|
|
|
12
12
|
const firewall_1 = require("./firewall");
|
|
13
13
|
const init_1 = require("./init");
|
|
14
14
|
const migrate_1 = require("./migrate");
|
|
15
|
+
const indexfolder_1 = require("./indexfolder");
|
|
15
16
|
const command_1 = require("./pipe/command");
|
|
16
17
|
const images_1 = require("./images");
|
|
17
18
|
const self_update_1 = require("./self-update");
|
|
18
19
|
const utils_1 = require("./utils");
|
|
19
20
|
const experiment_1 = require("./experiment");
|
|
20
|
-
const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'ca-path', 'output', 'out', 'workspace-root']);
|
|
21
|
-
const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force', 'replace']);
|
|
22
|
-
const COMMANDS = new Set(['start', 'firewall', 'fw', 'extension', 'ext', 'init', 'restart', 'experiment', 'migrate', 'pipe', 'help', 'version']);
|
|
21
|
+
const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'ca-path', 'output', 'out', 'workspace-root', 'depth']);
|
|
22
|
+
const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force', 'replace', 'all', 'list', 'clear']);
|
|
23
|
+
const COMMANDS = new Set(['start', 'firewall', 'fw', 'extension', 'ext', 'init', 'restart', 'experiment', 'migrate', 'indexfolder', 'indexfolders', 'pipe', 'help', 'version']);
|
|
23
24
|
function parseArgs(argv) {
|
|
24
25
|
const positional = [];
|
|
25
26
|
const flags = {};
|
|
@@ -124,8 +125,12 @@ Usage:
|
|
|
124
125
|
team firewall-rules folder)
|
|
125
126
|
huddle migrate [folder] Wire an existing docker-compose devcontainer
|
|
126
127
|
behind Huddle by generating an override file
|
|
128
|
+
huddle indexfolder [folder] Index the folders under this one so the portal
|
|
129
|
+
can offer them where a host path is needed
|
|
130
|
+
(the portal runs in a container and cannot
|
|
131
|
+
browse your host)
|
|
127
132
|
huddle pipe status Show whether the host pipe is online (lets the
|
|
128
|
-
portal
|
|
133
|
+
portal set up SSH for Connect IDE)
|
|
129
134
|
huddle pipe start|stop Start (or replace) / stop the host pipe in the
|
|
130
135
|
background (huddle init starts it for you)
|
|
131
136
|
huddle pipe serve Run the host pipe in the foreground (debugging)
|
|
@@ -184,6 +189,16 @@ Migrate options:
|
|
|
184
189
|
(default: docker-compose.huddle.yml next to the source)
|
|
185
190
|
--force Overwrite an existing override file
|
|
186
191
|
|
|
192
|
+
Indexfolder options:
|
|
193
|
+
--depth <n> How deep to walk (default: 2, max 8)
|
|
194
|
+
--all Also index build folders (node_modules, dist,
|
|
195
|
+
target, ...); hidden folders stay skipped
|
|
196
|
+
--replace Drop the earlier entries under this folder
|
|
197
|
+
first, instead of merging
|
|
198
|
+
--list Show the current index and exit
|
|
199
|
+
--clear Empty the index (or, with a folder, only the
|
|
200
|
+
entries under it)
|
|
201
|
+
|
|
187
202
|
Firewall options:
|
|
188
203
|
-i, --interactive Interactively approve/deny (list)
|
|
189
204
|
--container <name> Filter by (list) / scope to (add) a container
|
|
@@ -385,7 +400,18 @@ async function main() {
|
|
|
385
400
|
return;
|
|
386
401
|
}
|
|
387
402
|
if (cmd === 'pipe') {
|
|
388
|
-
await (0, command_1.runPipe)({ action:
|
|
403
|
+
await (0, command_1.runPipe)({ action: positional[1] });
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
if (cmd === 'indexfolder' || cmd === 'indexfolders') {
|
|
407
|
+
await (0, indexfolder_1.runIndexFolder)({
|
|
408
|
+
path: positional[1],
|
|
409
|
+
depth: flagString(flags, 'depth'),
|
|
410
|
+
all: flagBool(flags, 'all'),
|
|
411
|
+
replace: flagBool(flags, 'replace'),
|
|
412
|
+
clear: flagBool(flags, 'clear'),
|
|
413
|
+
list: flagBool(flags, 'list'),
|
|
414
|
+
});
|
|
389
415
|
return;
|
|
390
416
|
}
|
|
391
417
|
if (cmd === 'migrate') {
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.runIndexFolder = runIndexFolder;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const api_1 = require("./api");
|
|
10
|
+
const utils_1 = require("./utils");
|
|
11
|
+
// `huddle indexfolder` — make host folders selectable in the portal.
|
|
12
|
+
//
|
|
13
|
+
// The portal runs inside a container: it cannot open a file dialog on the host,
|
|
14
|
+
// so every host path had to be typed from memory. This command walks the host
|
|
15
|
+
// filesystem where the operator already is (their projects folder) and posts the
|
|
16
|
+
// folders it finds to the gateway, which stores them as an index. The portal then
|
|
17
|
+
// offers that index wherever a host path is needed.
|
|
18
|
+
//
|
|
19
|
+
// Deliberately a snapshot, not a live view: the gateway has no way to read the
|
|
20
|
+
// host filesystem, and re-running the command is cheap.
|
|
21
|
+
// Folders that are never a workspace choice but do contain thousands of
|
|
22
|
+
// subfolders. Skipping them is what keeps a scan of a projects folder in the
|
|
23
|
+
// hundreds rather than the tens of thousands. `--all` turns this off; hidden
|
|
24
|
+
// (dot) folders stay skipped either way.
|
|
25
|
+
const NOISE = new Set([
|
|
26
|
+
'node_modules', 'dist', 'build', 'out', 'bin', 'obj', 'target', 'vendor',
|
|
27
|
+
'venv', '__pycache__', 'coverage', 'packages', 'AppData', 'Library',
|
|
28
|
+
'$RECYCLE.BIN', 'System Volume Information', 'Windows', 'Program Files',
|
|
29
|
+
'Program Files (x86)', 'ProgramData',
|
|
30
|
+
]);
|
|
31
|
+
// Hard stop on discovery, well under the gateway's own cap. Pointing the command
|
|
32
|
+
// at a drive root should end in a clear warning, not a ten-minute walk.
|
|
33
|
+
const MAX_FOLDERS = 1500;
|
|
34
|
+
// Host paths travel to the gateway with forward slashes: `path.resolve` hands
|
|
35
|
+
// back `T:\projects\app` on Windows, and the whole stack (the portal, the index,
|
|
36
|
+
// the Docker mount translation) speaks the forward-slash form. The gateway
|
|
37
|
+
// normalizes again on ingest — this is only so what we PRINT matches what gets
|
|
38
|
+
// stored.
|
|
39
|
+
function toPosix(p) {
|
|
40
|
+
return p.replace(/\\/g, '/').replace(/^([a-z]):/, (_m, d) => `${d.toUpperCase()}:`);
|
|
41
|
+
}
|
|
42
|
+
function parseDepth(raw) {
|
|
43
|
+
if (raw === undefined)
|
|
44
|
+
return 2;
|
|
45
|
+
const n = Number(raw);
|
|
46
|
+
if (!Number.isInteger(n) || n < 0 || n > 8) {
|
|
47
|
+
throw new Error(`Invalid --depth "${raw}": use a whole number between 0 and 8.`);
|
|
48
|
+
}
|
|
49
|
+
return n;
|
|
50
|
+
}
|
|
51
|
+
// The folder to walk comes from argv, or from wherever the operator's shell is.
|
|
52
|
+
// Resolving it here — once, before anything touches the filesystem — is what lets
|
|
53
|
+
// the rest of the command treat "the root" as one absolute, `..`-free path: the
|
|
54
|
+
// walk below, the containment check, and the paths posted to the gateway all
|
|
55
|
+
// derive from this value.
|
|
56
|
+
function resolveScanRoot(raw) {
|
|
57
|
+
const input = raw ?? process.cwd();
|
|
58
|
+
// A null byte makes every fs call throw ERR_INVALID_ARG_VALUE with a stack
|
|
59
|
+
// trace; say what is wrong instead.
|
|
60
|
+
if (input.includes('\0'))
|
|
61
|
+
throw new Error('Invalid folder: the path contains a null byte.');
|
|
62
|
+
return path_1.default.resolve(input);
|
|
63
|
+
}
|
|
64
|
+
// Whether `candidate` is the root or sits underneath it.
|
|
65
|
+
function contains(root, candidate) {
|
|
66
|
+
const rel = path_1.default.relative(root, candidate);
|
|
67
|
+
return rel === '' || (!rel.startsWith('..') && !path_1.default.isAbsolute(rel));
|
|
68
|
+
}
|
|
69
|
+
// Breadth-first so a depth cut-off keeps the folders nearest the root — those are
|
|
70
|
+
// the ones an operator actually mounts. Symlinks are not followed: `isDirectory()`
|
|
71
|
+
// is false for a symlink entry, which also rules out a link loop.
|
|
72
|
+
function scan(root, depth, all) {
|
|
73
|
+
const folders = [root];
|
|
74
|
+
let level = [root];
|
|
75
|
+
for (let d = 0; d < depth; d++) {
|
|
76
|
+
const next = [];
|
|
77
|
+
for (const dir of level) {
|
|
78
|
+
let entries;
|
|
79
|
+
try {
|
|
80
|
+
entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
continue; // unreadable folder (permissions, a vanished dir) — skip it
|
|
84
|
+
}
|
|
85
|
+
for (const e of entries) {
|
|
86
|
+
if (!e.isDirectory())
|
|
87
|
+
continue;
|
|
88
|
+
if (e.name.startsWith('.'))
|
|
89
|
+
continue;
|
|
90
|
+
if (!all && NOISE.has(e.name))
|
|
91
|
+
continue;
|
|
92
|
+
const full = path_1.default.join(dir, e.name);
|
|
93
|
+
// Nothing outside the folder the operator named ever enters the index or
|
|
94
|
+
// gets opened by the next round of readdirSync. Entries come from
|
|
95
|
+
// readdirSync and symlinks are already skipped, so this should never
|
|
96
|
+
// fire — it is here so a scan can never walk out of its root by accident.
|
|
97
|
+
if (!contains(root, full))
|
|
98
|
+
continue;
|
|
99
|
+
folders.push(full);
|
|
100
|
+
next.push(full);
|
|
101
|
+
if (folders.length >= MAX_FOLDERS)
|
|
102
|
+
return { folders, truncated: true };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
level = next;
|
|
106
|
+
if (level.length === 0)
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
return { folders, truncated: false };
|
|
110
|
+
}
|
|
111
|
+
async function runIndexFolder(opts) {
|
|
112
|
+
if (opts.list) {
|
|
113
|
+
const res = await (0, api_1.get)('/api/indexed-folders');
|
|
114
|
+
if (res.folders.length === 0) {
|
|
115
|
+
console.log((0, utils_1.dim)('No folders indexed yet. Run `huddle indexfolder` in your projects folder.'));
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
(0, utils_1.printTable)(['ID', 'PATH', 'SOURCE'], res.folders.map((f) => [String(f.id), f.path, f.source]));
|
|
119
|
+
console.log((0, utils_1.dim)(`\n${res.folders.length} folder(s) indexed (max ${res.max}).`));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (opts.clear) {
|
|
123
|
+
// Scoped when a folder is given, so clearing one project's entries does not
|
|
124
|
+
// throw away everything else that was indexed.
|
|
125
|
+
const root = opts.path ? toPosix(resolveScanRoot(opts.path)) : undefined;
|
|
126
|
+
const query = root ? `?root=${encodeURIComponent(root)}` : '';
|
|
127
|
+
const res = await (0, api_1.del)(`/api/indexed-folders${query}`);
|
|
128
|
+
console.log((0, utils_1.green)(`[OK] Removed ${res.removed} folder(s) from the index${root ? ` under ${(0, utils_1.cyan)(root)}` : ''}.`));
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const depth = parseDepth(opts.depth);
|
|
132
|
+
const root = resolveScanRoot(opts.path);
|
|
133
|
+
let stat;
|
|
134
|
+
try {
|
|
135
|
+
stat = fs_1.default.statSync(root);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
throw new Error(`Folder does not exist: ${root}`);
|
|
139
|
+
}
|
|
140
|
+
if (!stat.isDirectory())
|
|
141
|
+
throw new Error(`Not a folder: ${root}`);
|
|
142
|
+
const posixRoot = toPosix(root);
|
|
143
|
+
console.log(`Indexing ${(0, utils_1.bold)(posixRoot)} ${(0, utils_1.dim)(`(depth ${depth}${opts.all ? ', including build folders' : ''})`)}`);
|
|
144
|
+
const { folders, truncated } = scan(root, depth, opts.all === true);
|
|
145
|
+
if (truncated) {
|
|
146
|
+
console.log((0, utils_1.yellow)(`[!] Stopped at ${MAX_FOLDERS} folders. Index a more specific folder, or lower --depth.`));
|
|
147
|
+
}
|
|
148
|
+
const res = await (0, api_1.post)('/api/indexed-folders', {
|
|
149
|
+
paths: folders.map(toPosix),
|
|
150
|
+
root: posixRoot,
|
|
151
|
+
replace: opts.replace === true,
|
|
152
|
+
});
|
|
153
|
+
if (res.removed)
|
|
154
|
+
console.log((0, utils_1.dim)(` Replaced: removed ${res.removed} earlier entr(y|ies) under this folder.`));
|
|
155
|
+
console.log((0, utils_1.green)(`[OK] ${res.added} added, ${res.updated} already known — ${res.total} folder(s) in the index.`));
|
|
156
|
+
if (res.skipped) {
|
|
157
|
+
console.log((0, utils_1.yellow)(`[!] ${res.skipped} folder(s) skipped (index limit ${res.max} reached, or a duplicate spelling).`));
|
|
158
|
+
}
|
|
159
|
+
for (const bad of res.invalid.slice(0, 5)) {
|
|
160
|
+
console.log((0, utils_1.yellow)(`[!] Refused ${bad.path}: ${bad.error}`));
|
|
161
|
+
}
|
|
162
|
+
if (res.invalid.length > 5)
|
|
163
|
+
console.log((0, utils_1.yellow)(`[!] ...and ${res.invalid.length - 5} more refused.`));
|
|
164
|
+
console.log();
|
|
165
|
+
console.log('Pick these folders in the portal when starting a devcontainer,');
|
|
166
|
+
console.log(`or manage the index under ${(0, utils_1.cyan)('Settings > Indexed folders')}.`);
|
|
167
|
+
}
|
package/dist/init.js
CHANGED
|
@@ -13,9 +13,9 @@ const images_1 = require("./images");
|
|
|
13
13
|
const config_1 = require("./config");
|
|
14
14
|
const os_1 = __importDefault(require("os"));
|
|
15
15
|
const host_logs_1 = require("./host-logs");
|
|
16
|
+
const fs_1 = __importDefault(require("fs"));
|
|
16
17
|
const protocol_1 = require("./pipe/protocol");
|
|
17
18
|
const command_1 = require("./pipe/command");
|
|
18
|
-
const fs_1 = __importDefault(require("fs"));
|
|
19
19
|
exports.CONTAINER = 'huddle';
|
|
20
20
|
const VOLUME = 'huddle-data';
|
|
21
21
|
/**
|
|
@@ -39,9 +39,6 @@ const HOST_PORT = process.env.HUDDLE_PORT ?? '3000';
|
|
|
39
39
|
* gateway/src/ssh-access.ts.
|
|
40
40
|
*/
|
|
41
41
|
exports.SSH_RELAY_PORTS = '2200-2219';
|
|
42
|
-
// Host port of the gateway's sbx egress proxy (docs/host-pipe.md). Published on
|
|
43
|
-
// loopback only: the sbx daemon runs on this machine, nothing else needs it.
|
|
44
|
-
const SBX_PROXY_HOST_PORT = process.env.HUDDLE_SBX_PROXY_PORT ?? '32768';
|
|
45
42
|
// Run a binary with an argv array — NO shell. Values that originate from config
|
|
46
43
|
// (team-folder paths, which are writable via `huddle firewall folder set` and the
|
|
47
44
|
// authenticated settings API) must never be interpolated into a shell string, or
|
|
@@ -191,13 +188,12 @@ async function runInit(opts, images) {
|
|
|
191
188
|
dockerArgs.push('-e', `HUDDLE_OPERATOR_TOKEN=${operatorToken}`);
|
|
192
189
|
dockerArgs.push('-p', `${HOST_PORT}:3000`);
|
|
193
190
|
dockerArgs.push('-p', `127.0.0.1:${exports.SSH_RELAY_PORTS}:${exports.SSH_RELAY_PORTS}`);
|
|
194
|
-
dockerArgs.push('-p', `127.0.0.1:${SBX_PROXY_HOST_PORT}:3128`, '-e', `HUDDLE_SBX_PROXY_HOST_PORT=${SBX_PROXY_HOST_PORT}`);
|
|
195
191
|
dockerArgs.push('-v', `${VOLUME}:/data`);
|
|
196
192
|
dockerArgs.push('-v', `${runtime.socketPath}:/var/run/docker.sock`);
|
|
197
193
|
dockerArgs.push('-v', `${hostTmpSockets}:/tmp/dc-sockets`);
|
|
198
194
|
dockerArgs.push('-v', `${config_1.CONFIG_DIR}:/huddle-home:rw`, '-e', 'HUDDLE_HOME_DIR=/huddle-home');
|
|
199
195
|
// Its host path, so the gateway can refuse mounts that would expose it (the
|
|
200
|
-
// operator token in config.json, the host pipe) to a devcontainer
|
|
196
|
+
// operator token in config.json, the host pipe, Huddle's SSH key) to a devcontainer.
|
|
201
197
|
dockerArgs.push('-e', `HUDDLE_HOST_HOME_DIR=${config_1.CONFIG_DIR}`);
|
|
202
198
|
if (fwFolder)
|
|
203
199
|
dockerArgs.push('-v', `${fwFolder}:/firewall-rules:rw`);
|
|
@@ -220,9 +216,9 @@ async function runInit(opts, images) {
|
|
|
220
216
|
// gateway cleans that up itself (see dns-egress.ts / the startup sanitize in
|
|
221
217
|
// index.ts).
|
|
222
218
|
runArgsSilent(rt, ['network', 'connect', exports.INTERNAL_NET, exports.CONTAINER]);
|
|
223
|
-
// The host pipe
|
|
224
|
-
//
|
|
225
|
-
//
|
|
219
|
+
// The host pipe sets up SSH on the host for Connect IDE (docs/host-pipe.md).
|
|
220
|
+
// Restarting it here means it always runs the CLI that was just installed.
|
|
221
|
+
// It is an extra, so a failure only warns.
|
|
226
222
|
const pipe = await (0, command_1.startPipeAgent)();
|
|
227
223
|
if (pipe.ok) {
|
|
228
224
|
console.log((0, utils_1.dim)(`Host pipe: running (pid ${pipe.pid})`));
|
package/dist/pipe/command.js
CHANGED
|
@@ -146,7 +146,6 @@ function runStatus() {
|
|
|
146
146
|
const hb = (0, protocol_1.readHeartbeat)();
|
|
147
147
|
if (hb && (0, protocol_1.heartbeatFresh)(hb)) {
|
|
148
148
|
console.log(`${(0, utils_1.green)('Host pipe: online')} ${(0, utils_1.dim)(`(pid ${hb.pid}, CLI ${hb.version}, ${hb.platform})`)}`);
|
|
149
|
-
console.log((0, utils_1.dim)(` tools: ${hb.tools.length ? hb.tools.join(', ') : 'none installed'}`));
|
|
150
149
|
console.log((0, utils_1.dim)(` started: ${hb.startedAt} · heartbeat ${ago(hb.updatedAt)}`));
|
|
151
150
|
}
|
|
152
151
|
else {
|
package/dist/pipe/protocol.js
CHANGED
|
@@ -8,7 +8,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
8
8
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
9
9
|
};
|
|
10
10
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
-
exports.PipeError = exports.
|
|
11
|
+
exports.PipeError = exports.STALE_FILE_MS = exports.HEARTBEAT_STALE_MS = exports.HEARTBEAT_MS = exports.POLL_MS = exports.LOG_FILE = exports.HEARTBEAT_FILE = exports.PIPE_DIR = exports.PROTOCOL_VERSION = void 0;
|
|
12
12
|
exports.ensurePrivateDir = ensurePrivateDir;
|
|
13
13
|
exports.writeJsonAtomic = writeJsonAtomic;
|
|
14
14
|
exports.readHeartbeat = readHeartbeat;
|
|
@@ -27,10 +27,6 @@ exports.HEARTBEAT_MS = 2000;
|
|
|
27
27
|
exports.HEARTBEAT_STALE_MS = 10_000;
|
|
28
28
|
/** Leftover request/reply files older than this are deleted on start. */
|
|
29
29
|
exports.STALE_FILE_MS = 60 * 60 * 1000;
|
|
30
|
-
exports.MAX_FOLDER_ENTRIES = 2000;
|
|
31
|
-
exports.MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
|
32
|
-
exports.DEFAULT_TOOL_TIMEOUT_MS = 30_000;
|
|
33
|
-
exports.MAX_TOOL_TIMEOUT_MS = 15 * 60 * 1000;
|
|
34
30
|
/** Thrown by an op handler to answer with `ok:false` and a specific code. */
|
|
35
31
|
class PipeError extends Error {
|
|
36
32
|
code;
|
|
@@ -40,14 +36,9 @@ class PipeError extends Error {
|
|
|
40
36
|
}
|
|
41
37
|
}
|
|
42
38
|
exports.PipeError = PipeError;
|
|
43
|
-
/**
|
|
44
|
-
* Writes JSON to `<file>.tmp` and renames it over `<file>`, so the other side
|
|
45
|
-
* never reads a half-written file. Rename within one folder is atomic on every
|
|
46
|
-
* platform, including across the Docker bind mount.
|
|
47
|
-
*/
|
|
48
39
|
/**
|
|
49
40
|
* Creates the pipe folder owner-only, or makes an existing one so. Whoever can
|
|
50
|
-
* write a request into it can
|
|
41
|
+
* write a request into it can make the agent set up SSH, so on POSIX it
|
|
51
42
|
* must be ours (not a symlink) and closed to everyone else, and its parent must
|
|
52
43
|
* not let anyone else swap it out. Throws when that cannot be made true. On
|
|
53
44
|
* Windows a folder under the user profile is private already.
|
|
@@ -77,6 +68,11 @@ function ensurePrivateDir(dir) {
|
|
|
77
68
|
if ((fs_1.default.statSync(dir).mode & 0o777) !== 0o700)
|
|
78
69
|
fs_1.default.chmodSync(dir, 0o700);
|
|
79
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Writes JSON to `<file>.tmp` and renames it over `<file>`, so the other side
|
|
73
|
+
* never reads a half-written file. Rename within one folder is atomic on every
|
|
74
|
+
* platform, including across the Docker bind mount.
|
|
75
|
+
*/
|
|
80
76
|
function writeJsonAtomic(file, data) {
|
|
81
77
|
const tmp = `${file}.tmp`;
|
|
82
78
|
fs_1.default.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600 });
|
package/dist/pipe/serve.js
CHANGED
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
// ── Host pipe: the agent's serve loop ─────────────────────────────────────────
|
|
3
3
|
// Polls the pipe folder for `<id>.in`, claims each by renaming it to
|
|
4
4
|
// `<id>.busy` (so it is handled exactly once, even if two agents race), runs it
|
|
5
|
-
// without blocking the loop
|
|
6
|
-
// listing), writes `<id>.out` atomically and deletes the `.busy`. Every request
|
|
5
|
+
// without blocking the loop, writes `<id>.out` atomically and deletes the `.busy`. Every request
|
|
7
6
|
// gets a reply, a malformed one included; nothing a request contains can crash
|
|
8
7
|
// the loop. See docs/host-pipe.md for the protocol.
|
|
9
8
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
@@ -13,37 +12,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
13
12
|
exports.cleanStale = cleanStale;
|
|
14
13
|
exports.servePipe = servePipe;
|
|
15
14
|
const fs_1 = __importDefault(require("fs"));
|
|
16
|
-
const os_1 = __importDefault(require("os"));
|
|
17
15
|
const path_1 = __importDefault(require("path"));
|
|
18
16
|
const self_update_1 = require("../self-update");
|
|
19
17
|
const protocol_1 = require("./protocol");
|
|
20
|
-
const fs_list_1 = require("./fs-list");
|
|
21
|
-
const tools_1 = require("./tools");
|
|
22
|
-
const sbx_kit_1 = require("./sbx-kit");
|
|
23
|
-
const sbx_links_1 = require("./sbx-links");
|
|
24
18
|
const ssh_hosts_1 = require("./ssh-hosts");
|
|
25
19
|
// Ids are generated by the gateway (32 hex); anything that does not look like
|
|
26
20
|
// an id is not ours and is left alone rather than turned into a reply path.
|
|
27
21
|
const REQUEST_RE = /^([A-Za-z0-9_-]{1,128})\.in$/;
|
|
28
22
|
const LEFTOVER_RE = /\.(in|busy|out|tmp)$/;
|
|
29
|
-
async function dispatch(req
|
|
23
|
+
async function dispatch(req) {
|
|
30
24
|
const args = req.args ?? {};
|
|
31
25
|
switch (req.op) {
|
|
32
26
|
case 'host.info':
|
|
33
|
-
return {
|
|
34
|
-
platform: process.platform,
|
|
35
|
-
version: (0, self_update_1.cliVersion)(),
|
|
36
|
-
home: (0, fs_list_1.toHuddlePath)(os_1.default.homedir()),
|
|
37
|
-
tools: await (0, tools_1.toolsInfo)(),
|
|
38
|
-
};
|
|
39
|
-
case 'fs.list':
|
|
40
|
-
return (0, fs_list_1.fsList)(args, maxEntries);
|
|
41
|
-
case 'tool.run':
|
|
42
|
-
return (0, tools_1.toolRun)(args);
|
|
43
|
-
case 'sbx.links':
|
|
44
|
-
return (0, sbx_links_1.sbxLinks)(args);
|
|
45
|
-
case 'sbx.kit':
|
|
46
|
-
return (0, sbx_kit_1.sbxKit)(args);
|
|
27
|
+
return { platform: process.platform, version: (0, self_update_1.cliVersion)() };
|
|
47
28
|
case 'ssh.key':
|
|
48
29
|
return (0, ssh_hosts_1.sshKey)(args);
|
|
49
30
|
case 'ssh.host':
|
|
@@ -98,7 +79,6 @@ function cleanStale(dir, inFlight = new Set(), now = Date.now()) {
|
|
|
98
79
|
}
|
|
99
80
|
function servePipe(opts) {
|
|
100
81
|
const { dir } = opts;
|
|
101
|
-
const maxEntries = opts.maxEntries ?? protocol_1.MAX_FOLDER_ENTRIES;
|
|
102
82
|
const log = opts.log ?? (() => { });
|
|
103
83
|
(0, protocol_1.ensurePrivateDir)(dir);
|
|
104
84
|
const startedAt = new Date().toISOString();
|
|
@@ -118,7 +98,7 @@ function servePipe(opts) {
|
|
|
118
98
|
try {
|
|
119
99
|
const req = parseRequest(await fs_1.default.promises.readFile(busy, 'utf8'));
|
|
120
100
|
op = req.op;
|
|
121
|
-
reply = { ok: true, result: await dispatch(req
|
|
101
|
+
reply = { ok: true, result: await dispatch(req) };
|
|
122
102
|
}
|
|
123
103
|
catch (err) {
|
|
124
104
|
reply = err instanceof protocol_1.PipeError
|
|
@@ -183,7 +163,6 @@ function servePipe(opts) {
|
|
|
183
163
|
pid: process.pid,
|
|
184
164
|
version,
|
|
185
165
|
platform: process.platform,
|
|
186
|
-
tools: (0, tools_1.availableTools)(),
|
|
187
166
|
startedAt,
|
|
188
167
|
updatedAt: new Date().toISOString(),
|
|
189
168
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@infosupport/huddle-cli",
|
|
3
|
-
"version": "0.0.0-experiment-
|
|
3
|
+
"version": "0.0.0-experiment-147.123.1",
|
|
4
4
|
"description": "Huddle CLI — start devcontainers and manage firewall rules",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"author": "Info Support B.V.",
|
package/dist/pipe/fs-list.js
DELETED
|
@@ -1,157 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
// ── Host pipe op `fs.list`: browsing the host, one folder at a time ───────────
|
|
3
|
-
// Replaces the old folder *index* (`huddle indexfolder`), which existed only
|
|
4
|
-
// because the portal runs in a container and cannot see the host: an operator
|
|
5
|
-
// had to walk the host from a shell and push a snapshot of folder names into the
|
|
6
|
-
// database. Through the host pipe the portal can just look, and a live look is
|
|
7
|
-
// strictly better than a snapshot that went stale the moment a folder was made.
|
|
8
|
-
//
|
|
9
|
-
// Nothing is stored and nothing walks: each call reads exactly one directory,
|
|
10
|
-
// which keeps a drive root cheap and a folder created five seconds ago visible.
|
|
11
|
-
// Port of host-browse.ts from feat/sbx-sandboxes-rebased.
|
|
12
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
13
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
14
|
-
};
|
|
15
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
-
exports.toHuddlePath = toHuddlePath;
|
|
17
|
-
exports.isAbsoluteHostPath = isAbsoluteHostPath;
|
|
18
|
-
exports.hostRoots = hostRoots;
|
|
19
|
-
exports.listHostFolders = listHostFolders;
|
|
20
|
-
exports.fsList = fsList;
|
|
21
|
-
const fs_1 = __importDefault(require("fs"));
|
|
22
|
-
const os_1 = __importDefault(require("os"));
|
|
23
|
-
const path_1 = __importDefault(require("path"));
|
|
24
|
-
const protocol_1 = require("./protocol");
|
|
25
|
-
/**
|
|
26
|
-
* A host path in Huddle notation: forward slashes, upper-case drive letter, no
|
|
27
|
-
* trailing slash except on a root. One spelling for the whole system, so the
|
|
28
|
-
* gateway can compare and store paths without knowing the host's platform.
|
|
29
|
-
* Duplicated (on purpose) from the gateway's host-path.ts: the CLI must not
|
|
30
|
-
* depend on gateway code.
|
|
31
|
-
*/
|
|
32
|
-
function toHuddlePath(p, platform = process.platform) {
|
|
33
|
-
// A bare drive ('c:') is that drive's root here, not its current directory.
|
|
34
|
-
if (platform === 'win32' && /^[A-Za-z]:$/.test(p))
|
|
35
|
-
return `${p.toUpperCase()}/`;
|
|
36
|
-
const normalized = platform === 'win32' ? path_1.default.win32.normalize(p) : path_1.default.posix.normalize(p);
|
|
37
|
-
let s = normalized.replace(/\\/g, '/');
|
|
38
|
-
s = s.replace(/^([a-z]):/, (_m, d) => `${d.toUpperCase()}:`);
|
|
39
|
-
while (s.length > 1 && s.endsWith('/') && !/^[A-Z]:\/$/.test(s))
|
|
40
|
-
s = s.slice(0, -1);
|
|
41
|
-
return s;
|
|
42
|
-
}
|
|
43
|
-
/** Absolute in the host's own sense: '/x' on POSIX, 'C:/x' or a UNC '//server/share' on Windows. */
|
|
44
|
-
function isAbsoluteHostPath(p, platform = process.platform) {
|
|
45
|
-
if (platform === 'win32')
|
|
46
|
-
return /^[A-Za-z]:[\\/]/.test(p) || /^[\\/]{2}[^\\/]/.test(p);
|
|
47
|
-
return p.startsWith('/');
|
|
48
|
-
}
|
|
49
|
-
function leaf(p) {
|
|
50
|
-
if (p === '/')
|
|
51
|
-
return '/';
|
|
52
|
-
if (/^[A-Z]:\/$/.test(p))
|
|
53
|
-
return p.slice(0, 2);
|
|
54
|
-
return p.slice(p.lastIndexOf('/') + 1);
|
|
55
|
-
}
|
|
56
|
-
// Joins in Huddle notation rather than the platform's, so Windows hands back
|
|
57
|
-
// 'C:/projects/app' and not 'C:\projects\app'.
|
|
58
|
-
function joinHost(parent, segment) {
|
|
59
|
-
return parent.endsWith('/') ? `${parent}${segment}` : `${parent}/${segment}`;
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Where browsing starts: the drives (Windows) or `/` (elsewhere), plus the home
|
|
63
|
-
* folder because that is where projects usually live and nobody wants to click
|
|
64
|
-
* through /home/<user> every time.
|
|
65
|
-
*/
|
|
66
|
-
function hostRoots() {
|
|
67
|
-
const out = [];
|
|
68
|
-
const seen = new Set();
|
|
69
|
-
const add = (p, name) => {
|
|
70
|
-
const key = p.toLowerCase();
|
|
71
|
-
if (seen.has(key))
|
|
72
|
-
return;
|
|
73
|
-
seen.add(key);
|
|
74
|
-
out.push({ path: p, name: name ?? leaf(p) });
|
|
75
|
-
};
|
|
76
|
-
if (process.platform === 'win32') {
|
|
77
|
-
// Probing 26 letters is a stat per letter and no slower than the WMI query
|
|
78
|
-
// that answers the same question, without a dependency. A CD drive with no
|
|
79
|
-
// disc exists but throws on read; it is no place for a workspace, so
|
|
80
|
-
// anything unreadable is left out.
|
|
81
|
-
for (let i = 0; i < 26; i++) {
|
|
82
|
-
const letter = String.fromCharCode(65 + i);
|
|
83
|
-
try {
|
|
84
|
-
fs_1.default.readdirSync(`${letter}:/`);
|
|
85
|
-
}
|
|
86
|
-
catch {
|
|
87
|
-
continue;
|
|
88
|
-
}
|
|
89
|
-
add(`${letter}:/`, `${letter}:`);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
else {
|
|
93
|
-
add('/', '/');
|
|
94
|
-
}
|
|
95
|
-
const home = os_1.default.homedir();
|
|
96
|
-
if (home) {
|
|
97
|
-
try {
|
|
98
|
-
if (fs_1.default.statSync(home).isDirectory())
|
|
99
|
-
add(toHuddlePath(home));
|
|
100
|
-
}
|
|
101
|
-
catch { /* no readable home: the drives/root above are enough */ }
|
|
102
|
-
}
|
|
103
|
-
return out;
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* The immediate subfolders of `dir`, sorted case-insensitively like a file
|
|
107
|
-
* dialog. Only one level: the portal asks again when it opens a folder.
|
|
108
|
-
*
|
|
109
|
-
* Hidden (dot) folders are included: `.config`, `.local` or a dotted worktree
|
|
110
|
-
* are real places, and a picker that omits a folder the operator sees in their
|
|
111
|
-
* own file manager reads as broken. Symlinked folders are included too; nothing
|
|
112
|
-
* walks, so a link loop is at worst someone clicking in circles.
|
|
113
|
-
*
|
|
114
|
-
* Sorting happens before truncation, so a huge folder shows its first `max`
|
|
115
|
-
* names alphabetically rather than an arbitrary readdir-order slice.
|
|
116
|
-
*/
|
|
117
|
-
async function listHostFolders(dir, max = protocol_1.MAX_FOLDER_ENTRIES) {
|
|
118
|
-
let entries;
|
|
119
|
-
try {
|
|
120
|
-
entries = await fs_1.default.promises.readdir(dir, { withFileTypes: true });
|
|
121
|
-
}
|
|
122
|
-
catch (err) {
|
|
123
|
-
throw new protocol_1.PipeError('not_found', `cannot read folder ${dir}: ${err.code ?? err}`);
|
|
124
|
-
}
|
|
125
|
-
const names = [];
|
|
126
|
-
for (const e of entries) {
|
|
127
|
-
let isDir = e.isDirectory();
|
|
128
|
-
if (!isDir && e.isSymbolicLink()) {
|
|
129
|
-
try {
|
|
130
|
-
isDir = (await fs_1.default.promises.stat(path_1.default.join(dir, e.name))).isDirectory();
|
|
131
|
-
}
|
|
132
|
-
catch {
|
|
133
|
-
continue; // dangling link
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
if (isDir)
|
|
137
|
-
names.push(e.name);
|
|
138
|
-
}
|
|
139
|
-
names.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
|
|
140
|
-
const truncated = names.length > max;
|
|
141
|
-
const folders = names.slice(0, max).map((name) => ({ path: joinHost(dir, name), name }));
|
|
142
|
-
return { path: dir, folders, truncated, max };
|
|
143
|
-
}
|
|
144
|
-
/** The `fs.list` op: no path → the roots, otherwise one folder. */
|
|
145
|
-
async function fsList(args, max = protocol_1.MAX_FOLDER_ENTRIES) {
|
|
146
|
-
const raw = args.path;
|
|
147
|
-
if (raw === undefined || raw === null || raw === '') {
|
|
148
|
-
return { path: '', folders: hostRoots(), truncated: false, max };
|
|
149
|
-
}
|
|
150
|
-
if (typeof raw !== 'string')
|
|
151
|
-
throw new protocol_1.PipeError('bad_request', 'path must be a string');
|
|
152
|
-
if (raw.includes('\0'))
|
|
153
|
-
throw new protocol_1.PipeError('bad_request', 'path contains a NUL byte');
|
|
154
|
-
if (!isAbsoluteHostPath(raw))
|
|
155
|
-
throw new protocol_1.PipeError('bad_request', `not an absolute host path: ${raw}`);
|
|
156
|
-
return listHostFolders(toHuddlePath(raw), max);
|
|
157
|
-
}
|
package/dist/pipe/sbx-kit.js
DELETED
|
@@ -1,107 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
// ── Host pipe op `sbx.kit`: the Huddle CA for a Docker Sandbox ──
|
|
3
|
-
// Huddle inspects TLS (it terminates it with its own CA) for a devcontainer, and
|
|
4
|
-
// the devcontainer is set up to trust that CA. A Docker Sandbox gets the same
|
|
5
|
-
// through an sbx kit (a "mixin": `sbx create --kit <dir>`), which sbx applies to
|
|
6
|
-
// the sandbox at create:
|
|
7
|
-
// - the CA in the system trust store (install, as root);
|
|
8
|
-
// - NODE_EXTRA_CA_CERTS / SSL_CERT_FILE / REQUESTS_CA_BUNDLE, like a devcontainer,
|
|
9
|
-
// but all on the system bundle: that keeps sbx's own proxy CA, which sbx's
|
|
10
|
-
// credential proxy needs (a tool trusting only the Huddle CA breaks there);
|
|
11
|
-
// - the CA in the keystore of a JetBrains backend (the JBR does not read the
|
|
12
|
-
// system store), also for a backend Toolbox installs later.
|
|
13
|
-
// The op writes the kit to ~/.huddle/sbx/kits/huddle-ca and returns its host path.
|
|
14
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
15
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
16
|
-
};
|
|
17
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
-
exports.KIT_NAME = exports.SBX_KITS_DIR = void 0;
|
|
19
|
-
exports.sbxKit = sbxKit;
|
|
20
|
-
const fs_1 = __importDefault(require("fs"));
|
|
21
|
-
const path_1 = __importDefault(require("path"));
|
|
22
|
-
const config_1 = require("../config");
|
|
23
|
-
const protocol_1 = require("./protocol");
|
|
24
|
-
const fs_list_1 = require("./fs-list");
|
|
25
|
-
exports.SBX_KITS_DIR = path_1.default.join(config_1.CONFIG_DIR, 'sbx', 'kits');
|
|
26
|
-
exports.KIT_NAME = 'huddle-ca';
|
|
27
|
-
const PEM_RE = /^-----BEGIN CERTIFICATE-----\r?\n[A-Za-z0-9+/=\r\n]+-----END CERTIFICATE-----\r?\n?$/;
|
|
28
|
-
const MAX_PEM = 16 * 1024;
|
|
29
|
-
// In the sandbox, files/home/ is /home/agent/.
|
|
30
|
-
const IN_BOX = '/home/agent/.huddle-ca';
|
|
31
|
-
const BUNDLE = '/etc/ssl/certs/ca-certificates.crt';
|
|
32
|
-
const SPEC = `schemaVersion: "2"
|
|
33
|
-
kind: mixin
|
|
34
|
-
name: ${exports.KIT_NAME}
|
|
35
|
-
description: Trust the Huddle CA, so Huddle can inspect this sandbox's TLS
|
|
36
|
-
environment:
|
|
37
|
-
variables:
|
|
38
|
-
NODE_EXTRA_CA_CERTS: ${BUNDLE}
|
|
39
|
-
SSL_CERT_FILE: ${BUNDLE}
|
|
40
|
-
REQUESTS_CA_BUNDLE: ${BUNDLE}
|
|
41
|
-
setup:
|
|
42
|
-
install:
|
|
43
|
-
- command: "sh ${IN_BOX}/install.sh"
|
|
44
|
-
user: "0"
|
|
45
|
-
startup:
|
|
46
|
-
- command: "sh ${IN_BOX}/jbr-watch.sh"
|
|
47
|
-
`;
|
|
48
|
-
const INSTALL = `#!/bin/sh
|
|
49
|
-
# Generated by Huddle. Runs as root when the sandbox is created.
|
|
50
|
-
set -e
|
|
51
|
-
mkdir -p /usr/local/share/ca-certificates
|
|
52
|
-
install -m 0644 ${IN_BOX}/huddle-ca.crt /usr/local/share/ca-certificates/huddle-ca.crt
|
|
53
|
-
# sbx's own proxy CA into the same store, so the bundle the variables point at
|
|
54
|
-
# trusts both (sbx's credential proxy signs with that one).
|
|
55
|
-
if [ -n "\${PROXY_CA_CERT_B64:-}" ]; then
|
|
56
|
-
echo "$PROXY_CA_CERT_B64" | base64 -d > /usr/local/share/ca-certificates/sbx-proxy-ca.crt 2>/dev/null \\
|
|
57
|
-
&& chmod 644 /usr/local/share/ca-certificates/sbx-proxy-ca.crt \\
|
|
58
|
-
|| rm -f /usr/local/share/ca-certificates/sbx-proxy-ca.crt
|
|
59
|
-
fi
|
|
60
|
-
update-ca-certificates >/dev/null 2>&1 || true
|
|
61
|
-
echo "[huddle] CA installed"
|
|
62
|
-
`;
|
|
63
|
-
// A JetBrains backend runs on its own JVM (the JBR), which only trusts its own
|
|
64
|
-
// keystore. Toolbox installs it under ~/.cache/JetBrains/RemoteDev/dist on the
|
|
65
|
-
// first connect, so this keeps watching (in the background) and imports the CA
|
|
66
|
-
// into every backend it finds, once.
|
|
67
|
-
const JBR_WATCH = `#!/bin/sh
|
|
68
|
-
# Generated by Huddle. Runs as the agent user on every sandbox start.
|
|
69
|
-
CA=/usr/local/share/ca-certificates/huddle-ca.crt
|
|
70
|
-
[ -f "$CA" ] || CA=${IN_BOX}/huddle-ca.crt
|
|
71
|
-
import_all() {
|
|
72
|
-
for d in "$HOME"/.cache/JetBrains/RemoteDev/dist/*/; do
|
|
73
|
-
kt="$d/jbr/bin/keytool"; ks="$d/jbr/lib/security/cacerts"
|
|
74
|
-
[ -x "$kt" ] && [ -f "$ks" ] && [ ! -f "$d/.huddle-ca" ] || continue
|
|
75
|
-
"$kt" -delete -alias huddle-ca -keystore "$ks" -storepass changeit >/dev/null 2>&1 || true
|
|
76
|
-
"$kt" -importcert -noprompt -trustcacerts -alias huddle-ca -file "$CA" -keystore "$ks" -storepass changeit >/dev/null 2>&1 \\
|
|
77
|
-
&& touch "$d/.huddle-ca"
|
|
78
|
-
done
|
|
79
|
-
}
|
|
80
|
-
import_all
|
|
81
|
-
( while sleep 30; do import_all; done ) >/dev/null 2>&1 </dev/null &
|
|
82
|
-
exit 0
|
|
83
|
-
`;
|
|
84
|
-
/** The `sbx.kit` op: `{ caPem }` → `{ dir }`, the kit's folder as a host path. */
|
|
85
|
-
function sbxKit(args, root = exports.SBX_KITS_DIR, platform = process.platform) {
|
|
86
|
-
const { caPem } = args;
|
|
87
|
-
if (typeof caPem !== 'string' || caPem.length > MAX_PEM || !PEM_RE.test(caPem)) {
|
|
88
|
-
throw new protocol_1.PipeError('bad_request', 'caPem must be one PEM certificate');
|
|
89
|
-
}
|
|
90
|
-
const dir = path_1.default.join(root, exports.KIT_NAME);
|
|
91
|
-
try {
|
|
92
|
-
(0, protocol_1.ensurePrivateDir)(root);
|
|
93
|
-
(0, protocol_1.ensurePrivateDir)(dir);
|
|
94
|
-
const home = path_1.default.join(dir, 'files', 'home', '.huddle-ca');
|
|
95
|
-
fs_1.default.mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
96
|
-
// \n only: these are read inside the Linux sandbox, also when written on Windows.
|
|
97
|
-
const write = (file, text) => fs_1.default.writeFileSync(file, text.replace(/\r\n/g, '\n'), { mode: 0o644 });
|
|
98
|
-
write(path_1.default.join(dir, 'spec.yaml'), SPEC);
|
|
99
|
-
write(path_1.default.join(home, 'huddle-ca.crt'), caPem.endsWith('\n') ? caPem : `${caPem}\n`);
|
|
100
|
-
write(path_1.default.join(home, 'install.sh'), INSTALL);
|
|
101
|
-
write(path_1.default.join(home, 'jbr-watch.sh'), JBR_WATCH);
|
|
102
|
-
}
|
|
103
|
-
catch (err) {
|
|
104
|
-
throw new protocol_1.PipeError('internal', `could not write the sbx kit: ${err.message ?? err}`);
|
|
105
|
-
}
|
|
106
|
-
return { dir: (0, fs_list_1.toHuddlePath)(dir, platform) };
|
|
107
|
-
}
|
package/dist/pipe/sbx-links.js
DELETED
|
@@ -1,147 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
// ── Host pipe op `sbx.links`: Settings → Folder mappings for a Docker Sandbox ──
|
|
3
|
-
// sbx mounts only the folders it is given at create, at their host path. So each
|
|
4
|
-
// sandbox gets two extra folders, ~/.huddle/sbx/links/<name>/rw and /ro, with one
|
|
5
|
-
// link per folder mapping in them (a junction on Windows, which needs no admin
|
|
6
|
-
// rights or developer mode; a symlink elsewhere). The gateway passes them to
|
|
7
|
-
// `sbx create`, ro with `:ro`, and links each one to its container path inside.
|
|
8
|
-
//
|
|
9
|
-
// Tested against sbx v0.39.0 on Windows (sbx-folder-links-poc.mjs): sbx's file
|
|
10
|
-
// share follows these links on the host side, `:ro` on the ro folder holds for
|
|
11
|
-
// what is behind them too, and a link the sandbox makes in rw itself stays inside
|
|
12
|
-
// the sandbox (it never appears on the host, so it cannot reach other folders).
|
|
13
|
-
//
|
|
14
|
-
// The op only (re)builds those folders. An empty list removes the sandbox's
|
|
15
|
-
// folder. Links in it are removed, never followed.
|
|
16
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
17
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
18
|
-
};
|
|
19
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
-
exports.SBX_LINKS_DIR = void 0;
|
|
21
|
-
exports.removeNoFollow = removeNoFollow;
|
|
22
|
-
exports.sbxLinks = sbxLinks;
|
|
23
|
-
const fs_1 = __importDefault(require("fs"));
|
|
24
|
-
const path_1 = __importDefault(require("path"));
|
|
25
|
-
const config_1 = require("../config");
|
|
26
|
-
const protocol_1 = require("./protocol");
|
|
27
|
-
const fs_list_1 = require("./fs-list");
|
|
28
|
-
exports.SBX_LINKS_DIR = path_1.default.join(config_1.CONFIG_DIR, 'sbx', 'links');
|
|
29
|
-
// Same rules as the gateway (environments/sbx.ts): the name is a folder name here.
|
|
30
|
-
const SANDBOX_NAME_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
31
|
-
const LINK_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
32
|
-
const MAX_LINKS = 64;
|
|
33
|
-
/** Removes `p` without following any link in it: a link is removed itself. */
|
|
34
|
-
function removeNoFollow(p) {
|
|
35
|
-
let st;
|
|
36
|
-
try {
|
|
37
|
-
st = fs_1.default.lstatSync(p);
|
|
38
|
-
}
|
|
39
|
-
catch {
|
|
40
|
-
return;
|
|
41
|
-
}
|
|
42
|
-
if (st.isSymbolicLink()) {
|
|
43
|
-
// A junction is a directory to unlink() on some Node versions.
|
|
44
|
-
try {
|
|
45
|
-
fs_1.default.unlinkSync(p);
|
|
46
|
-
}
|
|
47
|
-
catch {
|
|
48
|
-
fs_1.default.rmdirSync(p);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
else if (st.isDirectory()) {
|
|
52
|
-
for (const e of fs_1.default.readdirSync(p))
|
|
53
|
-
removeNoFollow(path_1.default.join(p, e));
|
|
54
|
-
fs_1.default.rmdirSync(p);
|
|
55
|
-
}
|
|
56
|
-
else {
|
|
57
|
-
fs_1.default.unlinkSync(p);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
function inside(child, parent, platform) {
|
|
61
|
-
const norm = (s) => {
|
|
62
|
-
const h = (0, fs_list_1.toHuddlePath)(s, platform);
|
|
63
|
-
return platform === 'win32' ? h.toLowerCase() : h;
|
|
64
|
-
};
|
|
65
|
-
const c = norm(child);
|
|
66
|
-
const p = norm(parent);
|
|
67
|
-
return c === p || c.startsWith(p.endsWith('/') ? p : `${p}/`);
|
|
68
|
-
}
|
|
69
|
-
function parseLinks(raw, platform) {
|
|
70
|
-
if (!Array.isArray(raw))
|
|
71
|
-
throw new protocol_1.PipeError('bad_request', 'links must be an array');
|
|
72
|
-
if (raw.length > MAX_LINKS)
|
|
73
|
-
throw new protocol_1.PipeError('bad_request', `at most ${MAX_LINKS} links`);
|
|
74
|
-
const seen = new Set();
|
|
75
|
-
return raw.map((l) => {
|
|
76
|
-
const { id, hostPath, readOnly } = (l ?? {});
|
|
77
|
-
if (typeof id !== 'string' || !LINK_ID_RE.test(id))
|
|
78
|
-
throw new protocol_1.PipeError('bad_request', 'link id must be 1-64 letters, digits, _ or -');
|
|
79
|
-
if (seen.has(id))
|
|
80
|
-
throw new protocol_1.PipeError('bad_request', `duplicate link id ${id}`);
|
|
81
|
-
seen.add(id);
|
|
82
|
-
if (typeof hostPath !== 'string' || hostPath.includes('\0') || !(0, fs_list_1.isAbsoluteHostPath)(hostPath, platform)) {
|
|
83
|
-
throw new protocol_1.PipeError('bad_request', `link ${id}: hostPath must be an absolute path`);
|
|
84
|
-
}
|
|
85
|
-
return { id, hostPath, readOnly: readOnly === true };
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
/** The `sbx.links` op. `root` and `huddleHome` are only moved in tests. */
|
|
89
|
-
function sbxLinks(args, root = exports.SBX_LINKS_DIR, huddleHome = config_1.CONFIG_DIR, platform = process.platform) {
|
|
90
|
-
const { name } = args;
|
|
91
|
-
if (typeof name !== 'string' || !SANDBOX_NAME_RE.test(name))
|
|
92
|
-
throw new protocol_1.PipeError('bad_request', 'invalid sandbox name');
|
|
93
|
-
const links = parseLinks(args.links, platform);
|
|
94
|
-
// Resolved first: a mapping that is itself a link counts as where it points.
|
|
95
|
-
const usable = [];
|
|
96
|
-
const skipped = [];
|
|
97
|
-
for (const l of links) {
|
|
98
|
-
let target;
|
|
99
|
-
try {
|
|
100
|
-
target = fs_1.default.realpathSync(l.hostPath);
|
|
101
|
-
if (!fs_1.default.statSync(target).isDirectory()) {
|
|
102
|
-
skipped.push({ id: l.id, reason: 'not a folder' });
|
|
103
|
-
continue;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
catch {
|
|
107
|
-
skipped.push({ id: l.id, reason: 'does not exist' });
|
|
108
|
-
continue;
|
|
109
|
-
}
|
|
110
|
-
// Same rule as every mount Huddle makes (gateway host-path.ts): never
|
|
111
|
-
// ~/.huddle or inside it, and a folder around it only read-only.
|
|
112
|
-
if (inside(target, huddleHome, platform)) {
|
|
113
|
-
skipped.push({ id: l.id, reason: "is Huddle's own folder or inside it" });
|
|
114
|
-
continue;
|
|
115
|
-
}
|
|
116
|
-
if (!l.readOnly && inside(huddleHome, target, platform)) {
|
|
117
|
-
skipped.push({ id: l.id, reason: "contains Huddle's own folder, so only read-only" });
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
usable.push({ ...l, target });
|
|
121
|
-
}
|
|
122
|
-
const boxDir = path_1.default.join(root, name);
|
|
123
|
-
try {
|
|
124
|
-
removeNoFollow(boxDir);
|
|
125
|
-
if (usable.length === 0)
|
|
126
|
-
return { rw: null, ro: null, skipped };
|
|
127
|
-
(0, protocol_1.ensurePrivateDir)(path_1.default.dirname(root));
|
|
128
|
-
(0, protocol_1.ensurePrivateDir)(root);
|
|
129
|
-
(0, protocol_1.ensurePrivateDir)(boxDir);
|
|
130
|
-
const made = { rw: null, ro: null };
|
|
131
|
-
for (const l of usable) {
|
|
132
|
-
const kind = l.readOnly ? 'ro' : 'rw';
|
|
133
|
-
const dir = path_1.default.join(boxDir, kind);
|
|
134
|
-
if (!made[kind]) {
|
|
135
|
-
fs_1.default.mkdirSync(dir, { mode: 0o700 });
|
|
136
|
-
made[kind] = (0, fs_list_1.toHuddlePath)(dir, platform);
|
|
137
|
-
}
|
|
138
|
-
fs_1.default.symlinkSync(l.target, path_1.default.join(dir, l.id), platform === 'win32' ? 'junction' : 'dir');
|
|
139
|
-
}
|
|
140
|
-
return { ...made, skipped };
|
|
141
|
-
}
|
|
142
|
-
catch (err) {
|
|
143
|
-
if (err instanceof protocol_1.PipeError)
|
|
144
|
-
throw err;
|
|
145
|
-
throw new protocol_1.PipeError('internal', `could not prepare the folder links: ${err.message ?? err}`);
|
|
146
|
-
}
|
|
147
|
-
}
|
package/dist/pipe/tools.js
DELETED
|
@@ -1,227 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
// ── Host pipe op `tool.run`: allowlisted host binaries, argv only ─────────────
|
|
3
|
-
// The gateway can ask the host to run a tool such as Docker Sandboxes (`sbx`).
|
|
4
|
-
// Only binaries named in TOOLS can run, always with an argv array and never via
|
|
5
|
-
// a shell, so an argument like `$(whoami)` or `& calc` stays a literal string.
|
|
6
|
-
// Adding the next environment tool is one entry in TOOLS (plus its provider in
|
|
7
|
-
// gateway/src/environments/).
|
|
8
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
9
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
10
|
-
};
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.TOOLS = void 0;
|
|
13
|
-
exports.resolveTool = resolveTool;
|
|
14
|
-
exports.execTool = execTool;
|
|
15
|
-
exports.toolRun = toolRun;
|
|
16
|
-
exports.toolVersion = toolVersion;
|
|
17
|
-
exports.toolsInfo = toolsInfo;
|
|
18
|
-
exports.availableTools = availableTools;
|
|
19
|
-
const fs_1 = __importDefault(require("fs"));
|
|
20
|
-
const os_1 = __importDefault(require("os"));
|
|
21
|
-
const path_1 = __importDefault(require("path"));
|
|
22
|
-
const child_process_1 = require("child_process");
|
|
23
|
-
const protocol_1 = require("./protocol");
|
|
24
|
-
exports.TOOLS = {
|
|
25
|
-
sbx: { bins: ['sbx', 'sbx.exe'], env: 'HUDDLE_SBX_BIN' },
|
|
26
|
-
};
|
|
27
|
-
// Windows runs .bat/.cmd through cmd.exe whatever argv we pass, and cmd.exe
|
|
28
|
-
// re-parses the command line, so an argument could inject a command. Only real
|
|
29
|
-
// executables are accepted.
|
|
30
|
-
const REFUSED_EXT = new Set(['.bat', '.cmd']);
|
|
31
|
-
const WIN_RUNNABLE_EXT = new Set(['.exe', '.com']);
|
|
32
|
-
function isRunnableFile(file) {
|
|
33
|
-
try {
|
|
34
|
-
if (!fs_1.default.statSync(file).isFile())
|
|
35
|
-
return false;
|
|
36
|
-
if (process.platform !== 'win32')
|
|
37
|
-
fs_1.default.accessSync(file, fs_1.default.constants.X_OK);
|
|
38
|
-
return true;
|
|
39
|
-
}
|
|
40
|
-
catch {
|
|
41
|
-
return false;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
/** Candidate file names for one bin: on Windows `sbx` becomes sbx.COM, sbx.EXE, ... per PATHEXT. */
|
|
45
|
-
function candidates(bin) {
|
|
46
|
-
if (process.platform !== 'win32' || path_1.default.extname(bin))
|
|
47
|
-
return [bin];
|
|
48
|
-
const exts = (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
|
|
49
|
-
return exts.map((ext) => bin + ext.toLowerCase());
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Finds a tool's binary without a shell: the env override if set, otherwise the
|
|
53
|
-
* first runnable match on PATH. A .bat/.cmd hit is skipped, and reported as
|
|
54
|
-
* not_allowed only when nothing else was found.
|
|
55
|
-
*/
|
|
56
|
-
function resolveTool(name) {
|
|
57
|
-
const spec = Object.prototype.hasOwnProperty.call(exports.TOOLS, name) ? exports.TOOLS[name] : undefined;
|
|
58
|
-
if (!spec)
|
|
59
|
-
return { error: new protocol_1.PipeError('not_allowed', `tool '${name}' is not allowlisted on the host`) };
|
|
60
|
-
const override = process.env[spec.env]?.trim();
|
|
61
|
-
const bins = override ? [override] : spec.bins;
|
|
62
|
-
const dirs = (process.env.PATH ?? '').split(path_1.default.delimiter).filter(Boolean);
|
|
63
|
-
let refused;
|
|
64
|
-
// Every file to try, in order. A bin with a directory in it is a path, not a
|
|
65
|
-
// name to look up on PATH.
|
|
66
|
-
const files = bins
|
|
67
|
-
.flatMap((bin) => (bin.includes('/') || bin.includes('\\') ? [path_1.default.resolve(bin)] : dirs.map((d) => path_1.default.join(d, bin))))
|
|
68
|
-
.flatMap(candidates);
|
|
69
|
-
for (const file of files) {
|
|
70
|
-
const ext = path_1.default.extname(file).toLowerCase();
|
|
71
|
-
// On Windows, skip batch files (they go through cmd.exe) and non-executables.
|
|
72
|
-
if (process.platform === 'win32' && !WIN_RUNNABLE_EXT.has(ext)) {
|
|
73
|
-
if (REFUSED_EXT.has(ext) && isRunnableFile(file))
|
|
74
|
-
refused ??= file;
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
77
|
-
if (isRunnableFile(file))
|
|
78
|
-
return { path: file };
|
|
79
|
-
}
|
|
80
|
-
if (refused) {
|
|
81
|
-
return { error: new protocol_1.PipeError('not_allowed', `refusing to run ${refused}: batch files go through cmd.exe`) };
|
|
82
|
-
}
|
|
83
|
-
const where = override ? `${spec.env}=${override}` : `${spec.bins.join(' / ')} on PATH`;
|
|
84
|
-
return { error: new protocol_1.PipeError('tool_missing', `${name} is not installed on the host (looked for ${where})`) };
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Runs `file` with argv `args`: no shell, stdin closed, no console window, a
|
|
88
|
-
* hard timeout and at most MAX_OUTPUT_BYTES kept per stream (the rest is
|
|
89
|
-
* drained and dropped, so a chatty tool cannot exhaust the agent's memory).
|
|
90
|
-
*/
|
|
91
|
-
function execTool(file, args, timeoutMs, maxBytes = protocol_1.MAX_OUTPUT_BYTES) {
|
|
92
|
-
return new Promise((resolve, reject) => {
|
|
93
|
-
let child;
|
|
94
|
-
try {
|
|
95
|
-
child = (0, child_process_1.spawn)(file, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, shell: false });
|
|
96
|
-
}
|
|
97
|
-
catch (err) {
|
|
98
|
-
reject(err);
|
|
99
|
-
return;
|
|
100
|
-
}
|
|
101
|
-
const collect = () => {
|
|
102
|
-
const chunks = [];
|
|
103
|
-
let size = 0;
|
|
104
|
-
let dropped = false;
|
|
105
|
-
return {
|
|
106
|
-
push(chunk) {
|
|
107
|
-
if (size >= maxBytes) {
|
|
108
|
-
dropped = true;
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
const room = maxBytes - size;
|
|
112
|
-
if (chunk.length > room) {
|
|
113
|
-
chunk = chunk.subarray(0, room);
|
|
114
|
-
dropped = true;
|
|
115
|
-
}
|
|
116
|
-
chunks.push(chunk);
|
|
117
|
-
size += chunk.length;
|
|
118
|
-
},
|
|
119
|
-
text() {
|
|
120
|
-
const s = Buffer.concat(chunks).toString('utf8');
|
|
121
|
-
return dropped ? `${s}\n[huddle] output truncated at ${maxBytes} bytes` : s;
|
|
122
|
-
},
|
|
123
|
-
};
|
|
124
|
-
};
|
|
125
|
-
const out = collect();
|
|
126
|
-
const err = collect();
|
|
127
|
-
child.stdout.on('data', (c) => out.push(c));
|
|
128
|
-
child.stderr.on('data', (c) => err.push(c));
|
|
129
|
-
let timedOut = false;
|
|
130
|
-
const timer = setTimeout(() => {
|
|
131
|
-
timedOut = true;
|
|
132
|
-
child.kill('SIGTERM');
|
|
133
|
-
// A tool that ignores SIGTERM still has to go; on Windows kill() is already final.
|
|
134
|
-
setTimeout(() => child.kill('SIGKILL'), 2000).unref();
|
|
135
|
-
}, timeoutMs);
|
|
136
|
-
child.on('error', (e) => {
|
|
137
|
-
clearTimeout(timer);
|
|
138
|
-
reject(e);
|
|
139
|
-
});
|
|
140
|
-
let done = false;
|
|
141
|
-
const finish = (code, signal) => {
|
|
142
|
-
if (done)
|
|
143
|
-
return;
|
|
144
|
-
done = true;
|
|
145
|
-
clearTimeout(timer);
|
|
146
|
-
let stderr = err.text();
|
|
147
|
-
// 124 is what timeout(1) exits with; a signal maps to the shell's 128+n.
|
|
148
|
-
let exit = code ?? (signal ? 128 + (os_1.default.constants.signals[signal] ?? 0) : 1);
|
|
149
|
-
if (timedOut) {
|
|
150
|
-
exit = 124;
|
|
151
|
-
stderr += `${stderr && !stderr.endsWith('\n') ? '\n' : ''}[huddle] timed out after ${timeoutMs} ms`;
|
|
152
|
-
}
|
|
153
|
-
resolve({ code: exit, stdout: out.text(), stderr });
|
|
154
|
-
};
|
|
155
|
-
// 'close' waits for the pipes, which stay open as long as ANY process holds
|
|
156
|
-
// them: a daemon the tool started in the background, or a grandchild that
|
|
157
|
-
// outlived a timeout kill. Once the tool itself has exited, give its output
|
|
158
|
-
// a moment to drain and then stop waiting for the stragglers.
|
|
159
|
-
child.on('exit', (code, signal) => {
|
|
160
|
-
setTimeout(() => {
|
|
161
|
-
child.stdout.destroy();
|
|
162
|
-
child.stderr.destroy();
|
|
163
|
-
finish(code, signal);
|
|
164
|
-
}, 1000);
|
|
165
|
-
});
|
|
166
|
-
child.on('close', finish);
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
/** The `tool.run` op. */
|
|
170
|
-
async function toolRun(args) {
|
|
171
|
-
const { tool, args: argv, timeoutMs } = args;
|
|
172
|
-
if (typeof tool !== 'string' || !tool)
|
|
173
|
-
throw new protocol_1.PipeError('bad_request', 'tool must be a non-empty string');
|
|
174
|
-
if (!Array.isArray(argv) || !argv.every((a) => typeof a === 'string')) {
|
|
175
|
-
throw new protocol_1.PipeError('bad_request', 'args must be an array of strings');
|
|
176
|
-
}
|
|
177
|
-
if (argv.some((a) => a.includes('\0')))
|
|
178
|
-
throw new protocol_1.PipeError('bad_request', 'args must not contain NUL bytes');
|
|
179
|
-
if (timeoutMs !== undefined && (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
|
|
180
|
-
throw new protocol_1.PipeError('bad_request', 'timeoutMs must be a positive number');
|
|
181
|
-
}
|
|
182
|
-
const resolved = resolveTool(tool);
|
|
183
|
-
if ('error' in resolved)
|
|
184
|
-
throw resolved.error;
|
|
185
|
-
const timeout = Math.min(Math.round(timeoutMs ?? protocol_1.DEFAULT_TOOL_TIMEOUT_MS), protocol_1.MAX_TOOL_TIMEOUT_MS);
|
|
186
|
-
try {
|
|
187
|
-
return await execTool(resolved.path, argv, timeout);
|
|
188
|
-
}
|
|
189
|
-
catch (err) {
|
|
190
|
-
const e = err;
|
|
191
|
-
if (e.code === 'ENOENT')
|
|
192
|
-
throw new protocol_1.PipeError('tool_missing', `${tool} disappeared from ${resolved.path}`);
|
|
193
|
-
throw new protocol_1.PipeError('internal', `could not run ${tool}: ${e.message ?? e}`);
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
// One probe per binary path per agent run: `sbx version` can take a moment, and
|
|
197
|
-
// host.info is asked for often enough that re-running it every time would show.
|
|
198
|
-
const versionCache = new Map();
|
|
199
|
-
/** First line of `<tool> version`, best effort (undefined on any failure). */
|
|
200
|
-
function toolVersion(file) {
|
|
201
|
-
let cached = versionCache.get(file);
|
|
202
|
-
if (!cached) {
|
|
203
|
-
cached = execTool(file, ['version'], 5000, 64 * 1024)
|
|
204
|
-
.then((r) => (r.code === 0 ? (r.stdout || r.stderr).trim().split(/\r?\n/)[0] || undefined : undefined))
|
|
205
|
-
.catch(() => undefined);
|
|
206
|
-
versionCache.set(file, cached);
|
|
207
|
-
}
|
|
208
|
-
return cached;
|
|
209
|
-
}
|
|
210
|
-
/** Availability of every allowlisted tool, for host.info. */
|
|
211
|
-
async function toolsInfo() {
|
|
212
|
-
const out = {};
|
|
213
|
-
await Promise.all(Object.keys(exports.TOOLS).map(async (name) => {
|
|
214
|
-
const r = resolveTool(name);
|
|
215
|
-
if ('error' in r) {
|
|
216
|
-
out[name] = { available: false };
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
const version = await toolVersion(r.path);
|
|
220
|
-
out[name] = version ? { available: true, path: r.path, version } : { available: true, path: r.path };
|
|
221
|
-
}));
|
|
222
|
-
return out;
|
|
223
|
-
}
|
|
224
|
-
/** Names of the allowlisted tools that are installed, for the heartbeat. */
|
|
225
|
-
function availableTools() {
|
|
226
|
-
return Object.keys(exports.TOOLS).filter((name) => !('error' in resolveTool(name)));
|
|
227
|
-
}
|