@infosupport/huddle-cli 0.0.0-experiment-109.53.1 → 0.0.0-experiment-109.55.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
@@ -16,9 +16,16 @@ const node_1 = require("./node");
16
16
  //
17
17
  // An explicit --url or HUDDLE_URL replaces the list entirely — the operator named
18
18
  // an address, and silently talking to a different one would be worse than failing.
19
+ //
20
+ // HUDDLE_PORT, when set, still has to flow through here: it is the same env var
21
+ // `huddle init`/`huddle node` read for a custom port (init.ts's HOST_PORT), so a
22
+ // custom port that stuck for the command that started Huddle Node must also
23
+ // stick for every command that talks to it afterwards — otherwise every command
24
+ // after `HUDDLE_PORT=<n> huddle init` probes the default port and never finds it.
25
+ const port = process.env.HUDDLE_PORT?.trim() || node_1.DEFAULT_NODE_PORT;
19
26
  let candidates = (process.env.HUDDLE_URL
20
27
  ? [process.env.HUDDLE_URL]
21
- : (0, node_1.nodeProbeUrls)(node_1.DEFAULT_NODE_PORT)).map(normalizeBaseUrl);
28
+ : (0, node_1.nodeProbeUrls)(port)).map(normalizeBaseUrl);
22
29
  let baseUrl = candidates[0];
23
30
  class ApiError extends Error {
24
31
  status;
@@ -88,6 +88,10 @@ function bridgeGateway(rt, network) {
88
88
  return null;
89
89
  }
90
90
  }
