@mmmbuto/nexuscrew 0.8.13 → 0.8.15

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.
@@ -0,0 +1,136 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const net = require('node:net');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const crypto = require('node:crypto');
8
+
9
+ const MAX_PAYLOAD = 512 * 1024;
10
+ const REQUEST_LIMIT = 256;
11
+
12
+ function runtimeDir(cfg = {}) {
13
+ const home = cfg.home || os.homedir();
14
+ return cfg.launchRuntimeDir || path.join(home, '.nexuscrew', 'run');
15
+ }
16
+
17
+ function ensureRuntimeDir(dir) {
18
+ const parent = path.dirname(dir);
19
+ try {
20
+ const parentSt = fs.lstatSync(parent);
21
+ const owned = typeof process.getuid !== 'function' || parentSt.uid === process.getuid();
22
+ if (!parentSt.isSymbolicLink() && parentSt.isDirectory() && owned && (parentSt.mode & 0o077)) {
23
+ fs.chmodSync(parent, 0o700);
24
+ }
25
+ const checked = fs.lstatSync(parent);
26
+ if (checked.isSymbolicLink() || !checked.isDirectory()
27
+ || (typeof process.getuid === 'function' && checked.uid !== process.getuid()) || (checked.mode & 0o077)) {
28
+ throw new Error('unsafe launch broker parent directory');
29
+ }
30
+ } catch (error) {
31
+ if (error.code !== 'ENOENT') throw error;
32
+ const grand = fs.lstatSync(path.dirname(parent));
33
+ if (grand.isSymbolicLink() || !grand.isDirectory()
34
+ || (typeof process.getuid === 'function' && grand.uid !== process.getuid()) || (grand.mode & 0o022)) {
35
+ throw new Error('unsafe launch broker parent root');
36
+ }
37
+ fs.mkdirSync(parent, { mode: 0o700 });
38
+ }
39
+ try {
40
+ const st = fs.lstatSync(dir);
41
+ if (st.isSymbolicLink() || !st.isDirectory()
42
+ || (typeof process.getuid === 'function' && st.uid !== process.getuid()) || (st.mode & 0o077)) {
43
+ throw new Error('unsafe launch broker directory');
44
+ }
45
+ } catch (error) {
46
+ if (error.code !== 'ENOENT') throw error;
47
+ fs.mkdirSync(dir, { mode: 0o700 });
48
+ }
49
+ }
50
+
51
+ function encodePayload(payload) {
52
+ const body = Buffer.from(JSON.stringify(payload), 'utf8');
53
+ if (!body.length || body.length > MAX_PAYLOAD) throw new Error('launch payload too large');
54
+ const head = Buffer.allocUnsafe(4); head.writeUInt32BE(body.length, 0);
55
+ return Buffer.concat([head, body]);
56
+ }
57
+
58
+ function createLaunchBroker(cfg = {}) {
59
+ const dir = runtimeDir(cfg);
60
+ let server = null;
61
+ let socketPath = '';
62
+ let starting = null;
63
+ let closed = false;
64
+ const pending = new Map();
65
+ const ttlMs = Math.max(1000, Number(cfg.launchTokenTtlMs) || 15000);
66
+
67
+ function expire(nonce) {
68
+ const entry = pending.get(nonce);
69
+ if (!entry) return;
70
+ pending.delete(nonce);
71
+ clearTimeout(entry.timer);
72
+ }
73
+
74
+ async function start() {
75
+ if (closed) throw new Error('launch broker closed');
76
+ if (server) return socketPath;
77
+ if (starting) return starting;
78
+ starting = new Promise((resolve, reject) => {
79
+ try {
80
+ ensureRuntimeDir(dir);
81
+ socketPath = path.join(dir, `launch-${process.pid}-${crypto.randomBytes(5).toString('hex')}.sock`);
82
+ } catch (error) { reject(error); return; }
83
+ server = net.createServer((socket) => {
84
+ let raw = '';
85
+ socket.setEncoding('utf8');
86
+ socket.setTimeout(3000, () => socket.destroy());
87
+ socket.on('data', (chunk) => {
88
+ raw += chunk;
89
+ if (raw.length > REQUEST_LIMIT) return socket.destroy();
90
+ const nl = raw.indexOf('\n');
91
+ if (nl === -1) return;
92
+ let nonce = '';
93
+ try { nonce = JSON.parse(raw.slice(0, nl)).nonce; } catch (_) {}
94
+ if (typeof nonce !== 'string' || !/^[a-f0-9]{64}$/.test(nonce)) return socket.destroy();
95
+ const entry = pending.get(nonce);
96
+ if (!entry || entry.expires < Date.now()) { expire(nonce); return socket.destroy(); }
97
+ // Single-use before any bytes leave this process. A second client can
98
+ // never claim the same payload, even while the first socket drains.
99
+ pending.delete(nonce); clearTimeout(entry.timer);
100
+ try { socket.end(entry.encoded); } catch (_) { socket.destroy(); }
101
+ });
102
+ });
103
+ server.once('error', (error) => {
104
+ if (!server?.listening) { server = null; starting = null; reject(error); }
105
+ });
106
+ server.listen(socketPath, () => {
107
+ try { fs.chmodSync(socketPath, 0o600); } catch (_) {}
108
+ server.unref(); starting = null; resolve(socketPath);
109
+ });
110
+ });
111
+ return starting;
112
+ }
113
+
114
+ async function issue(payload) {
115
+ const target = await start();
116
+ const nonce = crypto.randomBytes(32).toString('hex');
117
+ const entry = { encoded: encodePayload(payload), expires: Date.now() + ttlMs, timer: null };
118
+ entry.timer = setTimeout(() => expire(nonce), ttlMs);
119
+ entry.timer.unref?.();
120
+ pending.set(nonce, entry);
121
+ return { socketPath: target, nonce };
122
+ }
123
+
124
+ async function close() {
125
+ if (closed) return;
126
+ closed = true;
127
+ for (const [nonce] of pending) expire(nonce);
128
+ const active = server; server = null;
129
+ if (active) await new Promise((resolve) => active.close(() => resolve()));
130
+ try { if (socketPath) fs.unlinkSync(socketPath); } catch (_) {}
131
+ }
132
+
133
+ return { issue, close, pendingCount: () => pending.size };
134
+ }
135
+
136
+ module.exports = { createLaunchBroker, runtimeDir, ensureRuntimeDir, encodePayload, MAX_PAYLOAD };
@@ -6,6 +6,8 @@ const fs = require('node:fs');
6
6
  const path = require('node:path');
