@infosupport/huddle-cli 0.0.0-experiment-98.52.1 → 0.0.0-experiment-109.53.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/sbx.js ADDED
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ // ── `huddle sbx` — Docker Sandboxes command group ─────────────────────────────
3
+ // Thin client: every subcommand just calls the gateway's /api/sbx/* endpoints
4
+ // (same role the rest of the CLI plays). The gateway talks to the native
5
+ // host-agent over the volume-mapped socket; nothing sbx-related runs here.
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.runSbxStatus = runSbxStatus;
41
+ exports.runSbxList = runSbxList;
42
+ exports.runSbxStart = runSbxStart;
43
+ exports.runSbxRemove = runSbxRemove;
44
+ exports.runSbxLog = runSbxLog;
45
+ exports.runSbxIngest = runSbxIngest;
46
+ exports.runSbxTrustCa = runSbxTrustCa;
47
+ exports.runSbxTrustHost = runSbxTrustHost;
48
+ exports.runSbxSshSetup = runSbxSshSetup;
49
+ exports.runSbxReconcile = runSbxReconcile;
50
+ const api_1 = require("./api");
51
+ const utils_1 = require("./utils");
52
+ function scopeLabel(scope) {
53
+ return scope.kind === 'sandbox' && scope.name ? `sandbox:${scope.name}` : 'global';
54
+ }
55
+ async function runSbxStatus() {
56
+ const s = await (0, api_1.get)('/api/sbx/status');
57
+ console.log(`Sandbox (sbx) mode`);
58
+ console.log(` host-agent socket: ${s.socket ?? (0, utils_1.dim)('(not reachable)')}`);
59
+ console.log(` upstream proxy: ${s.upstreamUrl} ${(0, utils_1.dim)(`(port ${s.proxyPort})`)}`);
60
+ if (s.available) {
61
+ console.log(` sbx: ready — ${s.version}`);
62
+ }
63
+ else {
64
+ console.log(` sbx: unavailable`);
65
+ if (s.error)
66
+ console.log((0, utils_1.dim)(` reason: ${s.error}`));
67
+ }
68
+ }
69
+ async function runSbxList() {
70
+ const { sandboxes } = await (0, api_1.get)('/api/sbx/sandboxes');
71
+ if (!sandboxes.length) {
72
+ console.log((0, utils_1.dim)('No sandboxes.'));
73
+ return;
74
+ }
75
+ const nameW = Math.max(4, ...sandboxes.map((s) => s.name.length));
76
+ console.log(`${'NAME'.padEnd(nameW)} STATUS`);
77
+ for (const s of sandboxes)
78
+ console.log(`${s.name.padEnd(nameW)} ${s.status ?? ''}`);
79
+ }
80
+ async function runSbxStart(opts) {
81
+ const body = {};
82
+ if (opts.name)
83
+ body.name = opts.name;
84
+ if (opts.agent)
85
+ body.agent = opts.agent;
86
+ // A sandbox can hold several folders: --workspace is the one the agent starts in,
87
+ // every --folder is mounted alongside it. `<path>:ro` mounts that folder
88
+ // read-only (sbx's own suffix). Huddle's settings folders are added server-side.
89
+ const folders = (opts.folders ?? []).map((f) => f.trim()).filter(Boolean);
90
+ if (folders.length) {
91
+ const first = opts.workspace ? [{ path: opts.workspace, readOnly: false }] : [];
92
+ body.workspaces = [...first, ...folders.map(parseFolderArg)];
93
+ }
94
+ else if (opts.workspace) {
95
+ body.workspace = opts.workspace;
96
+ }
97
+ const r = await (0, api_1.post)('/api/sbx/start', body);
98
+ console.log(`${r.ok ? '✓ sandbox created' : '✗ stopped at a wall'}: ${r.name}`);
99
+ console.log((0, utils_1.dim)(` upstream ${r.upstreamUrl}`));
100
+ for (const w of r.workspaces ?? [])
101
+ console.log((0, utils_1.dim)(` folder ${w.path}${w.readOnly ? ' (read-only)' : ''}`));
102
+ for (const step of r.steps) {
103
+ console.log(` ${step.code === 0 ? '✓' : '✗'} ${step.label} ${(0, utils_1.dim)(`(exit ${step.code})`)}`);
104
+ console.log((0, utils_1.dim)(` ${step.command}`));
105
+ if (step.stdout?.trim() && step.label.startsWith('link settings folders')) {
106
+ console.log((0, utils_1.dim)(` ${step.stdout.trim().split('\n').join('\n ')}`));
107
+ }
108
+ if (step.stderr.trim())
109
+ console.log((0, utils_1.dim)(` ${step.stderr.trim().split('\n').join('\n ')}`));
110
+ }
111
+ for (const s of r.settingsSkipped ?? [])
112
+ console.log((0, utils_1.dim)(` ! settings folder '${s.name}' not mounted: ${s.reason}`));
113
+ if (!r.ok)
114
+ process.exitCode = 1;
115
+ }
116
+ /** `<host path>` or `<host path>:ro` — sbx's own read-only workspace suffix. */
117
+ function parseFolderArg(raw) {
118
+ const m = /^(.*?):(ro|rw)$/i.exec(raw);
119
+ if (!m)
120
+ return { path: raw, readOnly: false };
121
+ return { path: m[1], readOnly: m[2].toLowerCase() === 'ro' };
122
+ }
123
+ async function runSbxRemove(opts) {
124
+ if (!opts.name) {
125
+ console.error('Usage: huddle sbx rm <name> [--force]');
126
+ process.exit(1);
127
+ }
128
+ const q = opts.force ? '?force=1' : '';
129
+ const r = await (0, api_1.del)(`/api/sbx/sandboxes/${encodeURIComponent(opts.name)}${q}`);
130
+ console.log(`${r.ok ? '✓ removed' : '✗ failed'}: ${r.name} ${(0, utils_1.dim)(`(exit ${r.exitCode})`)}`);
131
+ if (!r.ok)
132
+ process.exitCode = 1;
133
+ }
134
+ async function runSbxLog(opts) {
135
+ if (!opts.name) {
136
+ console.error('Usage: huddle sbx log <name>');
137
+ process.exit(1);
138
+ }
139
+ const r = await (0, api_1.get)(`/api/sbx/sandboxes/${encodeURIComponent(opts.name)}/log`);
140
+ console.log((0, utils_1.dim)('── raw `sbx policy log --json` ──'));
141
+ console.log(r.raw.trim() || (0, utils_1.dim)('(empty)'));
142
+ console.log((0, utils_1.dim)(`── parsed denied (${r.denied.length}) ──`));
143
+ for (const d of r.denied)
144
+ console.log(` ✗ ${d.domain}${d.sandbox ? (0, utils_1.dim)(' @ ' + d.sandbox) : ''}`);
145
+ if (r.denied.length === 0)
146
+ console.log((0, utils_1.dim)(' (parser matched nothing — paste the raw JSON above so the parser can be tuned)'));
147
+ }
148
+ async function runSbxIngest() {
149
+ const r = await (0, api_1.post)('/api/sbx/ingest', {});
150
+ console.log(`Ingested ${r.added} blocked request(s) from sbx → pending in Huddle.`);
151
+ }
152
+ async function runSbxTrustCa(opts) {
153
+ if (!opts.name) {
154
+ console.error('Usage: huddle sbx trust-ca <name>');
155
+ process.exit(1);
156
+ }
157
+ const r = await (0, api_1.post)(`/api/sbx/sandboxes/${encodeURIComponent(opts.name)}/trust-ca`, {});
158
+ const marker = (r.stdout || '').match(/HUDDLE_CA_INSTALLED_\w+/)?.[0];
159
+ console.log(`${r.ok ? '✓ Huddle CA installed' : '✗ CA install failed'}: ${r.name} ${(0, utils_1.dim)(`(exit ${r.code}${marker ? ', ' + marker.toLowerCase() : ''})`)}`);
160
+ if (r.stderr?.trim())
161
+ console.log((0, utils_1.dim)(` ${r.stderr.trim().split('\n').join('\n ')}`));
162
+ if (r.ok)
163
+ console.log((0, utils_1.dim)(' HTTPS from inside the sandbox now trusts Huddle — reconnect your editor.'));
164
+ else
165
+ process.exitCode = 1;
166
+ }
167
+ /**
168
+ * Trust Huddle's CA on the HOST (where the sbx daemon runs), not inside a
169
+ * sandbox. Needed because sbx terminates TLS itself for some hosts (measured:
170
+ * platform.claude.com gets a `Docker Sandboxes Proxy CA` leaf) and then
171
+ * validates Huddle's certificate against the host trust store. Without it those
172
+ * requests die as "Empty reply from server" / ECONNRESET — see sbx-host-ca.ts.
173
+ */
174
+ async function runSbxTrustHost(opts = {}) {
175
+ const { installHostCa, printHostCaResult } = await Promise.resolve().then(() => __importStar(require('./sbx-host-ca')));
176
+ console.log('Trusting Huddle’s CA on the host (for the sbx daemon)');
177
+ const r = installHostCa({ restartDaemon: 'always' });
178
+ printHostCaResult(r);
179
+ if (!r.ok)
180
+ process.exitCode = 1;
181
+ }
182
+ async function runSbxSshSetup() {
183
+ const r = await (0, api_1.post)('/api/sbx/ssh-setup', {});
184
+ if (r.ok) {
185
+ console.log('✓ SSH bridge ready. Connect an editor with:');
186
+ console.log((0, utils_1.dim)(' ssh <sandbox-name>.sbx # or add it as a VS Code / JetBrains remote host'));
187
+ }
188
+ else {
189
+ console.log(`✗ ssh setup failed (exit ${r.exitCode})`);
190
+ process.exitCode = 1;
191
+ }
192
+ }
193
+ async function runSbxReconcile(opts) {
194
+ const q = opts.dryRun ? '?dryRun=1' : '';
195
+ const r = await (0, api_1.post)(`/api/sbx/reconcile${q}`, {});
196
+ const mode = r.dryRun ? 'DRY RUN — ' : '';
197
+ if (r.error) {
198
+ console.error(`✗ ${mode}reconcile could not run: ${r.error}`);
199
+ process.exit(1);
200
+ }
201
+ console.log(`${mode}Reconcile sbx policy (allow-all per sandbox; Huddle's proxy enforces)`);
202
+ console.log(` created: ${r.created} removed: ${r.deleted} failed: ${r.failed}`);
203
+ if (r.sandboxes.length)
204
+ console.log((0, utils_1.dim)(` sandboxes: ${r.sandboxes.map((n) => 'sandbox:' + n).join(', ')}`));
205
+ for (const a of r.actions) {
206
+ const sym = a.ok ? (a.op === 'create' ? '+' : '-') : '✗';
207
+ console.log(` ${sym} ${a.op} ${a.action} ${a.target} @ ${scopeLabel(a.scope)}${a.error ? (0, utils_1.dim)(' — ' + a.error) : ''}`);
208
+ }
209
+ if (r.failed > 0)
210
+ process.exitCode = 1;
211
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infosupport/huddle-cli",
3
- "version": "0.0.0-experiment-98.52.1",
3
+ "version": "0.0.0-experiment-109.53.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,13 @@
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": {
26
27
  "@types/node": "^22.0.0",
27
- "typescript": "^5.0.0"
28
+ "typescript": "^5.0.0",
29
+ "vitest": "^4.1.8"
28
30
  },
29
31
  "engines": {
30
32
  "node": ">=18"
@@ -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
- }