unbound-cli 1.22.0 → 1.23.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unbound-cli",
3
- "version": "1.22.0",
3
+ "version": "1.23.0",
4
4
  "description": "CLI tool for Unbound - AI Gateway management",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -10,7 +10,13 @@ const claudePaths = require('../claudePaths');
10
10
  // Validate the stored API key against the backend. Returns one of:
11
11
  // valid | invalid | not-logged-in | unverified (network/other error).
12
12
  async function checkApiKey() {
13
- if (!config.isLoggedIn()) return { state: 'not-logged-in', detail: 'no API key stored — run `unbound login`' };
13
+ if (!config.isLoggedIn()) {
14
+ if (!config.getDeviceKey()) return { state: 'not-logged-in', detail: 'no API key stored — run `unbound login`' };
15
+ const result = await api.validateApiKey(config.getDeviceKey());
16
+ if (result === 'valid') return { state: 'valid', detail: 'device key verified against the backend' };
17
+ if (result === 'invalid') return { state: 'invalid', detail: 'the stored device key was rejected (401) — run `unbound login`' };
18
+ return { state: 'unverified', detail: 'the backend did not confirm the key' };
19
+ }
14
20
  try {
15
21
  const deviceSerial = await getDeviceSerial();
16
22
  const privileges = await api.get('/api/v1/users/privileges/', { query: { device_serial: deviceSerial } });
@@ -168,7 +174,7 @@ Examples:
168
174
  console.log('');
169
175
  }
170
176
  if (!tampered.length) {
171
- if (configMismatch || blankConfigDir) { process.exitCode = 1; return; }
177
+ if (configMismatch || blankConfigDir || key.state === 'invalid') { process.exitCode = 1; return; }
172
178
  if (!anyInstalled) console.log(`${C.yellow('No tools are set up yet')} — nothing to fix. Run ${C.bold('unbound setup')} first.`);
173
179
  else output.success('Nothing to fix — all set up tools are healthy.');
174
180
  console.log('');
@@ -249,6 +249,35 @@ async function runPythonScript(scriptPath, args, { capture }) {
249
249
  });
250
250
  }
251
251
 
