@infosupport/huddle-cli 0.0.0-experiment-147.123.1 → 0.0.0-experiment-160.124.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 CHANGED
@@ -44,43 +44,25 @@ huddle --ide vscode \
44
44
 
45
45
  Default API URL: `http://localhost:3000`. Override it with `--url` or `HUDDLE_URL`.
46
46
 
47
- ## Making host folders selectable in the portal
47
+ ## Browsing host folders from the portal
48
48
 
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.
49
+ Huddle's portal runs inside a container, so it cannot see your host by itself. `huddle init`
50
+ (and `huddle restart`) therefore also start the **host pipe** in the background: a small agent,
51
+ part of this CLI, that answers the gateway through files in `~/.huddle/pipe`. Through it every
52
+ host-path field in the portal gets a **Browse** button with a live folder tree of your host —
53
+ starting a devcontainer, the folder mappings, and the team-managed folders — and the portal can
54
+ drive allowlisted host tools such as Docker Sandboxes (`sbx`, argv only, never a shell). Starting a
55
+ devcontainer, Ctrl-click picks several folders at once and each becomes its own worktree.
57
56
 
58
57
  ```bash
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)
58
+ huddle pipe status # online/offline, pid, CLI version, available tools
59
+ huddle pipe start # start in the background (replaces a running one)
60
+ huddle pipe stop
61
+ huddle pipe serve # run in the foreground, for debugging
66
62
  ```
67
63
 
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.
64
+ The agent logs to `~/.huddle/pipe/host.log`. Typing a path by hand keeps working when the pipe
65
+ is offline. The protocol is described in [docs/host-pipe.md](../docs/host-pipe.md).
84
66
 
85
67
  ## Experiments
86
68
 
package/dist/index.js CHANGED
@@ -12,15 +12,14 @@ 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");
16
15
  const command_1 = require("./pipe/command");
17
16
  const images_1 = require("./images");
18
17
  const self_update_1 = require("./self-update");
19
18
  const utils_1 = require("./utils");
20
19
  const experiment_1 = require("./experiment");
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']);
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']);
24
23
  function parseArgs(argv) {
25
24
  const positional = [];
26
25
  const flags = {};
@@ -125,12 +124,8 @@ Usage:
125
124
  team firewall-rules folder)
126
125
  huddle migrate [folder] Wire an existing docker-compose devcontainer
127
126
  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)
132
127
  huddle pipe status Show whether the host pipe is online (lets the
133
- portal set up SSH for Connect IDE)
128
+ portal browse host folders and run sbx)
134
129
  huddle pipe start|stop Start (or replace) / stop the host pipe in the
135
130
  background (huddle init starts it for you)
136
131
  huddle pipe serve Run the host pipe in the foreground (debugging)
@@ -189,16 +184,6 @@ Migrate options:
189
184
  (default: docker-compose.huddle.yml next to the source)
190
185
  --force Overwrite an existing override file
191
186
 
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
-
202
187
  Firewall options:
203
188
  -i, --interactive Interactively approve/deny (list)
204
189
  --container <name> Filter by (list) / scope to (add) a container
@@ -400,18 +385,7 @@ async function main() {
400
385
  return;
401
386
  }
402
387
  if (cmd === 'pipe') {
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
- });
388
+ await (0, command_1.runPipe)({ action: sub });
415
389
  return;
416
390
  }
417
391
  if (cmd === 'migrate') {
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"));
17
16
  const protocol_1 = require("./pipe/protocol");
18
17
  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,6 +39,9 @@ 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';
42
45
  // Run a binary with an argv array — NO shell. Values that originate from config
43
46
  // (team-folder paths, which are writable via `huddle firewall folder set` and the
44
47
  // authenticated settings API) must never be interpolated into a shell string, or
@@ -188,12 +191,13 @@ async function runInit(opts, images) {
188
191
  dockerArgs.push('-e', `HUDDLE_OPERATOR_TOKEN=${operatorToken}`);
189
192
  dockerArgs.push('-p', `${HOST_PORT}:3000`);
190
193
  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}`);
191
195
  dockerArgs.push('-v', `${VOLUME}:/data`);
192
196
  dockerArgs.push('-v', `${runtime.socketPath}:/var/run/docker.sock`);
193
197
  dockerArgs.push('-v', `${hostTmpSockets}:/tmp/dc-sockets`);
194
198
  dockerArgs.push('-v', `${config_1.CONFIG_DIR}:/huddle-home:rw`, '-e', 'HUDDLE_HOME_DIR=/huddle-home');
195
199
  // Its host path, so the gateway can refuse mounts that would expose it (the
196
- // operator token in config.json, the host pipe, Huddle's SSH key) to a devcontainer.
200
+ // operator token in config.json, the host pipe) to a devcontainer or sandbox.
197
201
  dockerArgs.push('-e', `HUDDLE_HOST_HOME_DIR=${config_1.CONFIG_DIR}`);
198
202
  if (fwFolder)
199
203
  dockerArgs.push('-v', `${fwFolder}:/firewall-rules:rw`);
@@ -216,9 +220,9 @@ async function runInit(opts, images) {
216
220
  // gateway cleans that up itself (see dns-egress.ts / the startup sanitize in
217
221
  // index.ts).
218
222
  runArgsSilent(rt, ['network', 'connect', exports.INTERNAL_NET, exports.CONTAINER]);
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.
223
+ // The host pipe lets the portal browse host folders and drive host tools
224
+ // (docs/host-pipe.md). Restarting it here means it always runs the CLI that
225
+ // was just installed. It is an extra, so a failure only warns.
222
226
  const pipe = await (0, command_1.startPipeAgent)();
223
227
  if (pipe.ok) {
224
228
  console.log((0, utils_1.dim)(`Host pipe: running (pid ${pipe.pid})`));
@@ -146,6 +146,7 @@ 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'}`));
149
150
  console.log((0, utils_1.dim)(` started: ${hb.startedAt} · heartbeat ${ago(hb.updatedAt)}`));