91
+ /** Bracket a literal IPv6 host for use in a URL, the way every other http://host:port here does. */
92
+ function formatHost(host) {
93
+ return host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
94
+ }
91
95
  /**
92
96
  * Decide the pair (bind host, URL) from what we know about the engine. Pure —
93
97
  * the engine probing happens in bridgeGateway() above.
@@ -96,18 +100,26 @@ function resolveControlAddress(input) {
96
100
  const override = input.override?.trim();
97
101
  const bindOverride = input.bindOverride?.trim();
98
102
  const derived = derive(input);
103
+ // HUDDLE_CONTROL_HOST moves where Node binds; unless HUDDLE_NODE_CONTROL_URL
104
+ // says otherwise too, the URL handed to the gateway has to move with it. Left
105
+ // pinned to the auto-derived URL, Node ends up listening on the overridden
106
+ // host while the gateway keeps probing the stale one — and being fail-closed,
107
+ // denies every request. HUDDLE_NODE_CONTROL_URL, when given, still wins: it is
108
+ // the more specific override and may legitimately name something other than
109
+ // the bind host (a different port, a tunnel, host.docker.internal itself).
110
+ const url = override || (bindOverride ? `http://${formatHost(bindOverride)}:${input.port}` : derived.url);
99
111
  return {
100
112
  ...derived,
101
113
  bindHost: bindOverride || derived.bindHost,
102
- url: override || derived.url,
114
+ url,
103
115
  reason: override || bindOverride
104
116
  ? 'set explicitly via HUDDLE_NODE_CONTROL_URL / HUDDLE_CONTROL_HOST'
105
117
  : derived.reason,
106
118
  // Whoever set it explicitly knows their own topology better than we do.
107
119
  reachable: derived.reachable || !!override || !!bindOverride,
108
- // An explicit URL may well name something other than the alias; adding a
109
- // host entry for a name nobody asked about would be noise at best.
110
- runArgs: override ? [] : derived.runArgs,
120
+ // Either override may name something other than the alias; adding a host
121
+ // entry for a name nobody asked about would be noise at best.
122
+ runArgs: (override || bindOverride) ? [] : derived.runArgs,
111
123
  };
112
124
  }
113
125
  function derive(input) {
@@ -126,7 +138,7 @@ function derive(input) {
126
138
  if (input.gatewayIp) {
127
139
  return {
128
140
  bindHost: input.gatewayIp,
129
- url: `http://${input.gatewayIp}:${port}`,
141
+ url: `http://${formatHost(input.gatewayIp)}:${port}`,
130
142
  runArgs: [],
131
143
  reason: `native engine — the container reaches this host at ${input.gatewayIp}`,
132
144
  reachable: true,
package/dist/index.js CHANGED
@@ -207,8 +207,9 @@ Start options:
207
207
  Migrate options:
208
208
  --ca-path <path> Where the Huddle CA lands in the container
209
209
  (NODE_EXTRA_CA_CERTS; default /home/vscode/.huddle-ca.crt)
210
- --docker-socket Also wire the filtered Docker socket + DOCKER_HOST
211
- (requires gateway socket pre-provisioning; see docs)
210
+ --docker-socket Also wire the filtered Docker socket + DOCKER_HOST;
211
+ registers the container(s) with Huddle Node so the
212
+ socket exists before "docker compose up" starts them
212
213
  --output <path> Override file to write
213
214
  (default: docker-compose.huddle.yml next to the source)
214
215
  --force Overwrite an existing override file
@@ -440,15 +441,12 @@ async function main() {
440
441
  else if (subCmd === 'log') {
441
442
  await (0, sbx_1.runSbxLog)({ name: positional[2] ?? flagString(flags, 'name') });
442
443
  }
443
- else if (subCmd === 'ingest') {
444
- await (0, sbx_1.runSbxIngest)();
445
- }
446
444
  else if (subCmd === 'ssh-setup' || subCmd === 'ssh') {
447
445
  await (0, sbx_1.runSbxSshSetup)();
448
446
  }
449
447
  else {
450
448
  console.error(`Unknown sbx subcommand: ${subCmd}`);
451
- console.error('Usage: huddle sbx <status|list|start|rm|reconcile|trust-ca|trust-host|ssh-setup|log|ingest>');
449
+ console.error('Usage: huddle sbx <status|list|start|rm|reconcile|trust-ca|trust-host|ssh-setup|log>');
452
450
  process.exit(1);
453
451
  }
454
452
  return;
package/dist/init.js CHANGED
@@ -363,14 +363,9 @@ async function runInit(opts, images) {
363
363
  // Both halves are up; now prove they can see each other, before the gateway is
364
364
  // handed an address it may never reach.
365
365
  control = await verifyControlChannel(rt, IMAGE, runtime.defaultNetwork, control, async (bindHost) => {
366
- // A running Node keeps the interface it was started on, and startNodeDetached
367
- // deliberately reuses one that answers — so it has to actually stop first.
368
- await (0, node_1.stopNode)();
369
- for (let i = 0; i < 40 && (await (0, node_1.pingNode)(HOST_PORT)); i++) {
370
- await new Promise((r) => setTimeout(r, 250));
371
- }
372
- if (await (0, node_1.pingNode)(HOST_PORT))
373
- return false;
366
+ // startNodeDetached() now recognizes a running Node bound to a different
367
+ // control host than requested and stops-and-restarts it on its own
368
+ // (cli/src/node.ts) — so naming the new host here is enough.
374
369
  try {
375
370
  node = await (0, node_1.startNodeDetached)({ port: HOST_PORT, controlHost: bindHost, operatorToken, extraEnv });
376
371
  return true;
package/dist/migrate.js CHANGED
@@ -20,6 +20,7 @@ const utils_1 = require("./utils");
20
20
  const runtime_1 = require("./runtime");
21
21
  const init_1 = require("./init");
22
22
  const node_1 = require("./node");
23
+ const api_1 = require("./api");
23
24
  // ─────────────────────────────────────────────────────────────────────────────
24
25
  // Conventions
25
26
  // ─────────────────────────────────────────────────────────────────────────────
@@ -153,7 +154,7 @@ function pickHuddleNetKey(compose, markedNetwork, preferred) {
153
154
  // add the Huddle egress network + proxy env, and (with --docker-socket) mount the
154
155
  // filtered Docker socket. Any second, non-internal network is flagged as a
155
156
  // blocker — it would be an unfiltered route out that bypasses Huddle.
156
- function buildInjectedService(svc, name, compose, ctx, warnings, blockers) {
157
+ function buildInjectedService(svc, name, compose, ctx, warnings, blockers, socketContainers) {
157
158
  for (const netKey of serviceNetworkKeys(svc)) {
158
159
  if (netKey === ctx.markedNetwork)
159
160
  continue;
@@ -184,6 +185,7 @@ function buildInjectedService(svc, name, compose, ctx, warnings, blockers) {
184
185
  }
185
186
  else {
186
187
  volumes.push(`${ctx.socketDir}/${cn}:/var/run/huddle`);
188
+ socketContainers.push(cn);
187
189
  }
188
190
  }
189
191
  return injected;
@@ -219,9 +221,10 @@ function buildOverride(compose, opts = {}) {
219
221
  dockerSocket: !!opts.dockerSocket,
220
222
  };
221
223
  const overrideServices = {};
224
+ const socketContainers = [];
222
225
  for (const name of services) {
223
226
  const svc = (compose.services?.[name] ?? {});
224
- overrideServices[name] = buildInjectedService(svc, name, compose, ctx, warnings, blockers);
227
+ overrideServices[name] = buildInjectedService(svc, name, compose, ctx, warnings, blockers, socketContainers);
225
228
  }
226
229
  const override = {
227
230
  services: overrideServices,
@@ -231,7 +234,7 @@ function buildOverride(compose, opts = {}) {
231
234
  [huddleNetKey]: { external: true, name: internalNet },
232
235
  },
233
236
  };
234
- return { markedNetwork, services, override, warnings, blockers };
237
+ return { markedNetwork, services, override, warnings, blockers, socketContainers };
235
238
  }
236
239
  function tokenize(input) {
237
240
  const out = [];
@@ -641,9 +644,28 @@ async function runMigrate(opts) {
641
644
  console.log((0, utils_1.yellow)(`[!] ${hostCaPath} does not exist yet — the override mounts it. Run \`huddle init\` first.`));
642
645
  console.log();
643
646
  }
644
- printNextSteps(composeFile, outPath, caPath, hostCaPath, !!opts.dockerSocket);
647
+ // Register the socket-mounted container_names with Node NOW, before `docker
648
+ // compose up` ever runs them: the socket has to already exist inside the
649
+ // bind-mounted directory by the time the container starts, or it mounts an
650
+ // empty directory instead (see /api/docker/register-socket, api.ts). This is
651
+ // the only way Node learns about these containers at all — they carry none
652
+ // of the labels a Huddle-created devcontainer does.
653
+ if (result.socketContainers.length > 0) {
654
+ try {
655
+ await (0, api_1.post)('/api/docker/register-socket', { names: result.socketContainers });
656
+ console.log((0, utils_1.green)(`[OK] Registered filtered socket(s) for: ${result.socketContainers.join(', ')}`));
657
+ }
658
+ catch (err) {
659
+ const detail = err instanceof api_1.ApiError ? err.message : String(err);
660
+ console.log((0, utils_1.yellow)(`[!] Could not register the filtered socket with Huddle Node: ${detail}`));
661
+ console.log((0, utils_1.dim)(' Run `huddle init` (or re-run `huddle migrate --docker-socket`) once it is reachable —'));
662
+ console.log((0, utils_1.dim)(' until then the socket mount will not exist and DOCKER_HOST will point at nothing.'));
663
+ }
664
+ console.log();
665
+ }
666
+ printNextSteps(composeFile, outPath, caPath, hostCaPath);
645
667
  }
646
- function printNextSteps(composeFile, outPath, caPath, hostCaPath, dockerSocket) {
668
+ function printNextSteps(composeFile, outPath, caPath, hostCaPath) {
647
669
  const composeBase = path_1.default.basename(composeFile);
648
670
  const overrideBase = path_1.default.basename(outPath);
649
671
  console.log((0, utils_1.bold)('Next steps (this command only GENERATED the override — it did not start anything):'));
@@ -660,12 +682,5 @@ function printNextSteps(composeFile, outPath, caPath, hostCaPath, dockerSocket)
660
682
  console.log((0, utils_1.dim)(' Or start it yourself:'));
661
683
  console.log((0, utils_1.cyan)(` docker compose -f ${composeBase} -f ${overrideBase} up -d`));
662
684
  console.log();
663
- if (dockerSocket) {
664
- console.log((0, utils_1.yellow)(' Note (--docker-socket): the socket mount is GENERATED but NOT yet served.'));
665
- console.log((0, utils_1.dim)(' Huddle does not yet pre-provision the per-container filtered socket for IDE-started\n' +
666
- ' containers (issue #66 follow-up). Until it does, the mount source will not exist and\n' +
667
- ' DOCKER_HOST will point at a missing socket. Only enable this once that lands.'));
668
- console.log();
669
- }
670
685
  console.log((0, utils_1.dim)('See docs/migrate-devcontainers.md for the full guide and the marked-network convention.'));
671
686
  }
package/dist/node.js CHANGED
@@ -12,22 +12,21 @@
12
12
  // init that only survives as long as the terminal it was typed in is not an
13
13
  // init at all.
14
14
  //
15
- // PACKAGING GAP (deliberately not solved here)
16
- // This command runs an EXISTING Huddle Node build; it cannot produce one. The
17
- // published CLI ships only its own dist and has zero dependencies, while
18
- // Huddle Node needs fastify, dockerode and better-sqlite3 — the last a native
19
- // module needing prebuilds per platform. Deciding how a released Huddle Node
20
- // reaches the host (bundled in the CLI package, a separate npm package, or
21
- // extracted from the gateway image) is its own step. Until then this resolves
22
- // a local build, which is what a repo checkout and `huddle init` in dev mode
23
- // both already have.
15
+ // DELIVERY
16
+ // Published CLI packages declare one optional Huddle Node package per supported
17
+ // os/cpu. npm installs only its matching package; this file resolves its SEA
18
+ // executable without a postinstall download or a host Node runtime dependency.
19
+ // A checkout still wins, deliberately, so contributors run what they built.
24
20
  var __importDefault = (this && this.__importDefault) || function (mod) {
25
21
  return (mod && mod.__esModule) ? mod : { "default": mod };
26
22
  };
27
23
  Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.NODE_LOG_FILE = exports.NODE_PID_FILE = exports.MissingNodeEntryError = exports.DEFAULT_NODE_PORT = void 0;
24
+ exports.NODE_CONTROL_HOST_FILE = exports.NODE_LOG_FILE = exports.NODE_PID_FILE = exports.MissingNodeEntryError = exports.DEFAULT_NODE_PORT = void 0;
25
+ exports.platformNodePackageName = platformNodePackageName;
26
+ exports.installedNodeEntry = installedNodeEntry;
29
27
  exports.explicitNodeEntry = explicitNodeEntry;
30
28
  exports.nodeEntryCandidates = nodeEntryCandidates;
29
+ exports.nodeLaunch = nodeLaunch;
31
30
  exports.resolveNodeEntry = resolveNodeEntry;
32
31
  exports.nodeEnv = nodeEnv;
33
32
  exports.nodeDataDir = nodeDataDir;
@@ -35,13 +34,17 @@ exports.nodeCaDir = nodeCaDir;
35
34
  exports.readOperatorToken = readOperatorToken;
36
35
  exports.readGatewayToken = readGatewayToken;
37
36
  exports.runNode = runNode;
37
+ exports.normalizeControlHost = normalizeControlHost;
38
38
  exports.nodeUrl = nodeUrl;
39
39
  exports.nodeProbeUrls = nodeProbeUrls;
40
40
  exports.readNodePid = readNodePid;
41
+ exports.readNodeControlHost = readNodeControlHost;
41
42
  exports.isNodePidAlive = isNodePidAlive;
43
+ exports.pidLooksLikeHuddleNode = pidLooksLikeHuddleNode;
42
44
  exports.pingNode = pingNode;
43
45
  exports.waitForNode = waitForNode;
44
46
  exports.stopNode = stopNode;
47
+ exports.stopNodeAndWait = stopNodeAndWait;
45
48
  exports.startNodeDetached = startNodeDetached;
46
49
  const child_process_1 = require("child_process");
47
50
  const fs_1 = __importDefault(require("fs"));
@@ -50,6 +53,34 @@ const path_1 = __importDefault(require("path"));
50
53
  const utils_1 = require("./utils");
51
54
  const config_1 = require("./config");
52
55
  exports.DEFAULT_NODE_PORT = 24842;
56
+ /**
57
+ * The executable is an optional dependency rather than a postinstall download:
58
+ * npm selects the one package whose os/cpu fields match the host. Keep this
59
+ * mapping here, beside resolution, so adding an architecture is a deliberate
60
+ * CLI change with a test rather than an implicit package-name convention.
61
+ */
62
+ function platformNodePackageName(platform = process.platform, arch = process.arch) {
63
+ const supported = new Set(['win32-x64', 'darwin-x64', 'darwin-arm64', 'linux-x64']);
64
+ const target = `${platform}-${arch}`;
65
+ return supported.has(target) ? `@infosupport/huddle-node-${target}` : null;
66
+ }
67
+ function installedNodeEntry(cliDir, platform = process.platform, arch = process.arch) {
68
+ const pkg = platformNodePackageName(platform, arch);
69
+ if (!pkg)
70
+ return null;
71
+ const executable = platform === 'win32' ? 'huddle-node.exe' : 'huddle-node';
72
+ try {
73
+ // `npm install -g` may hoist optional dependencies beside the CLI package,
74
+ // while a regular install commonly nests them below it. Node's resolver
75
+ // knows both layouts; a hard-coded `cli/node_modules` path does not.
76
+ const manifest = require.resolve(`${pkg}/package.json`, { paths: [path_1.default.resolve(cliDir, '..')] });
77
+ const entry = path_1.default.join(path_1.default.dirname(manifest), 'bin', executable);
78
+ return fs_1.default.existsSync(entry) ? entry : null;
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
53
84
  // An explicitly named entry, if there is one. Resolved separately from the
54
85
  // search path on purpose: naming a build is a claim about which one to run, so
55
86
  // a missing file has to fail loudly rather than quietly starting a different
@@ -63,10 +94,43 @@ function explicitNodeEntry(opts, env = process.env) {
63
94
  function nodeEntryCandidates(cliDir) {
64
95
  // A repo checkout: cli/dist/index.js → ../../gateway/dist/index.js, and the
65
96
  // same one level up for layouts that nest the build one deeper.
66
- return [
97
+ const exe = process.platform === 'win32' ? '.exe' : '';
98
+ const candidates = [
67
99
  path_1.default.resolve(cliDir, '..', '..', 'gateway', 'dist', 'index.js'),
68
100
  path_1.default.resolve(cliDir, '..', '..', '..', 'gateway', 'dist', 'index.js'),
101
+ // A single executable, either beside the CLI or dropped in ~/.huddle by
102
+ // hand. Last, so a checkout keeps winning over a stale download when both
103
+ // exist — the layout of someone working ON Huddle, whose build is the one
104
+ // they mean.
105
+ path_1.default.resolve(cliDir, '..', '..', 'gateway', 'build', 'sea', `huddle-node${exe}`),
69
106
  ];
107
+ // A checkout takes precedence so contributors always run the code they just
108
+ // built. Installed CLI packages have no checkout sibling and take this path.
109
+ const installed = installedNodeEntry(cliDir);
110
+ if (installed)
111
+ candidates.push(installed);
112
+ candidates.push(path_1.default.join(os_1.default.homedir(), '.huddle', `huddle-node${exe}`));
113
+ return candidates;
114
+ }
115
+ /**
116
+ * How to launch a resolved entry: `node build.js`, or the file on its own.
117
+ *
118
+ * Huddle Node ships two ways (gateway/scripts/build-sea.mjs). From a checkout
119
+ * it is gateway/dist/index.js, which needs a Node to run it. Downloaded, it IS
120
+ * a Node — a single executable with the whole app injected into the binary, and
121
+ * handing that to `node` makes it argv[1] and gets the REPL, or on Windows an
122
+ * ENOEXEC. The two are not distinguishable by asking the file politely, so the
123
+ * rule is the extension the build actually produces: .js means script, anything
124
+ * else means executable.
125
+ *
126
+ * Kept separate from resolveNodeEntry() because both spawn sites need it, and
127
+ * they are 150 lines apart — the foreground `huddle node` and the detached one
128
+ * `huddle init` uses.
129
+ */
130
+ function nodeLaunch(entry) {
131
+ return entry.toLowerCase().endsWith('.js')
132
+ ? { command: process.execPath, args: [entry] }
133
+ : { command: entry, args: [] };
70
134
  }
71
135
  class MissingNodeEntryError extends Error {
72
136
  entry;
@@ -181,10 +245,13 @@ async function runNode(opts = {}) {
181
245
  process.exit(1);
182
246
  }
183
247
  if (!entry) {
184
- console.error((0, utils_1.red)('No Huddle Node build found.'));
248
+ console.error((0, utils_1.red)('No Huddle Node executable found.'));
249
+ console.error('');
250
+ console.error(' A normal npm installation includes a platform-specific Huddle Node package.');
251
+ console.error(' Reinstall the CLI to fetch its optional dependency:');
252
+ console.error((0, utils_1.cyan)(' npm install -g @infosupport/huddle-cli'));
185
253
  console.error('');
186
- console.error(' `huddle node` runs an existing build; it does not create one.');
187
- console.error(' In a repo checkout, build it first:');
254
+ console.error(' In a repo checkout, build Huddle Node first:');
188
255
  console.error((0, utils_1.cyan)(' npm --prefix gateway install && npm --prefix gateway run build'));
189
256
  console.error('');
190
257
  console.error(' Or point at a build explicitly:');
@@ -192,6 +259,9 @@ async function runNode(opts = {}) {
192
259
  console.error((0, utils_1.dim)(' (or set HUDDLE_NODE_ENTRY)'));
193
260
  process.exit(1);
194
261
  }
262
+ // The SEA opens SQLite during boot. A source checkout often has ~/.huddle
263
+ // already, but `huddle node --data-dir <new path>` must work on its own too.
264
+ fs_1.default.mkdirSync(nodeDataDir(opts), { recursive: true, mode: 0o700 });
195
265
  const env = nodeEnv(opts);
196
266
  const port = env.HUDDLE_API_PORT ?? String(exports.DEFAULT_NODE_PORT);
197
267
  console.log((0, utils_1.bold)('Huddle Node') + (0, utils_1.dim)(' — control plane, on this host'));
@@ -206,7 +276,8 @@ async function runNode(opts = {}) {
206
276
  // `huddle init` uses startNodeDetached() below. stdio inherit so Huddle Node's
207
277
  // own logging is what the operator sees.
208
278
  await new Promise((resolve) => {
209
- const child = (0, child_process_1.spawn)(process.execPath, [entry], { env, stdio: 'inherit' });
279
+ const launch = nodeLaunch(entry);
280
+ const child = (0, child_process_1.spawn)(launch.command, launch.args, { env, stdio: 'inherit' });
210
281
  // Forward the signals an operator actually sends, so Ctrl-C stops Huddle
211
282
  // Node rather than orphaning it behind a dead CLI.
212
283
  const forward = (sig) => () => { try {
@@ -245,6 +316,20 @@ async function runNode(opts = {}) {
245
316
  // decides whether Huddle Node is up — see waitForNode().
246
317
  exports.NODE_PID_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.pid');
247
318
  exports.NODE_LOG_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.log');
319
+ // The control host the running Node was actually started with — see
320
+ // startNodeDetached()'s mismatch check below. Written beside the pid file
321
+ // because the two describe the same process and go stale together.
322
+ exports.NODE_CONTROL_HOST_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.control-host');
323
+ /**
324
+ * Collapse "unset" to the address nodeEnv/resolveControlAddress default to, so
325
+ * an unset request compares equal to a previous unset run instead of the empty
326
+ * string never matching anything. 127.0.0.1 is that default on both sides:
327
+ * nodeEnv() only sets HUDDLE_CONTROL_HOST when opts.controlHost is given, and
328
+ * control-address.ts's derive() falls back to the same loopback literal.
329
+ */
330
+ function normalizeControlHost(host) {
331
+ return host?.trim() || '127.0.0.1';
332
+ }
248
333
  /** The URL a HUMAN talks to Huddle Node on: printed, opened in a browser. */
249
334
  function nodeUrl(port = exports.DEFAULT_NODE_PORT) {
250
335
  return `http://localhost:${port}`;
@@ -281,6 +366,15 @@ function readNodePid() {
281
366
  return null;
282
367
  }
283
368
  }
369
+ /** The control host the running Node was actually started with, or null if unknown. */
370
+ function readNodeControlHost() {
371
+ try {
372
+ return fs_1.default.readFileSync(exports.NODE_CONTROL_HOST_FILE, 'utf8').trim() || null;
373
+ }
374
+ catch {
375
+ return null;
376
+ }
377
+ }
284
378
  /** Does the recorded pid still name a live process? Says nothing about whether it is Huddle Node. */
285
379
  function isNodePidAlive() {
286
380
  const pid = readNodePid();
@@ -294,6 +388,31 @@ function isNodePidAlive() {
294
388
  return false;
295
389
  }
296
390
  }
391
+ /**
392
+ * Best-effort check that `pid` still names a Huddle Node process, not a pid the
393
+ * OS has since recycled for something unrelated. A pid file's only real
394
+ * guarantee is "this was Huddle Node's pid at the moment we wrote it" — pids
395
+ * wrap around, and once they do, isNodePidAlive() alone would say "yes, alive"
396
+ * about a completely different process. That matters twice here: stopNode()
397
+ * must not SIGTERM whatever now holds that pid, and startNodeDetached() must
398
+ * not treat an arbitrary process answering on the port as Huddle Node just
399
+ * because a stale pid file also happens to resolve to a live process.
400
+ *
401
+ * /proc/<pid>/cmdline is Linux-only. Elsewhere (macOS, Windows) this degrades
402
+ * to "assume yes" — the behavior every caller already had before this check
403
+ * existed — rather than blocking a platform that cannot answer the question.
404
+ */
405
+ function pidLooksLikeHuddleNode(pid) {
406
+ try {
407
+ const cmdline = fs_1.default.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
408
+ return cmdline.includes('huddle-node') || cmdline.includes(path_1.default.join('gateway', 'dist', 'index.js'));
409
+ }
410
+ catch {
411
+ // ENOENT means either "no /proc" (not Linux) or "pid is already gone" —
412
+ // neither is this function's to decide, so don't block the caller on it.
413
+ return true;
414
+ }
415
+ }
297
416
  /**
298
417
  * Is Huddle Node answering? /api/auth/status is the probe: it needs no operator
299
418
  * token (api.ts keeps it public so the portal can find out whether login is
@@ -333,16 +452,45 @@ async function stopNode() {
333
452
  const pid = readNodePid();
334
453
  if (pid === null)
335
454
  return false;
336
- try {
337
- process.kill(pid, 'SIGTERM');
338
- }
339
- catch {
340
- // Already gone. Clearing the pid file below is still the right cleanup.
455
+ // Guard against a stale pid file: if the OS has recycled this pid for an
456
+ // unrelated process since Huddle Node last wrote it, signaling it would kill
457
+ // that unrelated process instead of cleaning up Huddle Node. Skip straight to
458
+ // clearing the stale record rather than sending SIGTERM blind.
459
+ if (pidLooksLikeHuddleNode(pid)) {
460
+ try {
461
+ process.kill(pid, 'SIGTERM');
462
+ }
463
+ catch {
464
+ // Already gone. Clearing the pid file below is still the right cleanup.
465
+ }
341
466
  }
342
467
  try {
343
468
  fs_1.default.unlinkSync(exports.NODE_PID_FILE);
344
469
  }
345
470
  catch { /* nothing to clean up */ }
471
+ try {
472
+ fs_1.default.unlinkSync(exports.NODE_CONTROL_HOST_FILE);
473
+ }
474
+ catch { /* nothing to clean up */ }
475
+ return true;
476
+ }
477
+ /**
478
+ * stopNode(), then wait until Huddle Node has actually gone quiet. SIGTERM is
479
+ * not instant, and a caller about to spawn a replacement on the same port needs
480
+ * to know the old process is truly down, not merely asked to leave — otherwise
481
+ * the new one can lose the race for the port, or the old one keeps answering
482
+ * and gets mistaken for the new one. Shared by startNodeDetached()'s own
483
+ * mismatch handling and init.ts's control-channel rebind.
484
+ */
485
+ async function stopNodeAndWait(port, timeoutMs = 10_000) {
486
+ if (!(await stopNode()))
487
+ return true; // nothing was running
488
+ const deadline = Date.now() + timeoutMs;
489
+ while (await pingNode(port)) {
490
+ if (Date.now() >= deadline)
491
+ return false;
492
+ await new Promise((r) => setTimeout(r, 250));
493
+ }
346
494
  return true;
347
495
  }
348
496
  /**
@@ -350,22 +498,75 @@ async function stopNode() {
350
498
  *
351
499
  * Refuses to spawn a second one: two Huddle Nodes on one machine would both open
352
500
  * the same SQLite file and both hand the gateway a policy feed, and only one of
353
- * them would own the port. If one is already answering, that one is used.
501
+ * them would own the port. If one is already answering AND bound to the control
502
+ * host this call is asking for, that one is used.
503
+ *
504
+ * That second condition matters because the API (what pingNode checks) always
505
+ * listens on loopback regardless of HUDDLE_CONTROL_HOST — so a Node started with
506
+ * a different control host still answers the ping. Reusing it anyway would hand
507
+ * the gateway a control URL nothing is listening on: it fails closed, so every
508
+ * devcontainer is denied all egress while init reports success. So a running
509
+ * Node bound to a different host than requested is stopped and replaced here,
510
+ * rather than reused — see NODE_CONTROL_HOST_FILE.
354
511
  */
355
512
  async function startNodeDetached(opts = {}) {
356
513
  const env = nodeEnv(opts);
357
514
  const port = env.HUDDLE_API_PORT ?? String(exports.DEFAULT_NODE_PORT);
358
- if (await pingNode(port)) {
359
- return { pid: readNodePid() ?? 0, entry: '(already running)', port, reused: true };
360
- }
515
+ const requestedControlHost = normalizeControlHost(opts.controlHost);
516
+ // Resolved before anything is stopped: if the replacement build can't be
517
+ // found, a mismatched-host Node below should be left running rather than
518
+ // killed and not replaced.
361
519
  const entry = resolveNodeEntry(opts, __dirname);
362
520
  if (!entry)
363
521
  throw new MissingNodeEntryError(nodeEntryCandidates(__dirname)[0]);
364
- fs_1.default.mkdirSync(config_1.CONFIG_DIR, { recursive: true });
522
+ if (await pingNode(port)) {
523
+ // A 200 on the port alone is not proof it's Huddle Node: /api/auth/status
524
+ // is deliberately unauthenticated (so the portal can ask "do I need to log
525
+ // in?"), which means any local process squatting the port before Huddle
526
+ // Node started would satisfy pingNode() too. init.ts hands the operator
527
+ // token to whatever this function says is "already running", so trusting
528
+ // that alone would let a squatter collect it. Require the pid THIS CLI
529
+ // itself recorded — only it can write NODE_PID_FILE, so a squatter cannot
530
+ // forge an entry there — to still look like Huddle Node before treating
531
+ // the port as genuinely owned.
532
+ const recordedPid = readNodePid();
533
+ if (recordedPid === null || !pidLooksLikeHuddleNode(recordedPid)) {
534
+ throw new Error(`Something is already answering on port ${port}, but it does not match the Huddle Node this CLI ` +
535
+ `started (no matching pid in ${exports.NODE_PID_FILE}).\n` +
536
+ ` Refusing to treat it as Huddle Node and hand it credentials. Stop whatever is bound to that port ` +
537
+ `and re-run, or use a different port with --port.`);
538
+ }
539
+ const runningControlHost = normalizeControlHost(readNodeControlHost() ?? undefined);
540
+ if (runningControlHost === requestedControlHost) {
541
+ return { pid: readNodePid() ?? 0, entry: '(already running)', port, reused: true };
542
+ }
543
+ // Bound to a different control host than asked for: stop it and fall
544
+ // through to spawn a fresh one on the requested host, rather than silently
545
+ // reusing a process the gateway would never actually be able to reach.
546
+ if (!(await stopNodeAndWait(port))) {
547
+ throw new Error(`Huddle Node is running on the old control host (${runningControlHost}) and did not stop in time ` +
548
+ `to rebind to ${requestedControlHost}.\n` +
549
+ ` Stop it manually (pid in ${exports.NODE_PID_FILE}) and re-run.`);
550
+ }
551
+ }
552
+ fs_1.default.mkdirSync(config_1.CONFIG_DIR, { recursive: true, mode: 0o700 });
553
+ fs_1.default.mkdirSync(nodeDataDir(opts), { recursive: true, mode: 0o700 });
365
554
  // Append, not truncate: the log of the run that just failed is usually the
366
555
  // thing you need after a restart.
367
- const log = fs_1.default.openSync(exports.NODE_LOG_FILE, 'a');
368
- const child = (0, child_process_1.spawn)(process.execPath, [entry], {
556
+ //
557
+ // 0o600: this file is Huddle Node's own stdout/stderr, which can include the
558
+ // operator token (auth.ts prints it on first boot so the operator can log
559
+ // in). The mode only applies at creation, so an already-existing log from
560
+ // before this fix is re-tightened with chmod too — belt-and-suspenders
561
+ // against a background process's output otherwise landing in a
562
+ // world-readable file other local users can read the token out of.
563
+ const log = fs_1.default.openSync(exports.NODE_LOG_FILE, 'a', 0o600);
564
+ try {
565
+ fs_1.default.chmodSync(exports.NODE_LOG_FILE, 0o600);
566
+ }
567
+ catch { /* best effort, e.g. unsupported on this platform */ }
568
+ const launch = nodeLaunch(entry);
569
+ const child = (0, child_process_1.spawn)(launch.command, launch.args, {
369
570
  env,
370
571
  detached: true,
371
572
  stdio: ['ignore', log, log],
@@ -373,8 +574,10 @@ async function startNodeDetached(opts = {}) {
373
574
  });
374
575
  child.unref();
375
576
  fs_1.default.closeSync(log);
376
- if (child.pid)
577
+ if (child.pid) {
377
578
  fs_1.default.writeFileSync(exports.NODE_PID_FILE, String(child.pid));
579
+ fs_1.default.writeFileSync(exports.NODE_CONTROL_HOST_FILE, requestedControlHost);
580
+ }
378
581
  if (!(await waitForNode(port))) {
379
582
  // Alive-but-unreachable and dead are different bugs with the same symptom,
380
583
  // and the difference is the first thing you want to know: init stops here,
package/dist/sbx.js CHANGED
@@ -42,7 +42,6 @@ exports.runSbxList = runSbxList;
42
42
  exports.runSbxStart = runSbxStart;
43
43
  exports.runSbxRemove = runSbxRemove;
44
44
  exports.runSbxLog = runSbxLog;
45
- exports.runSbxIngest = runSbxIngest;
46
45
  exports.runSbxTrustCa = runSbxTrustCa;
47
46
  exports.runSbxTrustHost = runSbxTrustHost;
48
47
  exports.runSbxSshSetup = runSbxSshSetup;
@@ -145,10 +144,6 @@ async function runSbxLog(opts) {
145
144
  if (r.denied.length === 0)
146
145
  console.log((0, utils_1.dim)(' (parser matched nothing — paste the raw JSON above so the parser can be tuned)'));
147
146
  }
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
147
  async function runSbxTrustCa(opts) {
153
148
  if (!opts.name) {
154
149
  console.error('Usage: huddle sbx trust-ca <name>');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infosupport/huddle-cli",
3
- "version": "0.0.0-experiment-109.53.1",
3
+ "version": "0.0.0-experiment-109.55.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.",
@@ -31,6 +31,12 @@
31
31
  "engines": {
32
32
  "node": ">=18"
33
33
  },
34
+ "optionalDependencies": {
35
+ "@infosupport/huddle-node-darwin-arm64": "1.3.0",
36
+ "@infosupport/huddle-node-darwin-x64": "1.3.0",
37
+ "@infosupport/huddle-node-linux-x64": "1.3.0",
38
+ "@infosupport/huddle-node-win32-x64": "1.3.0"
39
+ },
34
40
  "files": [
35
41
  "dist"
36
42
  ],