252
+ // An elevated process can't reach WSL distros (they're per user), so onboard.py's logon
253
+ // task sets each user's distros up as that user. Clear drops these tools; the task goes with the last one.
254
+ const WSL_TASK_PY = `import importlib.util as u, sys
255
+ s = u.spec_from_file_location("onboard", sys.argv[1]); m = u.module_from_spec(s); s.loader.exec_module(m)
256
+ urls = sys.argv[3:]
257
+ if sys.argv[2] != "clear": sys.exit(0 if m.install_wsl_logon_task(urls) else 1)
258
+ for x in urls: (m._wsl_dir() / x.replace("/mdm/setup.py", "/setup.py")[len(m._RAW_SETUP) + 1:].replace("/", "-")).unlink(missing_ok=True)
259
+ sys.exit(0 if any(m._wsl_dir().glob("*-setup.py")) or m.remove_wsl_logon_task() else 1)`;
260
+
261
+ async function syncWslLogonTask(tools, clear) {
262
+ const s = output.spinner(clear ? 'Clearing WSL logon task...' : 'Setting up WSL logon task...');
263
+ try {
264
+ const r = await withSecureTempFile('.py', async (tmp) => {
265
+ await downloadToFile(`${SETUP_BASE_URL}/mdm/onboard.py`, tmp);
266
+ const py = resolvePython();
267
+ const urls = tools.map((t) => `${SETUP_BASE_URL}/${t.script}`);
268
+ return spawnSync(py.cmd, [...py.prefix, '-I', '-c', WSL_TASK_PY, tmp, clear ? 'clear' : 'install', ...urls],
269
+ { encoding: 'utf8', windowsHide: true, timeout: 600000 });
270
+ });
271
+ if (r.status !== 0) throw new Error(`${r.stdout || ''}${r.stderr || ''}`.trim() || String(r.error || r.status));
272
+ s.succeed(clear ? 'WSL logon task updated' : "WSL distros: each user's are set up at their next login");
273
+ return true;
274
+ } catch (err) {
275
+ s.fail(clear ? 'Could not fully clear the WSL logon task' : 'WSL distros will not be set up; Windows setup is unaffected');
276
+ console.error(output.colors.dim(` ${err.message}`));
277
+ return false;
278
+ }
279
+ }
280
+
252
281
  /**
253
282
  * Builds the shared argv tail for setup.py invocations. Always passes the
254
283
  * tenant URL flags so the script's behavior is not sensitive to drift in its
@@ -602,8 +631,9 @@ function reportMdmSkips(labels) {
602
631
  * Runs a batch of tools sequentially with spinners. Stops on the first hard
603
632
  * failure. A tool that reports an MDM skip is NOT a failure — it's collected and
604
633
  * surfaced (in red) at the end, and the batch continues. Returns
605
- * { ok, skipped } — ok is false only on a hard failure; skipped is the list of
606
- * MDM-managed tool labels so callers can qualify their own success message.
634
+ * { ok, skipped, done } — ok is false only on a hard failure; skipped is the list of
635
+ * MDM-managed tool labels so callers can qualify their own success message; done
636
+ * is the tools that ran to success, even when a later one failed.
607
637
  * When `summary` is set, a green success line is printed for the configured
608
638
  * tools before the MDM notice.
609
639
  *
@@ -615,6 +645,7 @@ function reportMdmSkips(labels) {
615
645
  async function runBatch(tools, runFn, { clear = false, summary = null, report = null } = {}) {
616
646
  const action = clear ? 'Clearing' : 'Setting up';
617
647
  const mdmSkipped = [];
648
+ const done = [];
618
649
  for (const tool of tools) {
619
650
  const s = output.spinner(`${action} ${tool.label}...`);
620
651
  try {
@@ -627,6 +658,7 @@ async function runBatch(tools, runFn, { clear = false, summary = null, report =
627
658
  mdmSkipped.push(tool.label);
628
659
  } else {
629
660
  s.succeed(tool.label);
661
+ done.push(tool);
630
662
  }
631
663
  } catch (err) {
632
664
  s.fail(`Failed: ${tool.label}`);
@@ -643,7 +675,7 @@ async function runBatch(tools, runFn, { clear = false, summary = null, report =
643
675
  }
644
676
  // Still surface any tools skipped before this failure so the notice isn't lost.
645
677
  reportMdmSkips(mdmSkipped);
646
- return { ok: false, skipped: mdmSkipped };
678
+ return { ok: false, skipped: mdmSkipped, done };
647
679
  }
648
680
  }
649
681
  const configured = tools.length - mdmSkipped.length;
@@ -654,7 +686,7 @@ async function runBatch(tools, runFn, { clear = false, summary = null, report =
654
686
  output.success(mdmSkipped.length ? `${configured} of ${tools.length} tools ${clear ? 'cleared' : 'configured'}` : summary);
655
687
  }
656
688
  reportMdmSkips(mdmSkipped);
657
- return { ok: true, skipped: mdmSkipped };
689
+ return { ok: true, skipped: mdmSkipped, done };
658
690
  }
659
691
 
660
692
  /**
@@ -922,7 +954,7 @@ must update the MDM configuration.
922
954
  if (!scriptSupportsBackfill(tool.script)) noteBackfillUnsupported(tool.label, tool.script);
923
955
  }
924
956
  }
925
- const { ok } = await runBatch(
957
+ const { done } = await runBatch(
926
958
  resolvedTools,
927
959
  (tool) => {
928
960
  const toolArgs = buildScriptArgs(adminApiKey, {
@@ -938,7 +970,8 @@ must update the MDM configuration.
938
970
  },
939
971
  { clear: opts.clear, summary: opts.clear ? 'All tools cleared' : 'All tools configured', report: { apiKey: adminApiKey, backendUrl } }
940
972
  );
941
- if (!ok) return;
973
+ // Tools a later failure didn't reach are left as they were, on Windows and in WSL alike.
974
+ if (done.length && isWindowsNative()) await syncWslLogonTask(done, opts.clear);
942
975
  return;
943
976
  }
944
977
 
@@ -1225,6 +1258,7 @@ Examples:
1225
1258
  if (includeMdm) {
1226
1259
  const mdmTools = Object.keys(MDM_TOOLS).map(name => ({ name, ...MDM_TOOLS[name] }));
1227
1260
  mdmFailed = await clearToolsBestEffort('mdm', mdmTools, { mdm: true, backendUrl, gatewayUrl });
1261
+ if (isWindowsNative() && !(await syncWslLogonTask(mdmTools, true))) mdmFailed.push('WSL logon task');
1228
1262
 
1229
1263
  // Root-only by construction (gated on includeMdm). No-op when no binary
1230
1264
  // install is present (python-only setups) and on Windows.
@@ -1331,7 +1365,7 @@ async function runMdmSetupAllBundle(adminApiKey, { backendUrl, frontendUrl, gate
1331
1365
  if (!scriptSupportsBackfill(tool.script)) noteBackfillUnsupported(tool.label, tool.script);
1332
1366
  }
1333
1367
  }
1334
- return await runBatch(resolvedTools, (tool) => {
1368
+ const result = await runBatch(resolvedTools, (tool) => {
1335
1369
  const args = buildScriptArgs(adminApiKey, {
1336
1370
  backendUrl, frontendUrl, gatewayUrl, mdm: true,
1337
1371
  backfill: backfill && scriptSupportsBackfill(tool.script),
@@ -1339,6 +1373,8 @@ async function runMdmSetupAllBundle(adminApiKey, { backendUrl, frontendUrl, gate
1339
1373
  });
1340
1374
  return runScriptPiped(tool.script, args);
1341
1375
  }, { report: { apiKey: adminApiKey, backendUrl } });
1376
+ if (result.done.length && isWindowsNative()) await syncWslLogonTask(result.done, false);
1377
+ return result;
1342
1378
  }
1343
1379
 
1344
1380
  module.exports = {
@@ -1348,6 +1384,8 @@ module.exports = {
1348
1384
  scopeNotice,
1349
1385
  runSetupAllBundle,
1350
1386
  runMdmSetupAllBundle,
1387
+ syncWslLogonTask,
1388
+ WSL_TASK_PY,
1351
1389
  hasRootPrivileges,
1352
1390
  ALL_TOOLS,
1353
1391
  MDM_ALL_TOOLS,
@@ -79,6 +79,12 @@ Examples:
79
79
  pairs.push(['Role', role || '-']);
80
80
  if (token) pairs.push(['Token', token]);
81
81
  }
82
+ let deviceKey = null;
83
+ if (!loggedIn && config.getDeviceKey()) {
84
+ deviceKey = await api.validateApiKey(config.getDeviceKey(), { baseUrl: config.getBaseUrl() });
85
+ if (deviceKey === 'valid') connectivity = 'Connected';
86
+ pairs.push(['Device key', { valid: 'Valid', invalid: 'Invalid or expired', unknown: 'Could not verify' }[deviceKey]]);
87
+ }
82
88
  pairs.push(['Backend URL', config.getBaseUrl()]);
83
89
  pairs.push(['Frontend URL', config.getFrontendUrl()]);
84
90
  pairs.push(['Gateway URL', config.getGatewayUrl()]);
@@ -104,6 +110,7 @@ Examples:
104
110
  output.json({
105
111
  config_file: config.CONFIG_FILE,
106
112
  logged_in: loggedIn,
113
+ device_key: deviceKey,
107
114
  email: loggedIn ? (cfg.email || null) : null,
108
115
  organization: loggedIn ? (cfg.org_name || null) : null,
109
116
  role: role,
@@ -0,0 +1,123 @@
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const { EventEmitter } = require('events');
4
+ const childProcess = require('child_process');
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+
9
+ const RAW = 'https://raw.githubusercontent.com/websentry-ai/setup/refs/heads/main';
10
+
11
+ // Stands in for mdm/onboard.py: same names the snippet calls, recording instead of touching Windows.
12
+ const FAKE_ONBOARD = `import json, os
13
+ from pathlib import Path
14
+ _RAW_SETUP = ${JSON.stringify(RAW)}
15
+ def _rec(*a): open(os.environ["REC"], "a").write(json.dumps(a) + "\\n")
16
+ def _wsl_dir(): return Path(os.environ["STAGE"])
17
+ def install_wsl_logon_task(urls): _rec("install", urls); return os.environ.get("FAIL") != "1"
18
+ def remove_wsl_logon_task(): _rec("remove"); return True
19
+ `;
20
+
21
+ function runSnippet(mode, urls, { fail = false, staged = [] } = {}) {
22
+ const { WSL_TASK_PY } = require('../src/commands/setup');
23
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wsl-task-'));
24
+ const stage = path.join(dir, 'stage');
25
+ fs.mkdirSync(stage);
26
+ for (const name of staged) fs.writeFileSync(path.join(stage, name), '');
27
+ fs.writeFileSync(path.join(dir, 'onboard.py'), FAKE_ONBOARD);
28
+ const rec = path.join(dir, 'rec.jsonl');
29
+ const r = childProcess.spawnSync('python3', ['-I', '-c', WSL_TASK_PY, path.join(dir, 'onboard.py'), mode, ...urls], {
30
+ encoding: 'utf8', env: { ...process.env, REC: rec, STAGE: stage, FAIL: fail ? '1' : '' },
31
+ });
32
+ const calls = fs.existsSync(rec) ? fs.readFileSync(rec, 'utf8').trim().split('\n').map((l) => JSON.parse(l)) : [];
33
+ return { status: r.status, stderr: r.stderr, calls, left: fs.readdirSync(stage).sort() };
34
+ }
35
+
36
+ test('install hands the MDM script URLs to onboard.py unchanged', () => {
37
+ const urls = [`${RAW}/cursor/mdm/setup.py`, `${RAW}/claude-code/hooks/mdm/setup.py`];
38
+ const r = runSnippet('install', urls);
39
+ assert.equal(r.status, 0, r.stderr);
40
+ assert.deepEqual(r.calls, [['install', urls]]);
41
+ });
42
+
43
+ test('install fails when onboard.py could not register the task', () => {
44
+ assert.equal(runSnippet('install', [`${RAW}/cursor/mdm/setup.py`], { fail: true }).status, 1);
45
+ });
46
+
47
+ test('clearing one tool drops only its staged installer and keeps the task', () => {
48
+ const r = runSnippet('clear', [`${RAW}/cursor/mdm/setup.py`],
49
+ { staged: ['cursor-setup.py', 'codex-hooks-setup.py', 'run.py'] });
50
+ assert.equal(r.status, 0, r.stderr);
51
+ assert.deepEqual(r.left, ['codex-hooks-setup.py', 'run.py']);
52
+ assert.deepEqual(r.calls, []);
53
+ });
54
+
55
+ test('clearing the last tool removes the task', () => {
56
+ const r = runSnippet('clear', [`${RAW}/codex/hooks/mdm/setup.py`, `${RAW}/codex/gateway/mdm/setup.py`],
57
+ { staged: ['codex-hooks-setup.py', 'run.py'] });
58
+ assert.equal(r.status, 0, r.stderr);
59
+ assert.deepEqual(r.calls, [['remove']]);
60
+ });
61
+
62
+ // Loads setup.js with the network and every child process faked, on the given platform.
63
+ async function mdmBundle(platform, { exits = [0, 0] } = {}) {
64
+ for (const m of ['../src/commands/setup', '../src/utils', '../src/output']) delete require.cache[require.resolve(m)];
65
+ const utils = require('../src/utils');
66
+ const output = require('../src/output');
67
+ const orig = { spawn: childProcess.spawn, spawnSync: childProcess.spawnSync, dl: utils.downloadToFile,
68
+ spinner: output.spinner, platform: Object.getOwnPropertyDescriptor(process, 'platform') };
69
+ const taskCalls = [];
70
+ childProcess.spawnSync = (cmd, args) => {
71
+ if (args.includes('-c')) taskCalls.push(args.slice(args.indexOf('-c') + 3));
72
+ return { status: 0, stdout: '', stderr: '' };
73
+ };
74
+ childProcess.spawn = () => {
75
+ const child = new EventEmitter();
76
+ child.stdin = { on() {}, end() {} };
77
+ child.stdout = new EventEmitter();
78
+ child.stderr = new EventEmitter();
79
+ const code = exits.shift();
80
+ setImmediate(() => child.emit('close', code));
81
+ return child;
82
+ };
83
+ utils.downloadToFile = async () => {};
84
+ output.spinner = () => ({ succeed() {}, fail() {}, stop() {} });
85
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
86
+ const exitCode = process.exitCode;
87
+ try {
88
+ const setup = require('../src/commands/setup');
89
+ const result = await setup.runMdmSetupAllBundle('k', { tools: ['cursor', 'codex-subscription'] });
90
+ return { result, taskCalls };
91
+ } finally {
92
+ Object.assign(childProcess, { spawn: orig.spawn, spawnSync: orig.spawnSync });
93
+ utils.downloadToFile = orig.dl;
94
+ output.spinner = orig.spinner;
95
+ Object.defineProperty(process, 'platform', orig.platform);
96
+ process.exitCode = exitCode;
97
+ for (const m of ['../src/commands/setup', '../src/utils', '../src/output']) delete require.cache[require.resolve(m)];
98
+ }
99
+ }
100
+
101
+ test('elevated onboard on Windows registers the WSL task for the tools it set up', async () => {
102
+ const { result, taskCalls } = await mdmBundle('win32');
103
+ assert.equal(result.ok, true);
104
+ assert.deepEqual(taskCalls, [['install', `${RAW}/cursor/mdm/setup.py`, `${RAW}/codex/hooks/mdm/setup.py`]]);
105
+ });
106
+
107
+ test('macOS and Linux never touch the WSL task', async () => {
108
+ for (const platform of ['darwin', 'linux']) {
109
+ assert.deepEqual((await mdmBundle(platform)).taskCalls, []);
110
+ }
111
+ });
112
+
113
+ test('a failed tool still syncs the tools set up before it', async () => {
114
+ const { result, taskCalls } = await mdmBundle('win32', { exits: [0, 1] });
115
+ assert.equal(result.ok, false);
116
+ assert.deepEqual(taskCalls, [['install', `${RAW}/cursor/mdm/setup.py`]]);
117
+ });
118
+
119
+ test('a batch that set nothing up leaves the WSL task alone', async () => {
120
+ const { result, taskCalls } = await mdmBundle('win32', { exits: [1] });
121
+ assert.equal(result.ok, false);
122
+ assert.deepEqual(taskCalls, []);
123
+ });
@@ -0,0 +1,78 @@
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const http = require('http');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { spawn } = require('child_process');
8
+
9
+ const ROOT = path.join(__dirname, '..');
10
+
11
+ function startServer(status) {
12
+ const server = http.createServer((req, res) => {
13
+ res.writeHead(status, { 'Content-Type': 'application/json' });
14
+ res.end(JSON.stringify(status === 200 ? { is_admin: false, is_member: true } : { error: 'Invalid API key' }));
15
+ });
16
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve({ server, port: server.address().port })));
17
+ }
18
+
19
+ // Stubs the OS keychain so only the config file's device key is visible.
20
+ function writeKeychainStub(dir) {
21
+ const stub = path.join(dir, 'no-keychain.js');
22
+ fs.writeFileSync(stub, `require(${JSON.stringify(path.join(ROOT, 'src', 'keychain.js'))}).get = () => null;\n`);
23
+ return stub;
24
+ }
25
+
26
+ function runStatus(port, config) {
27
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'status-dk-'));
28
+ fs.mkdirSync(path.join(home, '.unbound'));
29
+ const cfg = { ...config, base_url: `http://127.0.0.1:${port}` };
30
+ fs.writeFileSync(path.join(home, '.unbound', 'config.json'), JSON.stringify(cfg));
31
+ const stub = writeKeychainStub(home);
32
+ return new Promise((resolve) => {
33
+ const child = spawn('node', ['-r', stub, path.join(ROOT, 'src', 'index.js'), 'status', '--json'], {
34
+ env: { ...process.env, HOME: home, UNBOUND_TOKEN: '', UNBOUND_API_URL: '', UNBOUND_TELEMETRY: '0', UNBOUND_NO_UPDATE_CHECK: '1' },
35
+ });
36
+ let stdout = '';
37
+ child.stdout.on('data', (d) => { stdout += d; });
38
+ child.on('close', (code) => {
39
+ fs.rmSync(home, { recursive: true, force: true });
40
+ resolve({ code, json: stdout ? JSON.parse(stdout) : null });
41
+ });
42
+ });
43
+ }
44
+
45
+ test('device key only: status reports it valid and connected', async () => {
46
+ const { server, port } = await startServer(200);
47
+ try {
48
+ const r = await runStatus(port, { device_token: 'device-key-1234' });
49
+ assert.equal(r.code, 0);
50
+ assert.equal(r.json.logged_in, false);
51
+ assert.equal(r.json.device_key, 'valid');
52
+ assert.equal(r.json.api_status, 'Connected');
53
+ } finally {
54
+ server.close();
55
+ }
56
+ });
57
+
58
+ test('device key rejected by the backend: status reports it invalid', async () => {
59
+ const { server, port } = await startServer(401);
60
+ try {
61
+ const r = await runStatus(port, { device_token: 'device-key-1234' });
62
+ assert.equal(r.json.device_key, 'invalid');
63
+ assert.notEqual(r.json.api_status, 'Connected');
64
+ } finally {
65
+ server.close();
66
+ }
67
+ });
68
+
69
+ test('no key at all: status shows no device key row', async () => {
70
+ const { server, port } = await startServer(200);
71
+ try {
72
+ const r = await runStatus(port, {});
73
+ assert.equal(r.json.logged_in, false);
74
+ assert.equal(r.json.device_key, null);
75
+ } finally {
76
+ server.close();
77
+ }
78
+ });