unbound-cli 1.21.3 → 1.22.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unbound-cli",
3
- "version": "1.21.3",
3
+ "version": "1.22.1",
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('');
@@ -73,9 +73,41 @@ async function list(traceValue, opts) {
73
73
  output.logTable(HEADERS, findings.map((f) => [String(f.id), f.type, f.action, statusOf(f)]));
74
74
  }
75
75
 
76
+ // Marks every finding of the user's on the trace that is still markable; --mark-all overrides --finding.
77
+ async function markAll(trace, findings, opts) {
78
+ const targets = findings.filter((f) => f.markable);
79
+ if (targets.length === 0) throw new Error('Nothing on this trace is left to mark.');
80
+ if (!opts.yes && !(await confirm(`Mark ${targets.length} findings on trace ${trace} as false positives?`))) {
81
+ output.info('Cancelled.');
82
+ return;
83
+ }
84
+ const marked = [];
85
+ for (const finding of targets) {
86
+ try {
87
+ const data = await call('post', PATH, {
88
+ body: { trace_id: trace, guardrail_action_id: finding.id, is_false_positive: true },
89
+ });
90
+ marked.push({ id: finding.id, type: finding.type, message: data.message });
91
+ } catch (err) {
92
+ throw new Error(`Marked ${marked.length} of ${targets.length}; finding ${finding.id} failed: ${err.message}`);
93
+ }
94
+ }
95
+ if (opts.json) {
96
+ output.json({ trace_id: trace, marked });
97
+ return;
98
+ }
99
+ for (const m of marked) output.success(`${m.message}: ${m.type} finding ${m.id}.`);
100
+ }
101
+
76
102
  async function setMark(traceValue, opts, mark) {
77
103
  const trace = resolveTraceId(traceValue);
78
- const finding = chooseFinding(await fetchFindings(trace), mark, opts.finding);
104
+ const findings = await fetchFindings(trace);
105
+ if (opts.markAll) {
106
+ if (!mark) throw new Error('--mark-all works with mark only.');
107
+ if (opts.finding !== undefined) throw new Error('Use either --finding or --mark-all, not both.');
108
+ return markAll(trace, findings, opts);
109
+ }
110
+ const finding = chooseFinding(findings, mark, opts.finding);
79
111
  const verb = mark ? 'Mark' : 'Unmark';
80
112
  if (!opts.yes && !(await confirm(`${verb} ${finding.type} finding ${finding.id} on trace ${trace} as a false positive?`))) {
81
113
  output.info('Cancelled.');
@@ -114,6 +146,7 @@ Examples:
114
146
  .command('mark <trace-id>')
115
147
  .description('Mark one of your findings on a trace ID as a false positive.')
116
148
  .option('--finding <id>', 'Finding ID, when the trace has more than one (see "list")')
149
+ .option('--mark-all', 'Mark every finding of yours on the trace (overrides --finding)')
117
150
  .option('-y, --yes', 'Skip the confirmation prompt')
118
151
  .option('--json', 'Output the JSON response')
119
152
  .addHelpText('after', `
@@ -124,6 +157,7 @@ any finding in their organization, or work by action ID with
124
157
  Examples:
125
158
  $ unbound false-positive mark 3f2a6c1e-8b7d-4e2f-9a1c-5d6e7f8a9b0c
126
159
  $ unbound false-positive mark 3f2a6c1e-8b7d-4e2f-9a1c-5d6e7f8a9b0c --finding 5521 --yes
160
+ $ unbound false-positive mark 3f2a6c1e-8b7d-4e2f-9a1c-5d6e7f8a9b0c --mark-all --yes
127
161
  `)
128
162
  .action((trace, opts) => run(() => setMark(trace, opts, true)));
129
163
 
@@ -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,
@@ -149,3 +149,40 @@ test('with no key at all it says to log in, and a refused key surfaces the refus
149
149
  await assert.rejects(freshCall({}).call('get', PATH), /unbound login/);
150
150
  await assert.rejects(freshCall({ deviceKey: 'd', refuse: ['d'] }).call('get', PATH), (e) => e.statusCode === 401);
151
151
  });
152
+
153
+ test('mark-all marks every markable finding and skips the ones already marked', async () => {
154
+ const second = { ...flagged, id: 13 };
155
+ const { server, seen, port } = await startServer((method) =>
156
+ (method === 'GET' ? [200, { findings: [flagged, marked, second] }] : [200, { message: 'False positive marked' }]));
157
+ try {
158
+ const r = await runCli(port, ['false-positive', 'mark', TRACE, '--mark-all', '--yes']);
159
+ assert.equal(r.code, 0, r.stderr);
160
+ const posts = seen.filter((s) => s.method === 'POST').map((s) => s.body.guardrail_action_id);
161
+ assert.deepEqual(posts, [11, 13]);
162
+ assert.match(r.stdout + r.stderr, /False positive marked/);
163
+ } finally {
164
+ server.close();
165
+ }
166
+ });
167
+
168
+ test('mark-all refuses to combine with --finding and posts nothing', async () => {
169
+ const { server, seen, port } = await startServer(() => [200, { findings: [flagged] }]);
170
+ try {
171
+ const r = await runCli(port, ['false-positive', 'mark', TRACE, '--mark-all', '--finding', '11', '--yes']);
172
+ assert.equal(r.code, 1);
173
+ assert.equal(seen.filter((s) => s.method === 'POST').length, 0);
174
+ } finally {
175
+ server.close();
176
+ }
177
+ });
178
+
179
+ test('mark-all with nothing left to mark exits 1 and posts nothing', async () => {
180
+ const { server, seen, port } = await startServer(() => [200, { findings: [marked] }]);
181
+ try {
182
+ const r = await runCli(port, ['false-positive', 'mark', TRACE, '--mark-all', '--yes']);
183
+ assert.equal(r.code, 1);
184
+ assert.equal(seen.filter((s) => s.method === 'POST').length, 0);
185
+ } finally {
186
+ server.close();
187
+ }
188
+ });
@@ -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
+ });