@infosupport/huddle-cli 0.0.0-experiment-98.51.1 → 0.0.0-experiment-98.52.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/config.js CHANGED
@@ -6,11 +6,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.CONFIG_DIR = void 0;
7
7
  exports.configPath = configPath;
8
8
  exports.readConfig = readConfig;
9
- exports.writeConfig = writeConfig;
9
+ exports.updateConfig = updateConfig;
10
10
  exports.operatorToken = operatorToken;
11
11
  exports.activeExperiment = activeExperiment;
12
12
  exports.imageTag = imageTag;
13
13
  const fs_1 = __importDefault(require("fs"));
14
+ const crypto_1 = require("crypto");
14
15
  const os_1 = __importDefault(require("os"));
15
16
  const path_1 = __importDefault(require("path"));
16
17
  exports.CONFIG_DIR = path_1.default.join(os_1.default.homedir(), '.huddle');
@@ -26,9 +27,146 @@ function readConfig() {
26
27
  return {};
27
28
  }
28
29
  }
29
- function writeConfig(config) {
30
+ // ── Cross-process locking ─────────────────────────────────────────────────────
31
+ //
32
+ // The gateway edits this same file from inside its container (the portal writes
33
+ // the folder mappings and resource defaults there, see gateway/src/host-config.ts)
34
+ // while the CLI edits it from the host. Both do a read-modify-write of the whole
35
+ // document, so without a lock whoever writes last silently reverts the other's
36
+ // change. Same protocol on both sides: exclusive create of a sibling lock file,
37
+ // which works across the bind mount that joins the two.
38
+ const LOCK_PATH = `${CONFIG_PATH}.lock`;
39
+ const LOCK_WAIT_MS = 5000; // the gateway holds it for microseconds; this is pure headroom
40
+ const LOCK_STALE_MS = 10_000; // older than this means the holder died mid-write
41
+ function sleepSync(ms) {
42
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
43
+ }
44
+ // The lock file carries the identity of its holder, not just its existence. Age
45
+ // alone is not enough to decide it may be removed: a writer that pauses past
46
+ // LOCK_STALE_MS gets its lock broken and taken over, and would then delete the
47
+ // *new* holder's lock on the way out — letting a third writer in alongside the
48
+ // second, which is exactly the clobber the lock exists to prevent. A pid would
49
+ // not do as identity: the gateway runs in a container and this CLI on the host,
50
+ // sharing the file over a bind mount, so their pid spaces are unrelated.
51
+ function lockToken() {
52
+ return `${process.pid}:${(0, crypto_1.randomUUID)()}`;
53
+ }
54
+ function readLockToken() {
55
+ try {
56
+ return fs_1.default.readFileSync(LOCK_PATH, 'utf8');
57
+ }
58
+ catch {
59
+ return null; // gone between the stat and the read
60
+ }
61
+ }
62
+ // Remove a lock left behind by a writer that was killed mid-update, but only that
63
+ // exact lock: the token and mtime are re-read right before the unlink, so a lock
64
+ // another contender has meanwhile broken and taken over is left in place.
65
+ function breakStaleLock() {
66
+ let mtimeMs;
67
+ try {
68
+ mtimeMs = fs_1.default.statSync(LOCK_PATH).mtimeMs;
69
+ }
70
+ catch {
71
+ return; // already gone
72
+ }
73
+ if (Date.now() - mtimeMs <= LOCK_STALE_MS)
74
+ return;
75
+ const token = readLockToken();
76
+ if (token === null)
77
+ return;
78
+ try {
79
+ if (readLockToken() !== token)
80
+ return;
81
+ if (fs_1.default.statSync(LOCK_PATH).mtimeMs !== mtimeMs)
82
+ return;
83
+ fs_1.default.unlinkSync(LOCK_PATH);
84
+ }
85
+ catch { /* another process got there first — just retry */ }
86
+ }
87
+ // Returns the token identifying this holder, to be handed back to releaseLock.
88
+ function acquireLock() {
89
+ const deadline = Date.now() + LOCK_WAIT_MS;
90
+ for (;;) {
91
+ const token = lockToken();
92
+ try {
93
+ const fd = fs_1.default.openSync(LOCK_PATH, 'wx');
94
+ try {
95
+ fs_1.default.writeSync(fd, token);
96
+ }
97
+ finally {
98
+ fs_1.default.closeSync(fd);
99
+ }
100
+ return token;
101
+ }
102
+ catch (err) {
103
+ if (err.code !== 'EEXIST')
104
+ return null;
105
+ breakStaleLock();
106
+ if (Date.now() >= deadline)
107
+ return null;
108
+ sleepSync(25);
109
+ }
110
+ }
111
+ }
112
+ function releaseLock(token) {
113
+ // Never unlink a lock this writer no longer owns: if it was broken as stale and
114
+ // taken over, the file belongs to the writer that is running right now.
115
+ if (readLockToken() !== token)
116
+ return;
117
+ try {
118
+ fs_1.default.unlinkSync(LOCK_PATH);
119
+ }
120
+ catch { /* already gone */ }
121
+ }
122
+ let tmpSeq = 0;
123
+ /**
124
+ * The only writer. Merges a patch into the config file, re-reading it inside the
125
+ * lock so a concurrent gateway write is preserved instead of reverted; a key set
126
+ * to `undefined` is removed from the file. There is deliberately no
127
+ * write-the-whole-document variant: every such write was a read-modify-write of
128
+ * a snapshot that could already be stale.
129
+ *
130
+ * Throws when the lock cannot be taken. Writing anyway would reintroduce exactly
131
+ * the clobber the lock exists to prevent — the gateway would have the config open
132
+ * for a read-modify-write of its own, and one of the two edits would vanish. A
133
+ * failed command the operator can retry is the better outcome; the callers below
134
+ * (`huddle init`, `huddle firewall …`, `huddle experiment …`) all abort cleanly
135
+ * because nothing has been written yet at that point.
136
+ *
137
+ * The temp file name is unique per write — a shared `.tmp` lets two writers
138
+ * truncate each other's half-written file and rename the wreckage over the real
139
+ * config.
140
+ */
141
+ function updateConfig(patch) {
30
142
  fs_1.default.mkdirSync(exports.CONFIG_DIR, { recursive: true });
31
- fs_1.default.writeFileSync(CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`);
143
+ const token = acquireLock();
144
+ if (token === null) {
145
+ throw new Error(`Could not lock ${CONFIG_PATH} within ${LOCK_WAIT_MS}ms — another Huddle process ` +
146
+ `is writing it. Nothing was changed; retry the command. If no other process is ` +
147
+ `running, remove the stale lock: rm ${LOCK_PATH}`);
148
+ }
149
+ const tmp = `${CONFIG_PATH}.${process.pid}.${tmpSeq++}.tmp`;
150
+ try {
151
+ const next = { ...readConfig(), ...patch };
152
+ for (const [k, v] of Object.entries(next)) {
153
+ if (v === undefined)
154
+ delete next[k];
155
+ }
156
+ fs_1.default.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`);
157
+ fs_1.default.renameSync(tmp, CONFIG_PATH);
158
+ return next;
159
+ }
160
+ catch (err) {
161
+ try {
162
+ fs_1.default.unlinkSync(tmp);
163
+ }
164
+ catch { /* never created, or already renamed */ }
165
+ throw err;
166
+ }
167
+ finally {
168
+ releaseLock(token);
169
+ }
32
170
  }