7
7
  const crypto = require('node:crypto');
8
8
  const { execFile } = require('node:child_process');
9
+ const { ENV_KEY_RE } = require('./env-key.js');
10
+ const { readCredentialStore } = require('./credentials.js');
9
11
 
10
12
  const OLLAMA_CLOUD_MODELS = Object.freeze([
11
13
  'glm-5.2', 'kimi-k2.7-code', 'deepseek-v4-pro', 'minimax-m3',
@@ -20,7 +22,6 @@ const OLLAMA_CONTEXT = Object.freeze({
20
22
  const CUSTOM_KEYS = ['displayName', 'protocol', 'baseUrl', 'envKey', 'providerId'];
21
23
  const MANAGED_KEYS = new Set(['client', 'provider', 'credentialProfile', 'model', 'permissionPolicy', ...CUSTOM_KEYS]);
22
24
  const CLIENT_LABELS = Object.freeze({ claude: 'Claude Code', codex: 'Codex', 'codex-vl': 'Codex-VL', pi: 'Pi' });
23
- const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
24
25
  const PROVIDER_ID_RE = /^[a-z][a-z0-9_-]{0,31}$/;
25
26
 
26
27
  function validBaseUrl(value) {
@@ -149,17 +150,44 @@ function parseAssignments(raw) {
149
150
  if ((v.startsWith("'") && v.endsWith("'")) || (v.startsWith('"') && v.endsWith('"'))) v = v.slice(1, -1);
150
151
  // This is a data parser, not a shell. Reject syntax that would have a
151
152
  // different meaning if sourced instead of treating it as a credential.
152
- if (/\$\(|`|\x00|\r|\n/.test(v)) continue;
153
+ if (/\$\(|`|\x00|\r|\n|\$(?:\{[A-Za-z_][A-Za-z0-9_]*\}|[A-Za-z_][A-Za-z0-9_]*)/.test(v)) continue;
153
154
  out[m[1]] = v;
154
155
  }
155
156
  return out;
156
157
  }
157
158
 
158
- function parseEnvFile(file) {
159
+ function insideRoot(root, target) {
160
+ const relative = path.relative(root, target);
161
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
162
+ }
163
+
164
+ function safeAllowedRoots(roots = []) {
165
+ const out = [];
166
+ for (const root of roots) {
167
+ try {
168
+ const st = fs.lstatSync(root);
169
+ if (st.isSymbolicLink() || !st.isDirectory() || (st.mode & 0o022)) continue;
170
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) continue;
171
+ out.push(fs.realpathSync(root));
172
+ } catch (_) {}
173
+ }
174
+ return out;
175
+ }
176
+
177
+ function parseEnvFile(file, opts = {}) {
159
178
  try {
160
- const st = fs.lstatSync(file);
179
+ const lst = fs.lstatSync(file);
180
+ let target = file;
181
+ if (lst.isSymbolicLink()) {
182
+ const roots = safeAllowedRoots(opts.allowSymlinkRoots);
183
+ if (!roots.length) return {};
184
+ target = fs.realpathSync(file);
185
+ if (!roots.some((root) => insideRoot(root, target))) return {};
186
+ }
187
+ const st = fs.lstatSync(target);
161
188
  if (!st.isFile() || st.isSymbolicLink() || (st.mode & 0o077) || st.size > 256 * 1024) return {};
162
- return parseAssignments(fs.readFileSync(file, 'utf8'));
189
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) return {};
190
+ return parseAssignments(fs.readFileSync(target, 'utf8'));
163
191
  } catch (_) { return {}; }
164
192
  }
165
193
 
@@ -222,24 +250,54 @@ function shellProvidersPath(cfg, home) {
222
250
  || path.join(home, '.config', 'ai-shell', 'providers.zsh');
223
251
  }
224
252
 
253
+ function providerKeyPaths(cfg, home) {
254
+ const paths = [
255
+ cfg.providerKeysPath || process.env.NEXUSCREW_PROVIDER_KEYS
256
+ || path.join(home, '.config', 'keys', 'ai.env'),
257
+ cfg.providerSecurePath || process.env.NEXUSCREW_PROVIDER_SECURE
258
+ || path.join(home, '.config', 'secure', '.env'),
259
+ ];
260
+ return [...new Set(paths.filter((file) => typeof file === 'string' && file))];
261
+ }
262
+
263
+ function parseProviderKeyFiles(cfg, home) {
264
+ const values = {};
265
+ // Match providers.zsh ordering: a later secure file may intentionally
266
+ // override the canonical ai.env value. Files remain data-only and must be
267
+ // private regular files owned by the NexusCrew user.
268
+ const files = providerKeyPaths(cfg, home);
269
+ const roots = [...new Set(files.map((file) => path.dirname(path.resolve(file))))];
270
+ for (const file of files) Object.assign(values, parseEnvFile(file, { allowSymlinkRoots: roots }));
271
+ return values;
272
+ }
273
+
225
274
  function credentialSources(cfg, home) {
275
+ let local = {};
276
+ try { local = readCredentialStore(cfg, home); } catch (_) { /* unsafe/corrupt store is ignored, never trusted */ }
226
277
  return {
227
278
  runtime: cfg.env || process.env,
279
+ local,
228
280
  shell: parseProviderShellFile(shellProvidersPath(cfg, home)),
281
+ keys: parseProviderKeyFiles(cfg, home),
229
282
  legacy: parseEnvFile(secretsPath(cfg, home)),
230
283
  };
231
284
  }
232
285
 
233
286
  function credential(profile, spec, cfg, home) {
234
- if (profile.auth === 'login' || profile.auth === 'none') return { envKey: profile.auth, value: '' };
287
+ if (profile.auth === 'login' || profile.auth === 'none') return { envKey: profile.auth, value: '', source: profile.auth };
235
288
  const envKey = profile.auth === 'dynamic' ? spec.envKey : profile.auth;
236
289
  const sources = credentialSources(cfg, home);
237
290
  // The fixed shell file is already the user's environment source. Values are
238
291
  // consumed only in memory and passed to the selected child; never persisted
239
292
  // in fleet.json, service files, API responses or logs.
240
- let value = sources.runtime[envKey] || sources.shell[envKey] || '';
241
- if (!value && profile.legacySecrets) value = sources.legacy[envKey] || '';
242
- return { envKey, value };
293
+ if (sources.runtime[envKey]) return { envKey, value: sources.runtime[envKey], source: 'environment' };
294
+ if (sources.local[envKey]) return { envKey, value: sources.local[envKey], source: 'local' };
295
+ if (sources.shell[envKey]) return { envKey, value: sources.shell[envKey], source: 'compatibility' };
296
+ if (sources.keys[envKey]) return { envKey, value: sources.keys[envKey], source: 'compatibility' };
297
+ if (profile.legacySecrets && sources.legacy[envKey]) {
298
+ return { envKey, value: sources.legacy[envKey], source: 'compatibility' };
299
+ }
300
+ return { envKey, value: '', source: 'missing' };
243
301
  }
244
302
 
245
303
  let ollamaCache = { at: 0, models: [] };
@@ -252,7 +310,8 @@ async function discoverOllamaModels(opts = {}) {
252
310
  const home = opts.home || require('node:os').homedir();
253
311
  const sources = credentialSources(opts, home);
254
312
  const apiKey = opts.apiKey || sources.runtime.OLLAMA_API_KEY
255
- || sources.shell.OLLAMA_API_KEY || sources.legacy.OLLAMA_API_KEY;
313
+ || sources.local.OLLAMA_API_KEY || sources.shell.OLLAMA_API_KEY || sources.keys.OLLAMA_API_KEY
314
+ || sources.legacy.OLLAMA_API_KEY;
256
315
  if (!apiKey) throw new Error('OLLAMA_API_KEY missing');
257
316
  const response = await fetchImpl('https://ollama.com/api/tags', { headers: { authorization: `Bearer ${apiKey}` }, signal: AbortSignal.timeout?.(2500) });
258
317
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -320,9 +379,12 @@ function describeManaged(spec, cfg = {}) {
320
379
  credentialProfile: normalized.credentialProfile || '', model: normalized.model,
321
380
  permissionPolicy: normalized.permissionPolicy, protocol: normalized.protocol || profile.protocol,
322
381
  endpoint: normalized.baseUrl || profile.endpoint || '', auth: cred.envKey, authConfigured,
382
+ credentialSource: authConfigured ? cred.source : 'missing',
323
383
  configured: !!binary && authConfigured, models: [...(profile.models || [])], defaultModel: profile.model || '',
324
384
  binary: binary || '', displayName: normalized.displayName || profile.label,
325
- reason: !binary ? `client ${profile.client} not found` : (!authConfigured ? `environment variable ${cred.envKey} missing` : 'ready'),
385
+ reason: !binary ? `client ${profile.client} not found` : (!authConfigured
386
+ ? `credential ${cred.envKey} missing — set it on this device`
387
+ : 'ready'),
326
388
  };
327
389
  }
328
390
 
@@ -469,4 +531,5 @@ module.exports = {
469
531
  CATALOG, OLLAMA_CLOUD_MODELS, OLLAMA_CONTEXT, CLIENT_LABELS, normalizeManagedSpec,
470
532
  defaultDefinitions, describeManaged, discoverOllamaModels, resolveManagedEngine, needsExplicitNode,
471
533
  discoverPiModels, parseEnvFile, parseProviderShellFile, findBinary, publicCatalog, writePiProviderExtension,
534
+ providerKeyPaths, parseProviderKeyFiles, credentialSources, credential, ENV_KEY_RE,
472
535
  };
@@ -106,6 +106,16 @@ function fleetRoutes(fleetP, cfg = {}) {
106
106
  // Ogni route negozia la capability del provider: mancante → 501 (§9c).
107
107
  r.get('/schema', guard((f) => { requireCap(f, 'schema'); return f.schema(); }));
108
108
  r.get('/definitions', guard((f) => { requireCap(f, 'definitions'); return f.definitions(); }));
109
+ r.get('/credentials/status', guard((f) => {
110
+ requireCap(f, 'credentials'); return f.credentialStatus();
111
+ }));
112
+ r.post('/credentials/set', guard((f, b) => {
113
+ requireCap(f, 'credentials');
114
+ return f.setLocalCredential(String(b.envKey || ''), typeof b.value === 'string' ? b.value : '');
115
+ }, { mutate: true }));
116
+ r.post('/credentials/remove', guard((f, b) => {
117
+ requireCap(f, 'credentials'); return f.removeLocalCredential(String(b.envKey || ''));
118
+ }, { mutate: true }));
109
119
  r.post('/define-engine', guard((f, b) => { requireCap(f, 'define'); return f.defineEngine(b.def); }, { mutate: true }));
110
120
  r.post('/edit-engine', guard((f, b) => { requireCap(f, 'edit'); return f.editEngine(b.id, b.patch, b.envChanges); }, { mutate: true }));
111
121
  r.post('/remove-engine', guard((f, b) => { requireCap(f, 'remove'); return f.removeEngine(b.id); }, { mutate: true }));
@@ -198,21 +198,29 @@ function capabilityProbeMaterial(capability, randomBytes = crypto.randomBytes) {
198
198
  // restart negoziato. Oltre alla reachability verifica prova capability e
199
199
  // instanceId atteso. Bounded, con sleep/random iniettabili per test.
200
200
  async function probeTransportReady({
201
- port, capability, expectedInstanceId, fetchImpl = fetch, attempts = 6,
202
- timeoutMs = 1500, sleep, randomBytes,
201
+ port, capability, expectedInstanceId, fetchImpl = fetch, attempts = 16,
202
+ timeoutMs = 1500, deadlineMs = 20000, sleep, randomBytes, now = Date.now,
203
203
  } = {}) {
204
204
  const wait = typeof sleep === 'function' ? sleep : (ms) => new Promise((r) => setTimeout(r, ms));
205
205
  const material = capabilityProbeMaterial(capability, randomBytes);
206
206
  if (!store.isPort(port) || !material || !store.NODE_ID_RE.test(String(expectedInstanceId || ''))) {
207
207
  return { ready: false, attempts: 0, code: 'identity-probe-invalid', lastError: 'parametri identity probe non validi' };
208
208
  }
209
+ const maxAttempts = Number.isInteger(attempts) && attempts > 0 ? Math.min(attempts, 32) : 16;
210
+ const boundedDeadlineMs = Number.isFinite(deadlineMs) && deadlineMs > 0
211
+ ? Math.min(Math.floor(deadlineMs), 60000) : 20000;
212
+ const startedAt = now();
213
+ const deadlineAt = startedAt + boundedDeadlineMs;
209
214
  let lastError = '';
210
215
  let code = 'transport-not-ready';
211
- for (let i = 0; i < attempts; i += 1) {
216
+ let attempted = 0;
217
+ for (let i = 0; i < maxAttempts && now() < deadlineAt; i += 1) {
218
+ attempted += 1;
212
219
  let timer;
213
220
  try {
214
221
  const ctrl = new AbortController();
215
- timer = setTimeout(() => ctrl.abort(), timeoutMs);
222
+ const remainingMs = Math.max(1, deadlineAt - now());
223
+ timer = setTimeout(() => ctrl.abort(), Math.min(timeoutMs, remainingMs));
216
224
  const response = await fetchImpl(`http://127.0.0.1:${port}/pair/identity`, {
217
225
  method: 'POST',
218
226
  headers: { 'content-type': 'application/json' },
@@ -238,15 +246,24 @@ async function probeTransportReady({
238
246
  code = 'identity-proof-invalid';
239
247
  throw new Error('prova crittografica del peer non valida');
240
248
  }
241
- return { ready: true, attempts: i + 1, instanceId: body.instanceId };
249
+ return { ready: true, attempts: attempted, instanceId: body.instanceId, elapsedMs: Math.max(0, now() - startedAt) };
242
250
  } catch (e) {
243
251
  lastError = String((e && e.message) || e);
244
252
  } finally {
245
253
  if (timer) clearTimeout(timer);
246
254
  }
247
- if (i < attempts - 1) await wait(250 * (i + 1));
255
+ if (i < maxAttempts - 1) {
256
+ const remainingMs = deadlineAt - now();
257
+ if (remainingMs <= 0) break;
258
+ // A refused loopback socket fails immediately. The old six-probe loop
259
+ // therefore exhausted in only 3.75 s and could tear down a perfectly
260
+ // valid SSH session just as mobile/macOS/Linux key negotiation finished.
261
+ // Keep retrying against a real deadline, with a bounded progressive wait.
262
+ const retryDelayMs = Math.min(1500, 250 * (i + 1), remainingMs);
263
+ if (retryDelayMs > 0) await wait(retryDelayMs);
264
+ }
248
265
  }
249
- return { ready: false, attempts, code, lastError };
266
+ return { ready: false, attempts: attempted, code, lastError, elapsedMs: Math.max(0, now() - startedAt) };
250
267
  }
251
268
 
252
269
  module.exports = {
@@ -27,6 +27,10 @@ let upTimer = null;
27
27
  let ownershipWaitTimer = null;
28
28
  let ownershipTimer = null;
29
29
 
30
+ function logEvent(message) {
31
+ try { process.stderr.write(`[nexuscrew] ${String(message).replace(/[\r\n]+/g, ' ')}\n`); } catch (_) {}
32
+ }
33
+
30
34
  function ownsGeneration() {
31
35
  try {
32
36
  const meta = JSON.parse(fs.readFileSync(pidPath, 'utf8'));
@@ -53,6 +57,7 @@ function writeState(status, extra = {}) {
53
57
  function scheduleRetry(detail) {
54
58
  if (stopping) return finish();
55
59
  const delayMs = backoffDelay(attempt, { baseMs: 1000, capMs: 60000 });
60
+ logEvent(`ssh retry scheduled attempt=${attempt + 2} delayMs=${delayMs}`);
56
61
  if (!writeState('retrying', { delayMs, detail })) return stop();
57
62
  attempt += 1;
58
63
  retryTimer = setTimeout(run, delayMs);
@@ -61,6 +66,7 @@ function scheduleRetry(detail) {
61
66
  function run() {
62
67
  if (stopping) return finish();
63
68
  if (!writeState('starting')) return stop();
69
+ logEvent(`ssh attempt=${attempt + 1} starting`);
64
70
  try {
65
71
  child = spawn(sshBin, sshArgs, { stdio: 'inherit' });
66
72
  } catch (e) {
@@ -77,21 +83,25 @@ function run() {
77
83
  scheduleRetry(detail);
78
84
  };
79
85
  child.once('spawn', () => {
86
+ logEvent(`ssh attempt=${attempt + 1} spawned`);
80
87
  // ExitOnForwardFailure makes bind/auth failures exit. Do not reset backoff
81
88
  // or advertise readiness on the spawn event: only a stable transport window
82
89
  // qualifies as transport-ready; HTTP federation health is checked above us.
83
90
  upTimer = setTimeout(() => {
84
91
  if (!stopping && child && child.exitCode == null) {
85
92
  attempt = 0;
93
+ logEvent(`transport ready stableMs=${stableMs}`);
86
94
  if (!writeState('transport-ready', { sshPid: child.pid, stableMs })) stop();
87
95
  }
88
96
  }, stableMs);
89
97
  });
90
98
  child.once('error', (e) => {
99
+ logEvent(`ssh child error code=${(e && e.code) || 'unknown'}`);
91
100
  handleFailure(String(e && e.message || e));
92
101
  });
93
102
  child.once('exit', (code, signal) => {
94
103
  if (stopping) return finish();
104
+ logEvent(`ssh exited code=${code === null ? 'null' : code} signal=${signal || 'none'}`);
95
105
  handleFailure(`ssh exited code=${code} signal=${signal || ''}`);
96
106
  });
97
107
  }
@@ -28,6 +28,10 @@ const SSH_BASE_OPTS = Object.freeze([
28
28
  '-o', 'ServerAliveInterval=30',
29
29
  '-o', 'ServerAliveCountMax=3',
30
30
  '-o', 'BatchMode=yes',
31
+ // A Host stanza may set LogLevel=QUIET, leaving the per-tunnel diagnostic
32
+ // completely empty even for bind/auth/forward failures. ERROR is still
33
+ // quiet on success and never logs key material, but preserves real failures.
34
+ '-o', 'LogLevel=ERROR',
31
35
  ]);
32
36
 
33
37
  function assertForwardSpec(node) {
@@ -406,6 +410,11 @@ function startTunnel(opts) {
406
410
  closeOwnedFd();
407
411
  return { started: false, reason: 'pidfile error', error: String(e && e.message || e) };
408
412
  }
413
+ // Safe local breadcrumb: argv, host, key paths and credentials are omitted.
414
+ // The detached supervisor appends lifecycle events to the same 0600 file.
415
+ if (Number.isInteger(logFd)) {
416
+ try { fs.writeSync(logFd, `[nexuscrew] supervisor requested transport=${path.basename(sshBin)}\n`); } catch (_) {}
417
+ }
409
418
  closeOwnedFd(); // copia del padre: il figlio ha la sua dup; nessun leak (audit F3)
410
419
  return { started: true, pid, logPath, transport: sshBin };
411
420
  }
@@ -51,7 +51,7 @@ function parseRoute(raw) {
51
51
 
52
52
  function knownResource(resource) {
53
53
  return resource === '/sessions'
54
- || /^\/sessions\/[\w.@%:+-]{1,128}$/.test(resource)
54
+ || /^\/sessions\/[\w.@%:+-]{1,128}(?:\/visibility)?$/.test(resource)
55
55
  || resource === '/config'
56
56
  || resource === '/fs/dirs'
57
57
  || resource === '/files'
@@ -67,12 +67,13 @@ function knownResource(resource) {
67
67
  // Hydra: the rest of /settings stays unreachable.
68
68
  || resource === '/settings/peering/invite'
69
69
  || resource === '/ws'
70
- || /^\/fleet\/(status|schema|definitions|up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource);
70
+ || /^\/fleet\/(status|schema|definitions|credentials\/status|credentials\/(?:set|remove)|up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource);
71
71
  }
72
72
 
73
73
  function allowedResource(resource, method = 'GET') {
74
74
  if (resource === '/sessions') return method === 'GET' || method === 'POST';
75
75
  if (/^\/sessions\/[\w.@%:+-]{1,128}$/.test(resource)) return method === 'DELETE';
76
+ if (/^\/sessions\/[\w.@%:+-]{1,128}\/visibility$/.test(resource)) return method === 'PATCH';
76
77
  if (resource === '/config') return method === 'GET';
77
78
  if (resource === '/fs/dirs') return method === 'GET';
78
79
  if (resource === '/files') return method === 'GET' || method === 'DELETE';
@@ -87,8 +88,8 @@ function allowedResource(resource, method = 'GET') {
87
88
  if (resource === '/topology') return method === 'GET';
88
89
  if (resource === '/settings/peering/invite') return method === 'POST';
89
90
  if (resource === '/ws') return method === 'GET';
90
- if (/^\/fleet\/(status|schema|definitions)$/.test(resource)) return method === 'GET';
91
- if (/^\/fleet\/(up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource)) return method === 'POST';
91
+ if (/^\/fleet\/(status|schema|definitions|credentials\/status)$/.test(resource)) return method === 'GET';
92
+ if (/^\/fleet\/(credentials\/(?:set|remove)|up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource)) return method === 'POST';
92
93
  return false;
93
94
  }
94
95
 
package/lib/server.js CHANGED
@@ -8,7 +8,7 @@ const express = require('express');
8
8
  const { WebSocketServer } = require('ws');
9
9
  const { defaults, loadConfig, assertLoopback, configJsonPath } = require('./config.js');
10
10
  const { writeConfigAtomic } = require('./cli/init.js');
11
- const { listSessions, attachedClients } = require('./tmux/list.js');
11
+ const { listSessions, attachedClients, setSessionVisibility } = require('./tmux/list.js');
12
12
  const { runAction, pasteToSession, submitToSession } = require('./tmux/actions.js');
13
13
  const { createSession, killSession, isProtectedSession } = require('./tmux/lifecycle.js');
14
14
  const { createPreviewSampler } = require('./tmux/preview.js');
@@ -197,6 +197,17 @@ function createServer(opts = {}) {
197
197
  res.json({ killed: true });
198
198
  } catch (e) { res.status(e.status || 500).json({ error: String(e.message || e) }); }
199
199
  });
200
+ api.patch('/sessions/:name/visibility', express.json({ limit: '1kb' }), async (req, res) => {
201
+ if (proxyReadonly()) return res.status(403).json({ error: 'READONLY: classificazione sessione bloccata' });
202
+ const name = String(req.params.name || '');
203
+ try {
204
+ const fleet = await fleetP;
205
+ if (isProtectedSession(name, fleet.isCellSession)) {
206
+ return res.status(409).json({ error: 'sessione di cella: la visibilità tecnica vale solo per sessioni tmux non gestite' });
207
+ }
208
+ res.json(await setSessionVisibility(cfg.tmuxBin, name, req.body?.technical === true));
209
+ } catch (e) { res.status(e.status || 500).json({ error: String(e.message || e) }); }
210
+ });
200
211
  api.get('/config', (_req, res) => res.json({
201
212
  readonlyDefault: cfg.readonlyDefault, version: VERSION, uiVersion: uiBuildVersion(distDir),
202
213
  bind: cfg.bind, port: cfg.port,
@@ -405,6 +416,10 @@ function createServer(opts = {}) {
405
416
  }
406
417
  });
407
418
 
419
+ server.on('close', () => {
420
+ fleetP.then((fleet) => (typeof fleet.close === 'function' ? fleet.close() : null)).catch(() => {});
421
+ });
422
+
408
423
  return { app, server, wss, cfg, token: tokenHolder.value, tokenStore, watcher, fleetP, updater };
409
424
  }
410
425
 
package/lib/tmux/list.js CHANGED
@@ -1,14 +1,14 @@
1
1
  'use strict';
2
2
  const { execFile, execFileSync } = require('node:child_process');
3
3
 
4
- const FMT = "#{session_name}\t#{session_attached}\t#{session_windows}\t#{session_created}\t#{session_activity}\t#{pane_current_command}";
4
+ const FMT = "#{session_name}\t#{session_attached}\t#{session_windows}\t#{session_created}\t#{session_activity}\t#{pane_current_command}\t#{@nexuscrew_visibility}";
5
5
 
6
6
  function parseSessions(raw) {
7
7
  return String(raw)
8
8
  .split('\n')
9
9
  .filter((l) => l.trim() !== '')
10
10
  .map((line) => {
11
- const [name, attached, windows, created, activity, cmd] = line.split('\t');
11
+ const [name, attached, windows, created, activity, cmd, visibility] = line.split('\t');
12
12
  return {
13
13
  name,
14
14
  attached: attached === '1',
@@ -16,11 +16,29 @@ function parseSessions(raw) {
16
16
  created: Number(created),
17
17
  activity: Number(activity) || 0,
18
18
  cmd: cmd || '',
19
+ technical: visibility === 'technical',
19
20
  };
20
21
  })
21
22
  .filter((session) => session.windows > 0);
22
23
  }
23
24
 
25
+ function setSessionVisibility(tmuxBin = 'tmux', name, technical = false) {
26
+ return new Promise((resolve, reject) => {
27
+ if (typeof name !== 'string' || !/^[\w.@%:+-]{1,128}$/.test(name) || name.startsWith('-')) {
28
+ const error = new Error('nome sessione non valido'); error.status = 400; reject(error); return;
29
+ }
30
+ const args = technical
31
+ ? ['set-option', '-t', `=${name}`, '@nexuscrew_visibility', 'technical']
32
+ : ['set-option', '-u', '-t', `=${name}`, '@nexuscrew_visibility'];
33
+ execFile(tmuxBin, args, (err, _stdout, stderr) => {
34
+ if (!err) { resolve({ name, technical: !!technical }); return; }
35
+ const error = new Error(`tmux set-option failed: ${String(stderr || err.message).trim()}`);
36
+ error.status = /can't find session|no server running/i.test(stderr || '') ? 404 : 500;
37
+ reject(error);
38
+ });
39
+ });
40
+ }
41
+
24
42
  function listSessions(tmuxBin = 'tmux') {
25
43
  return new Promise((resolve, reject) => {
26
44
  execFile(tmuxBin, ['list-sessions', '-F', FMT], (err, stdout, stderr) => {
@@ -46,4 +64,4 @@ function attachedClients(tmuxBin = 'tmux', session) {
46
64
  } catch (_) { return 0; }
47
65
  }
48
66
 
49
- module.exports = { parseSessions, listSessions, attachedClients, FMT };
67
+ module.exports = { parseSessions, listSessions, attachedClients, setSessionVisibility, FMT };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmmbuto/nexuscrew",
3
- "version": "0.8.13",
3
+ "version": "0.8.15",
4
4
  "description": "Faithful browser tmux client — attach to live sessions over a real PTY, localhost-only, mobile-easy",
5
5
  "main": "lib/server.js",
6
6
  "bin": {