@infosupport/huddle-cli 0.0.0-experiment-160.103.1 → 0.0.0-experiment-160.105.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/dist/api.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.del = exports.put = exports.post = exports.get = exports.ApiError = void 0;
4
4
  exports.setBaseUrl = setBaseUrl;
5
5
  exports.apiCall = apiCall;
6
+ exports.uploadFile = uploadFile;
6
7
  const config_1 = require("./config");
7
8
  let baseUrl = normalizeBaseUrl(process.env.HUDDLE_URL ?? 'http://localhost:3000');
8
9
  class ApiError extends Error {
@@ -21,6 +22,15 @@ async function apiCall(method, path, body) {
21
22
  const headers = {};
22
23
  if (body !== undefined)
23
24
  headers['content-type'] = 'application/json';
25
+ return send(method, path, body !== undefined ? JSON.stringify(body) : undefined, headers);
26
+ }
27
+ /** POSTs one file as multipart/form-data (field `file`), e.g. an extension zip. */
28
+ async function uploadFile(path, fileName, data) {
29
+ const form = new FormData();
30
+ form.append('file', new Blob([new Uint8Array(data)]), fileName);
31
+ return send('POST', path, form, {});
32
+ }
33
+ async function send(method, path, body, headers) {
24
34
  // Operator-auth: stuur het token als Bearer mee zodat de CLI de control-plane
25
35
  // -auth passeert. Zonder token krijgen we een 401 met een duidelijke hint.
26
36
  const token = (0, config_1.operatorToken)();
@@ -28,11 +38,7 @@ async function apiCall(method, path, body) {
28
38
  headers['authorization'] = `Bearer ${token}`;
29
39
  let res;
30
40
  try {
31
- res = await fetch(`${baseUrl}${path}`, {
32
- method,
33
- headers,
34
- body: body !== undefined ? JSON.stringify(body) : undefined,
35
- });
41
+ res = await fetch(`${baseUrl}${path}`, { method, headers, body });
36
42
  }
37
43
  catch (err) {
38
44
  const detail = err instanceof Error ? err.message : String(err);
package/dist/config.js CHANGED
@@ -139,7 +139,10 @@ let tmpSeq = 0;
139
139
  * config.
140
140
  */
141
141
  function updateConfig(patch) {
142
- fs_1.default.mkdirSync(exports.CONFIG_DIR, { recursive: true });
142
+ // The config holds the operator token: owner-only. chmod as well, because
143
+ // mkdir's mode does not tighten a directory created by an older version.
144
+ fs_1.default.mkdirSync(exports.CONFIG_DIR, { recursive: true, mode: 0o700 });
145
+ fs_1.default.chmodSync(exports.CONFIG_DIR, 0o700);
143
146
  const token = acquireLock();
144
147
  if (token === null) {
145
148
  throw new Error(`Could not lock ${CONFIG_PATH} within ${LOCK_WAIT_MS}ms — another Huddle process ` +
@@ -153,7 +156,7 @@ function updateConfig(patch) {
153
156
  if (v === undefined)
154
157
  delete next[k];
155
158
  }
156
- fs_1.default.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`);
159
+ fs_1.default.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
157
160
  fs_1.default.renameSync(tmp, CONFIG_PATH);
158
161
  return next;
159
162
  }
@@ -0,0 +1,170 @@
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.isExtensionId = exports.MAX_FOLDER_DEPTH = void 0;
7
+ exports.insideFolder = insideFolder;
8
+ exports.collectExtensionFiles = collectExtensionFiles;
9
+ exports.planInstall = planInstall;
10
+ exports.asExtensionList = asExtensionList;
11
+ exports.runExtensionList = runExtensionList;
12
+ exports.restartRuntime = restartRuntime;
13
+ exports.runExtensionInstall = runExtensionInstall;
14
+ exports.runExtensionRemove = runExtensionRemove;
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const child_process_1 = require("child_process");
18
+ const api_1 = require("./api");
19
+ const zip_1 = require("./zip");
20
+ const init_1 = require("./init");
21
+ const runtime_1 = require("./runtime");
22
+ const utils_1 = require("./utils");
23
+ const SKIPPED = new Set(['node_modules']);
24
+ exports.MAX_FOLDER_DEPTH = 32;
25
+ /** The gateway's own id rule: one lowercase path component, so it can never point outside the extensions folder. */
26
+ const isExtensionId = (id) => typeof id === 'string' && /^[a-z0-9-]+$/.test(id);
27
+ exports.isExtensionId = isExtensionId;
28
+ /** Resolves `rel` within `root` and refuses anything that lands outside it (`..`, absolute paths). */
29
+ function insideFolder(root, rel) {
30
+ const base = path_1.default.resolve(root);
31
+ const abs = path_1.default.resolve(base, rel);
32
+ if (abs !== base && !abs.startsWith(base + path_1.default.sep))
33
+ throw new Error(`${rel} is outside the extension folder`);
34
+ return abs;
35
+ }
36
+ /**
37
+ * Reads a regular file of the folder; a symlink is refused, so the zip can never carry a file from outside it.
38
+ * @param root the resolved extension folder @param rel a path relative to it, from readdir
39
+ */
40
+ function readPlainFile(root, rel) {
41
+ const abs = insideFolder(root, rel);
42
+ const stat = fs_1.default.lstatSync(abs);
43
+ if (stat.isSymbolicLink())
44
+ throw new Error(`${rel} is a symlink; extensions are packaged without symlinks`);
45
+ if (!stat.isFile())
46
+ throw new Error(`${rel} is not a regular file`);
47
+ return fs_1.default.readFileSync(abs);
48
+ }
49
+ /** Reads an extension folder into zip entries; the manifest must pass the gateway's own id rule. */
50
+ function collectExtensionFiles(dir) {
51
+ const root = path_1.default.resolve(dir);
52
+ for (const required of ['manifest.json', 'index.js']) {
53
+ if (!fs_1.default.lstatSync(insideFolder(root, required), { throwIfNoEntry: false }))
54
+ throw new Error(`${required} missing in ${root}`);
55
+ }
56
+ const manifest = JSON.parse(readPlainFile(root, 'manifest.json').toString('utf8'));
57
+ if (!(0, exports.isExtensionId)(manifest.id)) {
58
+ throw new Error(`manifest id ${JSON.stringify(manifest.id)} must be lowercase letters, digits and -`);
59
+ }
60
+ if (typeof manifest.name !== 'string' || !manifest.name)
61
+ throw new Error('manifest name is required');
62
+ readPlainFile(root, 'index.js');
63
+ const entries = [];
64
+ const walk = (rel, depth) => {
65
+ if (depth > exports.MAX_FOLDER_DEPTH)
66
+ throw new Error(`${rel} is nested deeper than ${exports.MAX_FOLDER_DEPTH} folders`);
67
+ for (const item of fs_1.default.readdirSync(insideFolder(root, rel), { withFileTypes: true })) {
68
+ if (item.name.startsWith('.') || SKIPPED.has(item.name))
69
+ continue;
70
+ const childRel = rel ? `${rel}/${item.name}` : item.name;
71
+ if (item.isSymbolicLink())
72
+ throw new Error(`${childRel} is a symlink; extensions are packaged without symlinks`);
73
+ if (item.isDirectory())
74
+ walk(childRel, depth + 1);
75
+ else if (item.isFile())
76
+ entries.push({ name: childRel, data: readPlainFile(root, childRel) });
77
+ }
78
+ };
79
+ walk('', 0);
80
+ return { manifest, entries };
81
+ }
82
+ /** An id already taken by an extension with another name is someone else's; only --force replaces it. */
83
+ function planInstall(incoming, installed, force) {
84
+ const existing = installed.find((e) => e.id === incoming.id);
85
+ if (!existing)
86
+ return { action: 'install' };
87
+ const from = existing.version ?? 'unknown';
88
+ if (existing.name !== incoming.name && !force) {
89
+ return {
90
+ action: 'refuse',
91
+ reason: `id '${incoming.id}' belongs to "${existing.name}" (v${from}), not "${incoming.name}". Use --force to replace it.`,
92
+ };
93
+ }
94
+ return { action: 'update', from };
95
+ }
96
+ /** The answer of /api/extensions, or an error when another service holds Huddle's address. */
97
+ function asExtensionList(value) {
98
+ if (!Array.isArray(value))
99
+ throw new Error('could not reach Huddle: the address answered, but not with its extensions. Check HUDDLE_URL.');
100
+ return value;
101
+ }
102
+ async function runExtensionList() {
103
+ const installed = asExtensionList(await (0, api_1.get)('/api/extensions'));
104
+ if (!installed.length) {
105
+ console.log('No extensions installed.');
106
+ return;
107
+ }
108
+ (0, utils_1.printTable)(['ID', 'NAME', 'VERSION', 'ENABLED'], installed.map((e) => [e.id, e.name, e.version ?? '-', e.enabled === false ? 'no' : 'yes']));
109
+ }
110
+ function hasHuddleContainer(rt) {
111
+ try {
112
+ (0, child_process_1.execFileSync)(rt, ['container', 'inspect', init_1.CONTAINER], { stdio: 'ignore' });
113
+ return true;
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ /**
120
+ * The engine whose huddle container gets restarted after an install. An explicit
121
+ * --runtime / HUDDLE_RUNTIME wins; otherwise the engine that actually runs the
122
+ * container. Plain auto-detection prefers Docker, so with Podman owning Huddle
123
+ * it would restart an unrelated `huddle` container (or none) and leave the new
124
+ * extension inactive.
125
+ */
126
+ function restartRuntime(explicit, hasContainer = hasHuddleContainer, detect = () => (0, runtime_1.resolveRuntime)().name) {
127
+ const requested = explicit ?? process.env.HUDDLE_RUNTIME;
128
+ if (requested !== undefined) {
129
+ // An empty value is a typo, not a request to auto-detect: probing could pick another engine's container.
130
+ if (!requested)
131
+ throw new Error('--runtime must not be empty; choose docker or podman.');
132
+ return (0, runtime_1.resolveRuntime)(requested).name;
133
+ }
134
+ const owners = ['docker', 'podman'].filter((rt) => hasContainer(rt));
135
+ if (owners.length === 1)
136
+ return owners[0];
137
+ if (owners.length === 0) {
138
+ throw new Error(`No ${init_1.CONTAINER} container found under docker or podman. Run huddle init first.`);
139
+ }
140
+ // Both commands see a huddle container: either `docker` is a Podman shim
141
+ // (one engine, detection reports podman) or two engines each run one.
142
+ if (detect() === 'podman')
143
+ return 'podman';
144
+ throw new Error(`Both docker and podman run a ${init_1.CONTAINER} container; pick one with --runtime <docker|podman>.`);
145
+ }
146
+ async function runExtensionInstall(dir, opts) {
147
+ const { manifest, entries } = collectExtensionFiles(dir);
148
+ const plan = planInstall(manifest, asExtensionList(await (0, api_1.get)('/api/extensions')), opts.force);
149
+ if (plan.action === 'refuse')
150
+ throw new Error(plan.reason);
151
+ const result = await (0, api_1.uploadFile)('/api/extensions/upload', `${manifest.id}.zip`, (0, zip_1.createZip)(entries));
152
+ const verb = plan.action === 'update' ? `Updated ${manifest.id} v${plan.from} → v${manifest.version ?? '?'}` : `Installed ${manifest.id} v${manifest.version ?? '?'}`;
153
+ console.log((0, utils_1.green)(`[OK] ${verb}`));
154
+ if (!result.restartRequired)
155
+ return;
156
+ if (!opts.restart) {
157
+ console.log((0, utils_1.yellow)('The gateway keeps running the old code until it restarts. Re-run with --restart, or restart the huddle container.'));
158
+ return;
159
+ }
160
+ const rt = restartRuntime(opts.runtime);
161
+ console.log((0, utils_1.dim)(`Restarting the gateway process (${rt} restart ${init_1.CONTAINER}); the container itself is kept.`));
162
+ (0, child_process_1.execFileSync)(rt, ['restart', init_1.CONTAINER], { stdio: 'ignore' });
163
+ console.log((0, utils_1.green)('[OK] Gateway restarted with the new extension code.'));
164
+ }
165
+ async function runExtensionRemove(id) {
166
+ if (!(0, exports.isExtensionId)(id))
167
+ throw new Error(`invalid extension id: ${id}`);
168
+ await (0, api_1.del)(`/api/extensions/${id}`);
169
+ console.log((0, utils_1.green)(`[OK] Removed ${id}`));
170
+ }
@@ -0,0 +1,60 @@
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.HOST_CODEX_INDEX_MOUNT = exports.HOST_CODEX_LOGS_MOUNT = exports.HOST_AGENT_LOGS_MOUNT = void 0;
7
+ exports.hostAgentLogsMountArgs = hostAgentLogsMountArgs;
8
+ exports.hostCodexLogsMountArgs = hostCodexLogsMountArgs;
9
+ exports.hostCodexIndexMountArgs = hostCodexIndexMountArgs;
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ /** Must match HOST_AGENT_LOGS_MOUNT in gateway/src/host-config.ts. */
13
+ exports.HOST_AGENT_LOGS_MOUNT = '/host-logs/claude/projects';
14
+ /** Must match HOST_CODEX_LOGS_MOUNT in gateway/src/host-config.ts. */
15
+ exports.HOST_CODEX_LOGS_MOUNT = '/host-logs/codex/sessions';
16
+ /** Extensions read the Codex index here; the gateway itself never opens it. */
17
+ exports.HOST_CODEX_INDEX_MOUNT = '/host-logs/codex/session_index.jsonl';
18
+ /** A real directory only: Docker follows a symlinked source, which could point the mount at ~/.claude itself. */
19
+ const isPlainDir = (p) => {
20
+ try {
21
+ return fs_1.default.lstatSync(p).isDirectory();
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ };
27
+ /**
28
+ * `docker run` args that expose the host's Claude session logs to extensions:
29
+ * only ~/.claude/projects, read-only — never ~/.claude itself, which holds credentials.
30
+ */
31
+ function hostAgentLogsMountArgs(cfg, homeDir, exists = isPlainDir) {
32
+ if (cfg.hostAgentLogs !== true)
33
+ return [];
34
+ const projects = path_1.default.join(homeDir, '.claude', 'projects');
35
+ return exists(projects) ? ['-v', `${projects}:${exports.HOST_AGENT_LOGS_MOUNT}:ro`] : [];
36
+ }
37
+ /** The same for Codex: only ~/.codex/sessions, read-only — never ~/.codex itself, which holds auth.json. */
38
+ function hostCodexLogsMountArgs(cfg, homeDir, exists = isPlainDir) {
39
+ if (cfg.hostAgentLogs !== true)
40
+ return [];
41
+ const sessions = path_1.default.join(homeDir, '.codex', 'sessions');
42
+ return exists(sessions) ? ['-v', `${sessions}:${exports.HOST_CODEX_LOGS_MOUNT}:ro`] : [];
43
+ }
44
+ /** A plain file only: a symlink or hard link here could point the mount at auth.json. */
45
+ const isPlainFile = (p) => {
46
+ try {
47
+ const stat = fs_1.default.lstatSync(p);
48
+ return stat.isFile() && stat.nlink === 1;
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ };
54
+ /** Codex keeps thread names in ~/.codex/session_index.jsonl; only that file is mounted, read-only. */
55
+ function hostCodexIndexMountArgs(cfg, homeDir, exists = isPlainFile) {
56
+ if (cfg.hostAgentLogs !== true)
57
+ return [];
58
+ const index = path_1.default.join(homeDir, '.codex', 'session_index.jsonl');
59
+ return exists(index) ? ['-v', `${index}:${exports.HOST_CODEX_INDEX_MOUNT}:ro`] : [];
60
+ }
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const api_1 = require("./api");
10
10
  const start_1 = require("./start");
11
+ const extension_1 = require("./extension");
11
12
  const firewall_1 = require("./firewall");
12
13
  const init_1 = require("./init");
13
14
  const migrate_1 = require("./migrate");
@@ -18,7 +19,7 @@ const utils_1 = require("./utils");
18
19
  const experiment_1 = require("./experiment");
19
20
  const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'ca-path', 'output', 'out', 'workspace-root']);
20
21
  const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force', 'replace']);
21
- const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'restart', 'experiment', 'migrate', 'pipe', 'help', 'version']);
22
+ const COMMANDS = new Set(['start', 'firewall', 'fw', 'extension', 'ext', 'init', 'restart', 'experiment', 'migrate', 'pipe', 'help', 'version']);
22
23
  function parseArgs(argv) {
23
24
  const positional = [];
24
25
  const flags = {};
@@ -143,6 +144,13 @@ Usage:
143
144
  huddle firewall folder set <path> Set the team-managed rules folder
144
145
  huddle firewall folder reload Re-read the team-managed rules folder
145
146
  huddle firewall folder sync Write the portal's groups back to the folder
147
+ huddle extension list List installed gateway extensions
148
+ huddle ext list Alias for extension list
149
+ huddle extension install <dir> Install or update the extension in a folder
150
+ (--force replaces another extension with the
151
+ same id, --restart reloads the gateway process
152
+ on the engine that runs Huddle, or --runtime)
153
+ huddle extension remove <id> Remove an installed extension
146
154
  huddle experiment use <nr> Activate the experimental build of issue/PR <nr>
147
155
  and run init
148
156
  huddle experiment reset Back to the stable release
@@ -163,7 +171,8 @@ Start options:
163
171
  --workspace-root <path> Container path the IDE opens as project root when using
164
172
  --mount (default: common parent of the mount targets)
165
173
  --name <name> Container name (default: devcontainer-<foldername>)
166
- --image <image> Use a specific image
174
+ --image <image> Use a specific image. Any Debian/Ubuntu/Alpine image works:
175
+ Huddle builds it once with its own layer on top
167
176
  --empty Empty container without a workspace
168
177
 
169
178
  Migrate options:
@@ -343,6 +352,38 @@ async function main() {
343
352
  }
344
353
  return;
345
354
  }
355
+ if (cmd === 'extension' || cmd === 'ext') {
356
+ const subCmd = sub ?? 'list';
357
+ if (subCmd === 'list') {
358
+ await (0, extension_1.runExtensionList)();
359
+ }
360
+ else if (subCmd === 'install') {
361
+ const dir = positional[2];
362
+ if (!dir) {
363
+ console.error('Usage: huddle extension install <dir> [--force] [--restart] [--runtime <docker|podman>]');
364
+ process.exit(1);
365
+ }
366
+ await (0, extension_1.runExtensionInstall)(dir, {
367
+ force: flagBool(flags, 'force'),
368
+ restart: flagBool(flags, 'restart'),
369
+ runtime: flagString(flags, 'runtime'),
370
+ });
371
+ }
372
+ else if (subCmd === 'remove' || subCmd === 'rm') {
373
+ const id = positional[2];
374
+ if (!id) {
375
+ console.error('Usage: huddle extension remove <id>');
376
+ process.exit(1);
377
+ }
378
+ await (0, extension_1.runExtensionRemove)(id);
379
+ }
380
+ else {
381
+ console.error(`Unknown extension subcommand: ${subCmd}`);
382
+ console.error('Usage: huddle extension <list|install <dir>|remove <id>>');
383
+ process.exit(1);
384
+ }
385
+ return;
386
+ }
346
387
  if (cmd === 'pipe') {
347
388
  await (0, command_1.runPipe)({ action: sub });
348
389
  return;
package/dist/init.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.HOST_SOCKET_DIR = exports.INTERNAL_NET = void 0;
6
+ exports.SSH_RELAY_PORTS = exports.HOST_SOCKET_DIR = exports.INTERNAL_NET = exports.CONTAINER = void 0;
7
7
  exports.runInit = runInit;
8
8
  const child_process_1 = require("child_process");
9
9
  const crypto_1 = __importDefault(require("crypto"));
@@ -11,10 +11,12 @@ const utils_1 = require("./utils");
11
11
  const runtime_1 = require("./runtime");
12
12
  const images_1 = require("./images");
13
13
  const config_1 = require("./config");
14
+ const os_1 = __importDefault(require("os"));
15
+ const host_logs_1 = require("./host-logs");
14
16
  const protocol_1 = require("./pipe/protocol");
15
17
  const command_1 = require("./pipe/command");
16
18
  const fs_1 = __importDefault(require("fs"));
17
- const CONTAINER = 'huddle';
19
+ exports.CONTAINER = 'huddle';
18
20
  const VOLUME = 'huddle-data';
19
21
  /**
20
22
  * The shared, internal network that `huddle init` creates (`--internal`, so it
@@ -31,6 +33,12 @@ exports.INTERNAL_NET = 'devcontainer-net';
31
33
  */
32
34
  exports.HOST_SOCKET_DIR = '/tmp/dc-sockets';
33
35
  const HOST_PORT = process.env.HUDDLE_PORT ?? '3000';
36
+ /**
37
+ * Ports of the per-devcontainer SSH relays (JetBrains Gateway over SSH), bound to
38
+ * the host's loopback only. Kept in sync with SSH_RELAY_PORT_MIN/MAX in
39
+ * gateway/src/ssh-access.ts.
40
+ */
41
+ exports.SSH_RELAY_PORTS = '2200-2219';
34
42
  // Host port of the gateway's sbx egress proxy (docs/host-pipe.md). Published on
35
43
  // loopback only: the sbx daemon runs on this machine, nothing else needs it.
36
44
  const SBX_PROXY_HOST_PORT = process.env.HUDDLE_SBX_PROXY_PORT ?? '32768';
@@ -99,7 +107,7 @@ async function runInit(opts, images) {
99
107
  console.log((0, utils_1.dim)(`Network: ${exports.INTERNAL_NET}`));
100
108
  runArgsSilent(rt, ['network', 'inspect', exports.INTERNAL_NET]) || runArgs(rt, ['network', 'create', '--internal', exports.INTERNAL_NET]);
101
109
  console.log((0, utils_1.dim)(`Removing old container if it exists`));
102
- runArgsSilent(rt, ['rm', '-f', CONTAINER]);
110
+ runArgsSilent(rt, ['rm', '-f', exports.CONTAINER]);
103
111
  console.log((0, utils_1.dim)(`Socket directory: /tmp/dc-sockets`));
104
112
  // The mount SOURCE must be the path on the Docker ENGINE host (on Windows:
105
113
  // the WSL2/Linux VM), even when the CLI itself runs on Windows. The gateway
@@ -167,16 +175,22 @@ async function runInit(opts, images) {
167
175
  console.log((0, utils_1.dim)(` Mounting extensions folder: ${extFolder} -> /extensions`));
168
176
  // The host pipe lives inside the ~/.huddle mount; create it now so the
169
177
  // gateway sees the folder from its first start, before the agent runs.
170
- fs_1.default.mkdirSync(protocol_1.PIPE_DIR, { recursive: true });
178
+ try {
179
+ (0, protocol_1.ensurePrivateDir)(protocol_1.PIPE_DIR);
180
+ }
181
+ catch (err) {
182
+ console.log((0, utils_1.yellow)(` Host pipe folder not usable: ${err instanceof Error ? err.message : err}`));
183
+ }
171
184
  // Build the container command as an argv array (runArgs → execFileSync, no
172
185
  // shell). The folder paths below come from config and are operator-writable via
173
186
  // the settings API, so they must never reach a shell as a string.
174
- const dockerArgs = ['run', '-d', '--name', CONTAINER, '--network', runtime.defaultNetwork];
187
+ const dockerArgs = ['run', '-d', '--name', exports.CONTAINER, '--network', runtime.defaultNetwork];
175
188
  for (const opt of runtime.securityOpts)
176
189
  dockerArgs.push('--security-opt', opt);
177
190
  dockerArgs.push('-e', `HUDDLE_RUNTIME=${runtime.name}`);
178
191
  dockerArgs.push('-e', `HUDDLE_OPERATOR_TOKEN=${operatorToken}`);
179
192
  dockerArgs.push('-p', `${HOST_PORT}:3000`);
193
+ dockerArgs.push('-p', `127.0.0.1:${exports.SSH_RELAY_PORTS}:${exports.SSH_RELAY_PORTS}`);
180
194
  dockerArgs.push('-p', `127.0.0.1:${SBX_PROXY_HOST_PORT}:3128`, '-e', `HUDDLE_SBX_PROXY_HOST_PORT=${SBX_PROXY_HOST_PORT}`);
181
195
  dockerArgs.push('-v', `${VOLUME}:/data`);
182
196
  dockerArgs.push('-v', `${runtime.socketPath}:/var/run/docker.sock`);
@@ -189,6 +203,15 @@ async function runInit(opts, images) {
189
203
  dockerArgs.push('-v', `${fwFolder}:/firewall-rules:rw`);
190
204
  if (extFolder)
191
205
  dockerArgs.push('-v', `${extFolder}:/extensions:ro`);
206
+ const hostLogs = (0, host_logs_1.hostAgentLogsMountArgs)(cfg, os_1.default.homedir());
207
+ if (hostLogs.length)
208
+ console.log((0, utils_1.dim)(' Mounting host Claude logs (read-only) for extensions'));
209
+ dockerArgs.push(...hostLogs);
210
+ const hostCodexLogs = (0, host_logs_1.hostCodexLogsMountArgs)(cfg, os_1.default.homedir());
211
+ if (hostCodexLogs.length)
212
+ console.log((0, utils_1.dim)(' Mounting host Codex logs (read-only) for extensions'));
213
+ dockerArgs.push(...hostCodexLogs);
214
+ dockerArgs.push(...(0, host_logs_1.hostCodexIndexMountArgs)(cfg, os_1.default.homedir()));
192
215
  dockerArgs.push(...(0, images_1.gatewayEnvArgs)(images));
193
216
  dockerArgs.push(IMAGE);
194
217
  runArgs(rt, dockerArgs);
@@ -196,7 +219,7 @@ async function runInit(opts, images) {
196
219
  // resolv.conf on Podman with that network's internal aardvark-DNS; the
197
220
  // gateway cleans that up itself (see dns-egress.ts / the startup sanitize in
198
221
  // index.ts).
199
- runArgsSilent(rt, ['network', 'connect', exports.INTERNAL_NET, CONTAINER]);
222
+ runArgsSilent(rt, ['network', 'connect', exports.INTERNAL_NET, exports.CONTAINER]);
200
223
  // The host pipe lets the portal browse host folders and drive host tools
201
224
  // (docs/host-pipe.md). Restarting it here means it always runs the CLI that
202
225
  // was just installed. It is an extra, so a failure only warns.
@@ -88,13 +88,13 @@ function rotateLog() {
88
88
  */
89
89
  async function startPipeAgent() {
90
90
  try {
91
- fs_1.default.mkdirSync(protocol_1.PIPE_DIR, { recursive: true });
91
+ (0, protocol_1.ensurePrivateDir)(protocol_1.PIPE_DIR);
92
92
  const old = await stopRunning();
93
93
  rotateLog();
94
94
  // dist/pipe/command.js -> dist/index.js: the entry of THIS install, not
95
95
  // whatever `huddle` resolves to on PATH.
96
96
  const entry = path_1.default.join(__dirname, '..', 'index.js');
97
- const logFd = fs_1.default.openSync(LOG_PATH, 'a');
97
+ const logFd = fs_1.default.openSync(LOG_PATH, 'a', 0o600);
98
98
  let pid;
99
99
  try {
100
100
  const child = (0, child_process_1.spawn)(process.execPath, [entry, 'pipe', 'serve'], {
@@ -9,6 +9,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  };
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
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
+ exports.ensurePrivateDir = ensurePrivateDir;
12
13
  exports.writeJsonAtomic = writeJsonAtomic;
13
14
  exports.readHeartbeat = readHeartbeat;
14
15
  exports.heartbeatFresh = heartbeatFresh;
@@ -44,9 +45,41 @@ exports.PipeError = PipeError;
44
45
  * never reads a half-written file. Rename within one folder is atomic on every
45
46
  * platform, including across the Docker bind mount.
46
47
  */
48
+ /**
49
+ * Creates the pipe folder owner-only, or makes an existing one so. Whoever can
50
+ * write a request into it can run the allowlisted host tools, so on POSIX it
51
+ * must be ours (not a symlink) and closed to everyone else, and its parent must
52
+ * not let anyone else swap it out. Throws when that cannot be made true. On
53
+ * Windows a folder under the user profile is private already.
54
+ */
55
+ function ensurePrivateDir(dir) {
56
+ fs_1.default.mkdirSync(dir, { recursive: true, mode: 0o700 });
57
+ if (process.platform === 'win32' || typeof process.getuid !== 'function')
58
+ return;
59
+ const uid = process.getuid();
60
+ const st = fs_1.default.lstatSync(dir);
61
+ if (!st.isDirectory())
62
+ throw new Error(`${dir} is not a directory (a symlink is not accepted)`);
63
+ if (st.uid !== uid)
64
+ throw new Error(`${dir} belongs to uid ${st.uid}, not to you: refusing to use it as the host pipe`);
65
+ // The parent: ours (then closed to writes by others), or root's and either not
66
+ // writable by others or sticky (like /tmp), where nobody else can rename ours.
67
+ const parent = path_1.default.dirname(dir);
68
+ const ps = fs_1.default.statSync(parent);
69
+ const pmode = ps.mode & 0o7777;
70
+ if (ps.uid === uid) {
71
+ if (pmode & 0o022)
72
+ fs_1.default.chmodSync(parent, pmode & ~0o022);
73
+ }
74
+ else if (ps.uid !== 0 || ((pmode & 0o022) && !(pmode & 0o1000))) {
75
+ throw new Error(`${parent} can be changed by other users: refusing to serve the host pipe below it`);
76
+ }
77
+ if ((fs_1.default.statSync(dir).mode & 0o777) !== 0o700)
78
+ fs_1.default.chmodSync(dir, 0o700);
79
+ }
47
80
  function writeJsonAtomic(file, data) {
48
81
  const tmp = `${file}.tmp`;
49
- fs_1.default.writeFileSync(tmp, JSON.stringify(data));
82
+ fs_1.default.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600 });
50
83
  fs_1.default.renameSync(tmp, file);
51
84
  }
52
85
  /** The heartbeat in `dir`, or null when there is none (or it is unreadable). */
@@ -89,7 +89,7 @@ function servePipe(opts) {
89
89
  const { dir } = opts;
90
90
  const maxEntries = opts.maxEntries ?? protocol_1.MAX_FOLDER_ENTRIES;
91
91
  const log = opts.log ?? (() => { });
92
- fs_1.default.mkdirSync(dir, { recursive: true });
92
+ (0, protocol_1.ensurePrivateDir)(dir);
93
93
  const startedAt = new Date().toISOString();
94
94
  const version = (0, self_update_1.cliVersion)();
95
95
  const inFlight = new Map();
@@ -134,7 +134,7 @@ function servePipe(opts) {
134
134
  catch {
135
135
  // The folder went away (e.g. ~/.huddle was removed); recreate and carry on.
136
136
  try {
137
- fs_1.default.mkdirSync(dir, { recursive: true });
137
+ (0, protocol_1.ensurePrivateDir)(dir);
138
138
  }
139
139
  catch { /* retry next tick */ }
140
140
  }
package/dist/start.js CHANGED
@@ -80,18 +80,19 @@ async function runStart(opts) {
80
80
  console.log(`Open in VS Code: ${(0, utils_1.cyan)('Dev Containers: Attach to Running Container')} -> ${(0, utils_1.bold)(result.containerName)}`);
81
81
  return;
82
82
  }
83
- console.log(`Open in JetBrains Gateway: ${(0, utils_1.cyan)('Remote Development > Dev Containers')} -> ${(0, utils_1.bold)(result.containerName)}`);
84
- await tryPrintIdeLink(result.containerName);
83
+ await tryPrintSshLink(result.containerName);
85
84
  }
86
- async function tryPrintIdeLink(containerName) {
87
- await new Promise((resolve) => setTimeout(resolve, 3000));
85
+ // Same link as the portal's Connect IDE button: sets up sshd + the localhost
86
+ // relay and returns a jetbrains-gateway:// link. Best-effort: without an SSH key
87
+ // in Settings, or on an older image, the portal button explains what is missing.
88
+ async function tryPrintSshLink(containerName) {
88
89
  try {
89
- const res = await (0, api_1.get)(`/api/docker/containers/${encodeURIComponent(containerName)}/ide-link`);
90
+ const res = await (0, api_1.get)(`/api/docker/containers/${encodeURIComponent(containerName)}/ssh-link`);
90
91
  if (res?.link)
91
- console.log((0, utils_1.dim)(`Gateway-link: ${res.link}`));
92
+ console.log(`Open in JetBrains Gateway: ${(0, utils_1.cyan)(res.link)}`);
92
93
  }
93
- catch {
94
- // The IDE link is best-effort; JetBrains may still be starting the backend.
94
+ catch (err) {
95
+ console.log((0, utils_1.dim)(`No SSH link yet (${err?.message ?? err}); use Connect IDE in the Huddle portal.`));
95
96
  }
96
97
  }
97
98
  function resolveWorkspace(workspace) {
package/dist/zip.js ADDED
@@ -0,0 +1,74 @@
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.createZip = createZip;
7
+ const zlib_1 = __importDefault(require("zlib"));
8
+ const CRC_TABLE = (() => {
9
+ const table = new Uint32Array(256);
10
+ for (let n = 0; n < 256; n++) {
11
+ let c = n;
12
+ for (let k = 0; k < 8; k++)
13
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
14
+ table[n] = c >>> 0;
15
+ }
16
+ return table;
17
+ })();
18
+ function crc32(data) {
19
+ let crc = 0xffffffff;
20
+ for (const byte of data)
21
+ crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
22
+ return (crc ^ 0xffffffff) >>> 0;
23
+ }
24
+ function assertSafeName(name) {
25
+ const segments = name.split('/');
26
+ if (!name || name.startsWith('/') || name.includes('\\') || segments.some((s) => s === '..' || s === '')) {
27
+ throw new Error(`invalid zip entry name: ${JSON.stringify(name)}`);
28
+ }
29
+ }
30
+ /** Builds a deflated zip archive with UTF-8 entry names, in the order given. */
31
+ function createZip(entries) {
32
+ const UTF8_NAMES = 0x0800;
33
+ const DEFLATE = 8;
34
+ const locals = [];
35
+ const centrals = [];
36
+ let offset = 0;
37
+ for (const entry of entries) {
38
+ assertSafeName(entry.name);
39
+ const name = Buffer.from(entry.name, 'utf8');
40
+ const packed = zlib_1.default.deflateRawSync(entry.data);
41
+ const crc = crc32(entry.data);
42
+ const local = Buffer.alloc(30);
43
+ local.writeUInt32LE(0x04034b50, 0);
44
+ local.writeUInt16LE(20, 4);
45
+ local.writeUInt16LE(UTF8_NAMES, 6);
46
+ local.writeUInt16LE(DEFLATE, 8);
47
+ local.writeUInt32LE(crc, 14);
48
+ local.writeUInt32LE(packed.length, 18);
49
+ local.writeUInt32LE(entry.data.length, 22);
50
+ local.writeUInt16LE(name.length, 26);
51
+ locals.push(local, name, packed);
52
+ const central = Buffer.alloc(46);
53
+ central.writeUInt32LE(0x02014b50, 0);
54
+ central.writeUInt16LE(20, 4);
55
+ central.writeUInt16LE(20, 6);
56
+ central.writeUInt16LE(UTF8_NAMES, 8);
57
+ central.writeUInt16LE(DEFLATE, 10);
58
+ central.writeUInt32LE(crc, 16);
59
+ central.writeUInt32LE(packed.length, 20);
60
+ central.writeUInt32LE(entry.data.length, 24);
61
+ central.writeUInt16LE(name.length, 28);
62
+ central.writeUInt32LE(offset, 42);
63
+ centrals.push(central, name);
64
+ offset += local.length + name.length + packed.length;
65
+ }
66
+ const centralDir = Buffer.concat(centrals);
67
+ const end = Buffer.alloc(22);
68
+ end.writeUInt32LE(0x06054b50, 0);
69
+ end.writeUInt16LE(entries.length, 8);
70
+ end.writeUInt16LE(entries.length, 10);
71
+ end.writeUInt32LE(centralDir.length, 12);
72
+ end.writeUInt32LE(offset, 16);
73
+ return Buffer.concat([...locals, centralDir, end]);
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infosupport/huddle-cli",
3
- "version": "0.0.0-experiment-160.103.1",
3
+ "version": "0.0.0-experiment-160.105.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.",
@@ -20,11 +20,15 @@
20
20
  "build": "tsc",
21
21
  "dev": "tsc --watch",
22
22
  "install-global": "npm run build && npm install -g .",
23
- "typecheck": "tsc --noEmit"
23
+ "typecheck": "tsc --noEmit",
24
+ "test": "vitest run"
24
25
  },
25
26
  "devDependencies": {
27
+ "@types/adm-zip": "^0.5.8",
26
28
  "@types/node": "^22.0.0",
27
- "typescript": "^5.0.0"
29
+ "adm-zip": "^0.5.18",
30
+ "typescript": "^5.0.0",
31
+ "vitest": "^4.1.11"
28
32
  },
29
33
  "engines": {
30
34
  "node": ">=18"