@infosupport/huddle-cli 0.0.0-experiment-109.53.1 → 0.0.0-experiment-109.54.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.
@@ -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
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,16 @@ 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;
42
43
  exports.pingNode = pingNode;
43
44
  exports.waitForNode = waitForNode;
44
45
  exports.stopNode = stopNode;
46
+ exports.stopNodeAndWait = stopNodeAndWait;
45
47
  exports.startNodeDetached = startNodeDetached;
46
48
  const child_process_1 = require("child_process");
47
49
  const fs_1 = __importDefault(require("fs"));
@@ -50,6 +52,34 @@ const path_1 = __importDefault(require("path"));
50
52
  const utils_1 = require("./utils");
51
53
  const config_1 = require("./config");
52
54
  exports.DEFAULT_NODE_PORT = 24842;
55
+ /**
56
+ * The executable is an optional dependency rather than a postinstall download:
57
+ * npm selects the one package whose os/cpu fields match the host. Keep this
58
+ * mapping here, beside resolution, so adding an architecture is a deliberate
59
+ * CLI change with a test rather than an implicit package-name convention.
60
+ */
61
+ function platformNodePackageName(platform = process.platform, arch = process.arch) {
62
+ const supported = new Set(['win32-x64', 'darwin-x64', 'darwin-arm64', 'linux-x64']);
63
+ const target = `${platform}-${arch}`;
64
+ return supported.has(target) ? `@infosupport/huddle-node-${target}` : null;
65
+ }
66
+ function installedNodeEntry(cliDir, platform = process.platform, arch = process.arch) {
67
+ const pkg = platformNodePackageName(platform, arch);
68
+ if (!pkg)
69
+ return null;
70
+ const executable = platform === 'win32' ? 'huddle-node.exe' : 'huddle-node';
71
+ try {
72
+ // `npm install -g` may hoist optional dependencies beside the CLI package,
73
+ // while a regular install commonly nests them below it. Node's resolver
74
+ // knows both layouts; a hard-coded `cli/node_modules` path does not.
75
+ const manifest = require.resolve(`${pkg}/package.json`, { paths: [path_1.default.resolve(cliDir, '..')] });
76
+ const entry = path_1.default.join(path_1.default.dirname(manifest), 'bin', executable);
77
+ return fs_1.default.existsSync(entry) ? entry : null;
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ }
53
83
  // An explicitly named entry, if there is one. Resolved separately from the
54
84
  // search path on purpose: naming a build is a claim about which one to run, so
55
85
  // a missing file has to fail loudly rather than quietly starting a different
@@ -63,10 +93,43 @@ function explicitNodeEntry(opts, env = process.env) {
63
93
  function nodeEntryCandidates(cliDir) {
64
94
  // A repo checkout: cli/dist/index.js → ../../gateway/dist/index.js, and the
65
95
  // same one level up for layouts that nest the build one deeper.
66
- return [
96
+ const exe = process.platform === 'win32' ? '.exe' : '';
97
+ const candidates = [
67
98
  path_1.default.resolve(cliDir, '..', '..', 'gateway', 'dist', 'index.js'),
68
99
  path_1.default.resolve(cliDir, '..', '..', '..', 'gateway', 'dist', 'index.js'),
100
+ // A single executable, either beside the CLI or dropped in ~/.huddle by
101
+ // hand. Last, so a checkout keeps winning over a stale download when both
102
+ // exist — the layout of someone working ON Huddle, whose build is the one
103
+ // they mean.
104
+ path_1.default.resolve(cliDir, '..', '..', 'gateway', 'build', 'sea', `huddle-node${exe}`),
69
105
  ];
106
+ // A checkout takes precedence so contributors always run the code they just
107
+ // built. Installed CLI packages have no checkout sibling and take this path.
108
+ const installed = installedNodeEntry(cliDir);
109
+ if (installed)
110
+ candidates.push(installed);
111
+ candidates.push(path_1.default.join(os_1.default.homedir(), '.huddle', `huddle-node${exe}`));
112
+ return candidates;
113
+ }
114
+ /**
115
+ * How to launch a resolved entry: `node build.js`, or the file on its own.
116
+ *
117
+ * Huddle Node ships two ways (gateway/scripts/build-sea.mjs). From a checkout
118
+ * it is gateway/dist/index.js, which needs a Node to run it. Downloaded, it IS
119
+ * a Node — a single executable with the whole app injected into the binary, and
120
+ * handing that to `node` makes it argv[1] and gets the REPL, or on Windows an
121
+ * ENOEXEC. The two are not distinguishable by asking the file politely, so the
122
+ * rule is the extension the build actually produces: .js means script, anything
123
+ * else means executable.
124
+ *
125
+ * Kept separate from resolveNodeEntry() because both spawn sites need it, and
126
+ * they are 150 lines apart — the foreground `huddle node` and the detached one
127
+ * `huddle init` uses.
128
+ */
129
+ function nodeLaunch(entry) {
130
+ return entry.toLowerCase().endsWith('.js')
131
+ ? { command: process.execPath, args: [entry] }
132
+ : { command: entry, args: [] };
70
133
  }
71
134
  class MissingNodeEntryError extends Error {
72
135
  entry;
@@ -181,10 +244,13 @@ async function runNode(opts = {}) {
181
244
  process.exit(1);
182
245
  }
183
246
  if (!entry) {
184
- console.error((0, utils_1.red)('No Huddle Node build found.'));
247
+ console.error((0, utils_1.red)('No Huddle Node executable found.'));
248
+ console.error('');
249
+ console.error(' A normal npm installation includes a platform-specific Huddle Node package.');
250
+ console.error(' Reinstall the CLI to fetch its optional dependency:');
251
+ console.error((0, utils_1.cyan)(' npm install -g @infosupport/huddle-cli'));
185
252
  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:');
253
+ console.error(' In a repo checkout, build Huddle Node first:');
188
254
  console.error((0, utils_1.cyan)(' npm --prefix gateway install && npm --prefix gateway run build'));
189
255
  console.error('');
190
256
  console.error(' Or point at a build explicitly:');
@@ -192,6 +258,9 @@ async function runNode(opts = {}) {
192
258
  console.error((0, utils_1.dim)(' (or set HUDDLE_NODE_ENTRY)'));
193
259
  process.exit(1);
194
260
  }
261
+ // The SEA opens SQLite during boot. A source checkout often has ~/.huddle
262
+ // already, but `huddle node --data-dir <new path>` must work on its own too.
263
+ fs_1.default.mkdirSync(nodeDataDir(opts), { recursive: true, mode: 0o700 });
195
264
  const env = nodeEnv(opts);
196
265
  const port = env.HUDDLE_API_PORT ?? String(exports.DEFAULT_NODE_PORT);
197
266
  console.log((0, utils_1.bold)('Huddle Node') + (0, utils_1.dim)(' — control plane, on this host'));
@@ -206,7 +275,8 @@ async function runNode(opts = {}) {
206
275
  // `huddle init` uses startNodeDetached() below. stdio inherit so Huddle Node's
207
276
  // own logging is what the operator sees.
208
277
  await new Promise((resolve) => {
209
- const child = (0, child_process_1.spawn)(process.execPath, [entry], { env, stdio: 'inherit' });
278
+ const launch = nodeLaunch(entry);
279
+ const child = (0, child_process_1.spawn)(launch.command, launch.args, { env, stdio: 'inherit' });
210
280
  // Forward the signals an operator actually sends, so Ctrl-C stops Huddle
211
281
  // Node rather than orphaning it behind a dead CLI.
212
282
  const forward = (sig) => () => { try {
@@ -245,6 +315,20 @@ async function runNode(opts = {}) {
245
315
  // decides whether Huddle Node is up — see waitForNode().
246
316
  exports.NODE_PID_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.pid');
247
317
  exports.NODE_LOG_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.log');
318
+ // The control host the running Node was actually started with — see
319
+ // startNodeDetached()'s mismatch check below. Written beside the pid file
320
+ // because the two describe the same process and go stale together.
321
+ exports.NODE_CONTROL_HOST_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.control-host');
322
+ /**
323
+ * Collapse "unset" to the address nodeEnv/resolveControlAddress default to, so
324
+ * an unset request compares equal to a previous unset run instead of the empty
325
+ * string never matching anything. 127.0.0.1 is that default on both sides:
326
+ * nodeEnv() only sets HUDDLE_CONTROL_HOST when opts.controlHost is given, and
327
+ * control-address.ts's derive() falls back to the same loopback literal.
328
+ */
329
+ function normalizeControlHost(host) {
330
+ return host?.trim() || '127.0.0.1';
331
+ }
248
332
  /** The URL a HUMAN talks to Huddle Node on: printed, opened in a browser. */
249
333
  function nodeUrl(port = exports.DEFAULT_NODE_PORT) {
250
334
  return `http://localhost:${port}`;
@@ -281,6 +365,15 @@ function readNodePid() {
281
365
  return null;
282
366
  }
283
367
  }
368
+ /** The control host the running Node was actually started with, or null if unknown. */
369
+ function readNodeControlHost() {
370
+ try {
371
+ return fs_1.default.readFileSync(exports.NODE_CONTROL_HOST_FILE, 'utf8').trim() || null;
372
+ }
373
+ catch {
374
+ return null;
375
+ }
376
+ }
284
377
  /** Does the recorded pid still name a live process? Says nothing about whether it is Huddle Node. */
285
378
  function isNodePidAlive() {
286
379
  const pid = readNodePid();
@@ -343,6 +436,29 @@ async function stopNode() {
343
436
  fs_1.default.unlinkSync(exports.NODE_PID_FILE);
344
437
  }
345
438
  catch { /* nothing to clean up */ }
439
+ try {
440
+ fs_1.default.unlinkSync(exports.NODE_CONTROL_HOST_FILE);
441
+ }
442
+ catch { /* nothing to clean up */ }
443
+ return true;
444
+ }
445
+ /**
446
+ * stopNode(), then wait until Huddle Node has actually gone quiet. SIGTERM is
447
+ * not instant, and a caller about to spawn a replacement on the same port needs
448
+ * to know the old process is truly down, not merely asked to leave — otherwise
449
+ * the new one can lose the race for the port, or the old one keeps answering
450
+ * and gets mistaken for the new one. Shared by startNodeDetached()'s own
451
+ * mismatch handling and init.ts's control-channel rebind.
452
+ */
453
+ async function stopNodeAndWait(port, timeoutMs = 10_000) {
454
+ if (!(await stopNode()))
455
+ return true; // nothing was running
456
+ const deadline = Date.now() + timeoutMs;
457
+ while (await pingNode(port)) {
458
+ if (Date.now() >= deadline)
459
+ return false;
460
+ await new Promise((r) => setTimeout(r, 250));
461
+ }
346
462
  return true;
347
463
  }
348
464
  /**
@@ -350,22 +466,48 @@ async function stopNode() {
350
466
  *
351
467
  * Refuses to spawn a second one: two Huddle Nodes on one machine would both open
352
468
  * 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.
469
+ * them would own the port. If one is already answering AND bound to the control
470
+ * host this call is asking for, that one is used.
471
+ *
472
+ * That second condition matters because the API (what pingNode checks) always
473
+ * listens on loopback regardless of HUDDLE_CONTROL_HOST — so a Node started with
474
+ * a different control host still answers the ping. Reusing it anyway would hand
475
+ * the gateway a control URL nothing is listening on: it fails closed, so every
476
+ * devcontainer is denied all egress while init reports success. So a running
477
+ * Node bound to a different host than requested is stopped and replaced here,
478
+ * rather than reused — see NODE_CONTROL_HOST_FILE.
354
479
  */
355
480
  async function startNodeDetached(opts = {}) {
356
481
  const env = nodeEnv(opts);
357
482
  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
- }
483
+ const requestedControlHost = normalizeControlHost(opts.controlHost);
484
+ // Resolved before anything is stopped: if the replacement build can't be
485
+ // found, a mismatched-host Node below should be left running rather than
486
+ // killed and not replaced.
361
487
  const entry = resolveNodeEntry(opts, __dirname);
362
488
  if (!entry)
363
489
  throw new MissingNodeEntryError(nodeEntryCandidates(__dirname)[0]);
490
+ if (await pingNode(port)) {
491
+ const runningControlHost = normalizeControlHost(readNodeControlHost() ?? undefined);
492
+ if (runningControlHost === requestedControlHost) {
493
+ return { pid: readNodePid() ?? 0, entry: '(already running)', port, reused: true };
494
+ }
495
+ // Bound to a different control host than asked for: stop it and fall
496
+ // through to spawn a fresh one on the requested host, rather than silently
497
+ // reusing a process the gateway would never actually be able to reach.
498
+ if (!(await stopNodeAndWait(port))) {
499
+ throw new Error(`Huddle Node is running on the old control host (${runningControlHost}) and did not stop in time ` +
500
+ `to rebind to ${requestedControlHost}.\n` +
501
+ ` Stop it manually (pid in ${exports.NODE_PID_FILE}) and re-run.`);
502
+ }
503
+ }
364
504
  fs_1.default.mkdirSync(config_1.CONFIG_DIR, { recursive: true });
505
+ fs_1.default.mkdirSync(nodeDataDir(opts), { recursive: true, mode: 0o700 });
365
506
  // Append, not truncate: the log of the run that just failed is usually the
366
507
  // thing you need after a restart.
367
508
  const log = fs_1.default.openSync(exports.NODE_LOG_FILE, 'a');
368
- const child = (0, child_process_1.spawn)(process.execPath, [entry], {
509
+ const launch = nodeLaunch(entry);
510
+ const child = (0, child_process_1.spawn)(launch.command, launch.args, {
369
511
  env,
370
512
  detached: true,
371
513
  stdio: ['ignore', log, log],
@@ -373,8 +515,10 @@ async function startNodeDetached(opts = {}) {
373
515
  });
374
516
  child.unref();
375
517
  fs_1.default.closeSync(log);
376
- if (child.pid)
518
+ if (child.pid) {
377
519
  fs_1.default.writeFileSync(exports.NODE_PID_FILE, String(child.pid));
520
+ fs_1.default.writeFileSync(exports.NODE_CONTROL_HOST_FILE, requestedControlHost);
521
+ }
378
522
  if (!(await waitForNode(port))) {
379
523
  // Alive-but-unreachable and dead are different bugs with the same symptom,
380
524
  // and the difference is the first thing you want to know: init stops here,
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.54.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
  ],