150
151
  }
151
152
  else {
@@ -0,0 +1,157 @@
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
+ }
@@ -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.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;
11
+ exports.PipeError = exports.MAX_TOOL_TIMEOUT_MS = exports.DEFAULT_TOOL_TIMEOUT_MS = exports.MAX_OUTPUT_BYTES = exports.MAX_FOLDER_ENTRIES = 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,6 +27,10 @@ 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;
30
34
  /** Thrown by an op handler to answer with `ok:false` and a specific code. */
31
35
  class PipeError extends Error {
32
36
  code;
@@ -36,9 +40,14 @@ class PipeError extends Error {
36
40
  }
37
41
  }
38
42
  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
+ */
39
48
  /**
40
49
  * Creates the pipe folder owner-only, or makes an existing one so. Whoever can
41
- * write a request into it can make the agent set up SSH, so on POSIX it
50
+ * write a request into it can run the allowlisted host tools, so on POSIX it
42
51
  * must be ours (not a symlink) and closed to everyone else, and its parent must
43
52
  * not let anyone else swap it out. Throws when that cannot be made true. On
44
53
  * Windows a folder under the user profile is private already.
@@ -68,11 +77,6 @@ function ensurePrivateDir(dir) {
68
77
  if ((fs_1.default.statSync(dir).mode & 0o777) !== 0o700)
69
78
  fs_1.default.chmodSync(dir, 0o700);
70
79
  }
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
- */
76
80
  function writeJsonAtomic(file, data) {
77
81
  const tmp = `${file}.tmp`;
78
82
  fs_1.default.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600 });
@@ -0,0 +1,107 @@
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
+ }
@@ -0,0 +1,147 @@
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
+ }
@@ -2,7 +2,8 @@
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, writes `<id>.out` atomically and deletes the `.busy`. Every request
5
+ // without blocking the loop (a 10-minute `sbx create` must not hold up a folder
6
+ // listing), writes `<id>.out` atomically and deletes the `.busy`. Every request
6
7
  // gets a reply, a malformed one included; nothing a request contains can crash
7
8
  // the loop. See docs/host-pipe.md for the protocol.
8
9
  var __importDefault = (this && this.__importDefault) || function (mod) {
@@ -12,19 +13,37 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
13
  exports.cleanStale = cleanStale;
13
14
  exports.servePipe = servePipe;
14
15
  const fs_1 = __importDefault(require("fs"));
16
+ const os_1 = __importDefault(require("os"));
15
17
  const path_1 = __importDefault(require("path"));
16
18
  const self_update_1 = require("../self-update");
17
19
  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");
18
24
  const ssh_hosts_1 = require("./ssh-hosts");
19
25
  // Ids are generated by the gateway (32 hex); anything that does not look like
20
26
  // an id is not ours and is left alone rather than turned into a reply path.
21
27
  const REQUEST_RE = /^([A-Za-z0-9_-]{1,128})\.in$/;
22
28
  const LEFTOVER_RE = /\.(in|busy|out|tmp)$/;
23
- async function dispatch(req) {
29
+ async function dispatch(req, maxEntries) {
24
30
  const args = req.args ?? {};
25
31
  switch (req.op) {
26
32
  case 'host.info':
27
- return { platform: process.platform, version: (0, self_update_1.cliVersion)() };
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);
28
47
  case 'ssh.key':
29
48
  return (0, ssh_hosts_1.sshKey)(args);
30
49
  case 'ssh.host':
@@ -79,6 +98,7 @@ function cleanStale(dir, inFlight = new Set(), now = Date.now()) {
79
98
  }
80
99
  function servePipe(opts) {
81
100
  const { dir } = opts;
101
+ const maxEntries = opts.maxEntries ?? protocol_1.MAX_FOLDER_ENTRIES;
82
102
  const log = opts.log ?? (() => { });
83
103
  (0, protocol_1.ensurePrivateDir)(dir);
84
104
  const startedAt = new Date().toISOString();
@@ -98,7 +118,7 @@ function servePipe(opts) {
98
118
  try {
99
119
  const req = parseRequest(await fs_1.default.promises.readFile(busy, 'utf8'));
100
120
  op = req.op;
101
- reply = { ok: true, result: await dispatch(req) };
121
+ reply = { ok: true, result: await dispatch(req, maxEntries) };
102
122
  }
103
123
  catch (err) {
104
124
  reply = err instanceof protocol_1.PipeError
@@ -163,6 +183,7 @@ function servePipe(opts) {
163
183
  pid: process.pid,
164
184
  version,
165
185
  platform: process.platform,
186
+ tools: (0, tools_1.availableTools)(),
166
187
  startedAt,
167
188
  updatedAt: new Date().toISOString(),
168
189
  };
@@ -0,0 +1,227 @@
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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infosupport/huddle-cli",
3
- "version": "0.0.0-experiment-147.123.1",
3
+ "version": "0.0.0-experiment-160.124.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.",
@@ -1,167 +0,0 @@
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
- }