33
171
  /** Operator-token voor API-auth: env wint, anders uit de config. */
34
172
  function operatorToken() {
@@ -57,7 +57,7 @@ function ensureCliForChannel(relaunchArgs, opts = {}) {
57
57
  */
58
58
  async function runExperimentUse(issue, initOpts = {}) {
59
59
  const previous = (0, config_1.readConfig)();
60
- (0, config_1.writeConfig)({ ...previous, channel: 'experiment', experiment: issue });
60
+ (0, config_1.updateConfig)({ channel: 'experiment', experiment: issue });
61
61
  console.log((0, utils_1.green)(`Experiment ${issue} activated`) + (0, utils_1.dim)(` (${(0, config_1.configPath)()})`));
62
62
  const relaunchArgs = ['init', ...(initOpts.runtime ? ['--runtime', initOpts.runtime] : [])];
63
63
  try {
@@ -67,22 +67,27 @@ async function runExperimentUse(issue, initOpts = {}) {
67
67
  }
68
68
  catch (err) {
69
69
  // Activation failed → roll back the config so a subsequent `huddle init`
70
- // doesn't stay stuck on an experiment that cannot be installed.
71
- (0, config_1.writeConfig)(previous);
70
+ // doesn't stay stuck on an experiment that cannot be installed. Only the two
71
+ // keys this function set are restored; anything the gateway wrote to the
72
+ // shared file meanwhile (folder mappings, resource defaults) stays put.
73
+ try {
74
+ (0, config_1.updateConfig)({ channel: previous.channel, experiment: previous.experiment });
75
+ }
76
+ catch (rollbackErr) {
77
+ // The rollback is a courtesy; never let it mask why activation failed.
78
+ console.error((0, utils_1.dim)(`Could not roll back ${(0, config_1.configPath)()}: ${rollbackErr.message}`));
79
+ }
72
80
  throw err;
73
81
  }
74
82
  await (0, init_1.runInit)(initOpts, (0, images_1.resolveImages)());
75
83
  }
76
84
  /** Puts Huddle back on the stable release. */
77
85
  async function runExperimentReset() {
78
- const config = (0, config_1.readConfig)();
79
86
  if ((0, config_1.activeExperiment)() === undefined && cliExperiment() === undefined) {
80
87
  console.log('No experiment active; Huddle is already running on stable.');
81
88
  return;
82
89
  }
83
- delete config.experiment;
84
- config.channel = 'stable';
85
- (0, config_1.writeConfig)(config);
90
+ (0, config_1.updateConfig)({ channel: 'stable', experiment: undefined });
86
91
  console.log((0, utils_1.green)('Experiment config removed') + (0, utils_1.dim)(` (${(0, config_1.configPath)()})`));
87
92
  // If an experimental CLI is still running, this installs the stable version
88
93
  // and the new CLI restarts itself to show the status.
package/dist/firewall.js CHANGED
@@ -260,7 +260,7 @@ async function runFirewallFolder(opts) {
260
260
  throw new Error('Usage: huddle firewall folder set <path>');
261
261
  // Config-only: the gateway reads the folder at the fixed mount point the CLI
262
262
  // binds it to; there is no DB setting. Persist here and mount on restart.
263
- (0, config_1.writeConfig)({ ...(0, config_1.readConfig)(), firewallRulesFolder: path });
263
+ (0, config_1.updateConfig)({ firewallRulesFolder: path });
264
264
  console.log((0, utils_1.green)(`[OK] Firewall rules folder set to ${(0, utils_1.cyan)(path)}`));
265
265
  console.log((0, utils_1.dim)(' Run `huddle restart` to mount it into the gateway; it is then read on start & reload.'));
266
266
  return;
@@ -48,6 +48,24 @@ function parseDepth(raw) {
48
48
  }
49
49
  return n;
50
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
+ }
51
69
  // Breadth-first so a depth cut-off keeps the folders nearest the root — those are
52
70
  // the ones an operator actually mounts. Symlinks are not followed: `isDirectory()`
53
71
  // is false for a symlink entry, which also rules out a link loop.
@@ -72,6 +90,12 @@ function scan(root, depth, all) {
72
90
  if (!all && NOISE.has(e.name))
73
91
  continue;
74
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;
75
99
  folders.push(full);
76
100
  next.push(full);
77
101
  if (folders.length >= MAX_FOLDERS)
@@ -98,14 +122,14 @@ async function runIndexFolder(opts) {
98
122
  if (opts.clear) {
99
123
  // Scoped when a folder is given, so clearing one project's entries does not
100
124
  // throw away everything else that was indexed.
101
- const root = opts.path ? toPosix(path_1.default.resolve(opts.path)) : undefined;
125
+ const root = opts.path ? toPosix(resolveScanRoot(opts.path)) : undefined;
102
126
  const query = root ? `?root=${encodeURIComponent(root)}` : '';
103
127
  const res = await (0, api_1.del)(`/api/indexed-folders${query}`);
104
128
  console.log((0, utils_1.green)(`[OK] Removed ${res.removed} folder(s) from the index${root ? ` under ${(0, utils_1.cyan)(root)}` : ''}.`));
105
129
  return;
106
130
  }
107
131
  const depth = parseDepth(opts.depth);
108
- const root = path_1.default.resolve(opts.path ?? process.cwd());
132
+ const root = resolveScanRoot(opts.path);
109
133
  let stat;
110
134
  try {
111
135
  stat = fs_1.default.statSync(root);
package/dist/init.js CHANGED
@@ -140,7 +140,7 @@ async function runInit(opts, images) {
140
140
  (cfg.operatorToken && cfg.operatorToken.trim()) ||
141
141
  crypto_1.default.randomBytes(32).toString('base64url');
142
142
  if (cfg.operatorToken !== operatorToken) {
143
- (0, config_1.writeConfig)({ ...cfg, operatorToken });
143
+ (0, config_1.updateConfig)({ operatorToken });
144
144
  }
145
145
  // The container is created on the engine's default network first (with -p),
146
146
  // then joins devcontainer-net (--internal) afterwards: Docker skips the host
package/dist/migrate.js CHANGED
@@ -292,67 +292,76 @@ function rejectUnsupportedYaml(lines) {
292
292
  throw unsupportedYaml('a YAML alias (`*`)');
293
293
  }
294
294
  }
295
+ function atIndent(c, indent) {
296
+ return c.pos < c.lines.length && c.lines[c.pos].indent === indent;
297
+ }
298
+ // Cap the mutual recursion (parseNode ↔ parseMapping/parseSequence) so a deeply
299
+ // nested (malformed or hostile) compose file cannot exhaust the stack (CWE-674).
300
+ function parseNode(c, indent, depth) {
301
+ if (depth > MAX_YAML_DEPTH) {
302
+ throw new Error(`YAML nesting exceeds ${MAX_YAML_DEPTH} levels; refusing to parse this compose file.`);
303
+ }
304
+ if (c.pos >= c.lines.length || c.lines[c.pos].indent < indent)
305
+ return null;
306
+ return isSeqItem(c.lines[c.pos].text) ? parseSequence(c, indent, depth) : parseMapping(c, indent, depth);
307
+ }
308
+ function parseMapping(c, indent, depth) {
309
+ const map = {};
310
+ while (atIndent(c, indent) && !isSeqItem(c.lines[c.pos].text)) {
311
+ const { text } = c.lines[c.pos];
312
+ const colon = findKeyColon(text);
313
+ // Not a mapping line where we expected one — stop and let the caller cope.
314
+ if (colon < 0)
315
+ break;
316
+ const key = unquote(text.slice(0, colon).trim());
317
+ const rest = text.slice(colon + 1).trim();
318
+ c.pos++;
319
+ map[key] = parseMappingValue(c, rest, indent, depth);
320
+ }
321
+ return map;
322
+ }
323
+ /** The value belonging to `key:` — inline, the indented block below it, or none. */
324
+ function parseMappingValue(c, rest, indent, depth) {
325
+ if (rest !== '')
326
+ return parseScalar(rest);
327
+ if (c.pos < c.lines.length && c.lines[c.pos].indent > indent) {
328
+ return parseNode(c, c.lines[c.pos].indent, depth + 1);
329
+ }
330
+ return null;
331
+ }
332
+ function parseSequence(c, indent, depth) {
333
+ const arr = [];
334
+ while (atIndent(c, indent) && isSeqItem(c.lines[c.pos].text)) {
335
+ arr.push(parseSequenceItem(c, indent, depth));
336
+ }
337
+ return arr;
338
+ }
339
+ function parseSequenceItem(c, indent, depth) {
340
+ const line = c.lines[c.pos];
341
+ const afterDash = line.text.replace(/^-\s*/, '');
342
+ // A bare `-`: the item is the indented block on the following lines.
343
+ if (afterDash === '') {
344
+ c.pos++;
345
+ return c.pos < c.lines.length && c.lines[c.pos].indent > indent
346
+ ? parseNode(c, c.lines[c.pos].indent, depth + 1)
347
+ : null;
348
+ }
349
+ // Inline map item: "- key: value". Re-interpret the remainder as a mapping
350
+ // that starts at a virtual indent past the dash. parseMapping consumes this
351
+ // same line, so the cursor deliberately does not advance here.
352
+ if (findKeyColon(afterDash) >= 0) {
353
+ const virtualIndent = indent + (line.text.length - afterDash.length);
354
+ c.lines[c.pos] = { indent: virtualIndent, text: afterDash };
355
+ return parseMapping(c, virtualIndent, depth + 1);
356
+ }
357
+ c.pos++;
358
+ return parseScalar(afterDash);
359
+ }
295
360
  function parseYaml(input) {
296
361
  const lines = tokenize(input);
297
362
  rejectUnsupportedYaml(lines);
298
- let pos = 0;
299
- // Cap the mutual recursion (parseNode ↔ parseMapping/parseSequence) so a deeply
300
- // nested (malformed or hostile) compose file cannot exhaust the stack (CWE-674).
301
- function parseNode(indent, depth) {
302
- if (depth > MAX_YAML_DEPTH) {
303
- throw new Error(`YAML nesting exceeds ${MAX_YAML_DEPTH} levels; refusing to parse this compose file.`);
304
- }
305
- if (pos >= lines.length || lines[pos].indent < indent)
306
- return null;
307
- return isSeqItem(lines[pos].text) ? parseSequence(indent, depth) : parseMapping(indent, depth);
308
- }
309
- function parseMapping(indent, depth) {
310
- const map = {};
311
- while (pos < lines.length && lines[pos].indent === indent && !isSeqItem(lines[pos].text)) {
312
- const { text } = lines[pos];
313
- const colon = findKeyColon(text);
314
- if (colon < 0) {
315
- // Not a mapping line where we expected one — stop and let the caller cope.
316
- break;
317
- }
318
- const key = unquote(text.slice(0, colon).trim());
319
- const rest = text.slice(colon + 1).trim();
320
- pos++;
321
- if (rest !== '') {
322
- map[key] = parseScalar(rest);
323
- }
324
- else if (pos < lines.length && lines[pos].indent > indent) {
325
- map[key] = parseNode(lines[pos].indent, depth + 1);
326
- }
327
- else {
328
- map[key] = null;
329
- }
330
- }
331
- return map;
332
- }
333
- function parseSequence(indent, depth) {
334
- const arr = [];
335
- while (pos < lines.length && lines[pos].indent === indent && isSeqItem(lines[pos].text)) {
336
- const afterDash = lines[pos].text.replace(/^-\s*/, '');
337
- if (afterDash === '') {
338
- pos++;
339
- arr.push(pos < lines.length && lines[pos].indent > indent ? parseNode(lines[pos].indent, depth + 1) : null);
340
- }
341
- else if (findKeyColon(afterDash) >= 0) {
342
- // Inline map item: "- key: value". Re-interpret the remainder as a
343
- // mapping that starts at a virtual indent past the dash.
344
- const virtualIndent = indent + (lines[pos].text.length - afterDash.length);
345
- lines[pos] = { indent: virtualIndent, text: afterDash };
346
- arr.push(parseMapping(virtualIndent, depth + 1));
347
- }
348
- else {
349
- arr.push(parseScalar(afterDash));
350
- pos++;
351
- }
352
- }
353
- return arr;
354
- }
355
- const root = parseNode(lines.length ? lines[0].indent : 0, 0);
363
+ const cursor = { lines, pos: 0 };
364
+ const root = parseNode(cursor, lines.length ? lines[0].indent : 0, 0);
356
365
  return (root && typeof root === 'object' ? root : {});
357
366
  }
358
367
  function isSeqItem(text) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infosupport/huddle-cli",
3
- "version": "0.0.0-experiment-98.51.1",
3
+ "version": "0.0.0-experiment-98.52.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.",