unbound-cli 1.26.2 → 1.27.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/README.md +4 -4
- package/package.json +1 -1
- package/src/api.js +11 -1
- package/src/commands/delivery.js +17 -9
- package/src/commands/onboard.js +3 -1
- package/src/commands/setup.js +111 -16
- package/src/index.js +1 -1
- package/src/setup-report.js +54 -0
- package/src/toolHealth.js +23 -7
- package/test/delivery.test.js +5 -2
- package/test/onboard-scope.test.js +22 -3
- package/test/setup-args.test.js +15 -1
- package/test/setup-removal-context.test.js +428 -0
- package/test/tool-health.test.js +161 -0
package/test/delivery.test.js
CHANGED
|
@@ -381,7 +381,7 @@ test('branch detail says when only the newest 100 sessions are shown', async ()
|
|
|
381
381
|
|
|
382
382
|
test('users and teams send sort, page and ticket filters and print the columns the server lists', async () => {
|
|
383
383
|
await withBackend(async ({ seen, run }) => {
|
|
384
|
-
const users = await run(['delivery', 'users', '--sort', '
|
|
384
|
+
const users = await run(['delivery', 'users', '--sort', 'merge-rate-pct', '--page', '2', '--ticket-status', 'todo',
|
|
385
385
|
'--work-group', 'fix', '--team', 'Platform']);
|
|
386
386
|
assert.equal(users.code, 0, users.stderr);
|
|
387
387
|
assert.equal(seen[0].path, `${BASE}/users/`);
|
|
@@ -434,7 +434,7 @@ test('users and teams warn when the server sorted by another column', async () =
|
|
|
434
434
|
await withBackend(async ({ run }) => {
|
|
435
435
|
const r = await run(['delivery', 'teams', '--sort', 'merge_rate_pct']);
|
|
436
436
|
assert.equal(r.code, 0, r.stderr);
|
|
437
|
-
assert.match(r.stderr, /Sorted by
|
|
437
|
+
assert.match(r.stderr, /Sorted by ai-spend: merge-rate-pct needs GitHub connected\./);
|
|
438
438
|
const asked = await run(['delivery', 'teams', '--sort', 'ai_spend']);
|
|
439
439
|
assert.doesNotMatch(asked.stderr, /Sorted by/);
|
|
440
440
|
const unsorted = await run(['delivery', 'teams']);
|
|
@@ -510,6 +510,9 @@ test('bad input fails before any request is sent', async () => {
|
|
|
510
510
|
[['delivery', 'users', '--sort', 'name'], /Invalid --sort "name"/],
|
|
511
511
|
[['delivery', 'users', '--sort', 'active_ai_users'], /Invalid --sort "active_ai_users"/],
|
|
512
512
|
[['delivery', 'teams', '--sort', 'last_active'], /Invalid --sort "last_active"/],
|
|
513
|
+
[['delivery', 'teams', '--sort', 'last-active'],
|
|
514
|
+
/Must be one of: active-ai-users, ai-branches, prs-raised, prs-merged, merge-rate-pct, ai-spend, cost-per-merged-pr,/],
|
|
515
|
+
[['delivery', 'branches', '--outcome', 'open'], /Must be one of: merged, in-review, closed, no-pr, pr-raised\./],
|
|
513
516
|
[['delivery', 'teams', '--order', 'up'], /Invalid --order "up"/],
|
|
514
517
|
[['delivery', 'branch', 'abc'], /Invalid branch ID "abc"/],
|
|
515
518
|
[['delivery', 'spend', '--by', 'tool'], /Invalid --by "tool"/],
|
|
@@ -35,7 +35,7 @@ test('hasRootPrivileges: false when effective uid is not 0 (no sudo)', () => {
|
|
|
35
35
|
// ---- 2. onboard routes by detected scope ----
|
|
36
36
|
// Reloads the module graph with stubbed deps so we can observe which bundle
|
|
37
37
|
// helper the single `onboard` command invokes.
|
|
38
|
-
async function runOnboard(isRoot, { setCron = false, discoveryKey = 'd', domain, ownerKeyThrows = false } = {}) {
|
|
38
|
+
async function runOnboard(isRoot, { setCron = false, discoveryKey = 'd', domain, ownerKeyThrows = false, skipCowork = false } = {}) {
|
|
39
39
|
for (const m of [
|
|
40
40
|
'../src/commands/onboard',
|
|
41
41
|
'../src/commands/setup',
|
|
@@ -60,8 +60,8 @@ async function runOnboard(isRoot, { setCron = false, discoveryKey = 'd', domain,
|
|
|
60
60
|
// Detection and the Pi step are covered in tool-detect.test.js; here pi is absent,
|
|
61
61
|
// so the bundle is the only setup call.
|
|
62
62
|
require('../src/toolDetect').detectInstalledTools = (names) => ({ detected: [], missing: names });
|
|
63
|
-
setup.runMdmSetupAllBundle = async () => { calls.mdm++; return { ok: true, skipped: [] }; };
|
|
64
|
-
setup.runSetupAllBundle = async () => { calls.user++; return { ok: true, skipped: [] }; };
|
|
63
|
+
setup.runMdmSetupAllBundle = async (key, o) => { calls.mdm++; calls.mdmOpts = o; return { ok: true, skipped: [] }; };
|
|
64
|
+
setup.runSetupAllBundle = async (key, o) => { calls.user++; calls.userOpts = o; return { ok: true, skipped: [] }; };
|
|
65
65
|
discover.runDiscoveryScan = async (o) => { calls.discovery++; calls.discoveryArgs = o; };
|
|
66
66
|
// User scope resolves the device key (the stored or passed key, swapped for a device key).
|
|
67
67
|
auth.resolveDeviceKey = async () => { calls.loggedIn++; return 'resolved-key'; };
|
|
@@ -90,6 +90,7 @@ async function runOnboard(isRoot, { setCron = false, discoveryKey = 'd', domain,
|
|
|
90
90
|
if (discoveryKey) argv.push('--discovery-key', discoveryKey);
|
|
91
91
|
if (domain) argv.push('--domain', domain);
|
|
92
92
|
if (setCron) argv.push('--set-cron');
|
|
93
|
+
if (skipCowork) argv.push('--skip-cowork');
|
|
93
94
|
const prevExit = process.exitCode;
|
|
94
95
|
process.exitCode = 0;
|
|
95
96
|
await program.parseAsync(argv);
|
|
@@ -186,3 +187,21 @@ test('onboard without sudo WITH --discovery-key → ignored + deprecation warnin
|
|
|
186
187
|
'emits exactly one deprecation warning',
|
|
187
188
|
);
|
|
188
189
|
});
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
test('onboard with sudo → the MDM bundle leaves Cowork capture at its default (on)', async () => {
|
|
193
|
+
const calls = await runOnboard(true);
|
|
194
|
+
assert.equal(calls.mdmOpts.skipCowork, false);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test('onboard --skip-cowork with sudo → the MDM bundle is asked to leave Cowork capture off', async () => {
|
|
198
|
+
const calls = await runOnboard(true, { skipCowork: true });
|
|
199
|
+
assert.equal(calls.mdmOpts.skipCowork, true);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test('onboard --skip-cowork without sudo → the user bundle is unaffected and onboarding succeeds', async () => {
|
|
203
|
+
const calls = await runOnboard(false, { skipCowork: true });
|
|
204
|
+
assert.equal(calls.user, 1);
|
|
205
|
+
assert.equal(calls.userOpts.skipCowork, undefined, 'the user bundle never gets the flag');
|
|
206
|
+
assert.equal(calls.exitCode, 0);
|
|
207
|
+
});
|
package/test/setup-args.test.js
CHANGED
|
@@ -3,7 +3,7 @@ const assert = require('node:assert/strict');
|
|
|
3
3
|
const fs = require('fs');
|
|
4
4
|
const os = require('os');
|
|
5
5
|
const path = require('path');
|
|
6
|
-
const { buildScriptArgs, scriptSupportsBackfill, resolveSetupAllTools, clearUnboundEnvsEverywhere, failureReason, NUKE_ENV_VARS, removeBinaryInstall, removeScheduledRun, runBinaryClear, BINARY_INSTALL_PATHS, configDirForScript } = require('../src/commands/setup');
|
|
6
|
+
const { buildScriptArgs, scriptSupportsBackfill, scriptSupportsCowork, resolveSetupAllTools, clearUnboundEnvsEverywhere, failureReason, NUKE_ENV_VARS, removeBinaryInstall, removeScheduledRun, runBinaryClear, BINARY_INSTALL_PATHS, configDirForScript } = require('../src/commands/setup');
|
|
7
7
|
const scheduled = require('../src/scheduled');
|
|
8
8
|
const { uninstallScheduledRun } = scheduled;
|
|
9
9
|
|
|
@@ -56,6 +56,20 @@ test('buildScriptArgs: backfill:true appends --backfill', () => {
|
|
|
56
56
|
assert.ok(args.includes('--backfill'), args);
|
|
57
57
|
});
|
|
58
58
|
|
|
59
|
+
test('buildScriptArgs: skipCowork appends --skip-cowork only when set', () => {
|
|
60
|
+
assert.ok(buildScriptArgs('sk-x', { mdm: true, skipCowork: true }).endsWith('--skip-cowork'));
|
|
61
|
+
assert.ok(!buildScriptArgs('sk-x', { mdm: true }).includes('cowork'));
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// Only the Claude Code MDM installer writes Claude Desktop's machine-wide config.
|
|
65
|
+
test('scriptSupportsCowork: only the Claude Code MDM script', () => {
|
|
66
|
+
assert.equal(scriptSupportsCowork('claude-code/hooks/mdm/setup.py'), true);
|
|
67
|
+
for (const script of ['claude-code/hooks/setup.py', 'claude-code/gateway/mdm/setup.py', 'codex/hooks/mdm/setup.py',
|
|
68
|
+
'cursor/mdm/setup.py', 'copilot/hooks/mdm/setup.py']) {
|
|
69
|
+
assert.equal(scriptSupportsCowork(script), false, script);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
|
|
59
73
|
// Backfill is supported only by the hooks variants of Claude Code, Codex, and
|
|
60
74
|
// Copilot. Gateway-mode scripts and Cursor have no local transcripts to seed.
|
|
61
75
|
test('scriptSupportsBackfill: hooks variants of claude-code, codex, copilot are supported', () => {
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
const { test, mock } = require('node:test');
|
|
2
|
+
const assert = require('node:assert/strict');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const http = require('http');
|
|
7
|
+
const { Command } = require('commander');
|
|
8
|
+
|
|
9
|
+
// The clear scripts and `unbound-hook clear` tag their removal report with the
|
|
10
|
+
// UNBOUND_CLEAR_* / UNBOUND_REMOVAL_ID env the CLI passes them. These tests run
|
|
11
|
+
// the real commands against a temp HOME. The setup-script download is stubbed
|
|
12
|
+
// with a tiny Python script that only records its env, so no real clear runs.
|
|
13
|
+
|
|
14
|
+
const SRC = path.join(__dirname, '..', 'src');
|
|
15
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
16
|
+
const CLEAR_KEYS = ['UNBOUND_CLEAR_SOURCE', 'UNBOUND_CLEAR_COMMAND', 'UNBOUND_REMOVAL_ID'];
|
|
17
|
+
|
|
18
|
+
function recorderScript(outFile) {
|
|
19
|
+
return [
|
|
20
|
+
'import json, os, sys',
|
|
21
|
+
`keys = ${JSON.stringify(CLEAR_KEYS)}`,
|
|
22
|
+
`with open(${JSON.stringify(outFile)}, 'a') as f:`,
|
|
23
|
+
' f.write(json.dumps({"argv": sys.argv[1:], "env": {k: os.environ.get(k) for k in keys}}) + "\\n")',
|
|
24
|
+
'',
|
|
25
|
+
].join('\n');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Loads src/ fresh against a temp HOME with every machine-touching call stubbed.
|
|
29
|
+
// post: a stub for api.post, or 'real' to send real requests to baseUrl.
|
|
30
|
+
function loadCli({ deviceKey = 'fake-device-key', serial = 'FAKESERIAL123', post, baseUrl = 'https://backend.test' } = {}) {
|
|
31
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'unbound-removal-'));
|
|
32
|
+
const savedHome = process.env.HOME;
|
|
33
|
+
process.env.HOME = home;
|
|
34
|
+
fs.mkdirSync(path.join(home, '.unbound'), { recursive: true });
|
|
35
|
+
const cfg = { base_url: baseUrl };
|
|
36
|
+
if (deviceKey) cfg.api_key = deviceKey;
|
|
37
|
+
fs.writeFileSync(path.join(home, '.unbound', 'config.json'), JSON.stringify(cfg));
|
|
38
|
+
for (const k of Object.keys(require.cache)) if (k.startsWith(SRC)) delete require.cache[k];
|
|
39
|
+
|
|
40
|
+
const log = [];
|
|
41
|
+
const runsFile = path.join(home, 'runs.jsonl');
|
|
42
|
+
const utils = require('../src/utils');
|
|
43
|
+
utils.downloadToFile = async (url, dest) => {
|
|
44
|
+
log.push(`clear:${url.split('/main/')[1]}`);
|
|
45
|
+
fs.writeFileSync(dest, recorderScript(runsFile));
|
|
46
|
+
};
|
|
47
|
+
const api = require('../src/api');
|
|
48
|
+
const realPost = api.post;
|
|
49
|
+
api.post = async (p, opts) => {
|
|
50
|
+
log.push(`post:${opts.body.tool_type}`);
|
|
51
|
+
if (post === 'real') return realPost(p, opts);
|
|
52
|
+
return post ? post(p, opts) : { recorded: true };
|
|
53
|
+
};
|
|
54
|
+
const config = require('../src/config');
|
|
55
|
+
const realClearConfig = config.clearConfig;
|
|
56
|
+
config.clearConfig = () => { log.push('clearConfig'); return true; };
|
|
57
|
+
require('../src/device-serial').getDeviceSerial = async () => serial;
|
|
58
|
+
require('../src/scheduled').uninstallScheduledRun = async () => {};
|
|
59
|
+
const output = require('../src/output');
|
|
60
|
+
for (const k of ['info', 'success', 'warn', 'error']) output[k] = () => {};
|
|
61
|
+
output.spinner = () => ({ succeed() {}, fail() {}, stop() {} });
|
|
62
|
+
const setup = require('../src/commands/setup');
|
|
63
|
+
|
|
64
|
+
const runs = () => (fs.existsSync(runsFile)
|
|
65
|
+
? fs.readFileSync(runsFile, 'utf8').trim().split('\n').map((l) => JSON.parse(l))
|
|
66
|
+
: []);
|
|
67
|
+
const runWith = async (deps, ...argv) => {
|
|
68
|
+
const program = new Command();
|
|
69
|
+
program.exitOverride();
|
|
70
|
+
setup.register(program, deps);
|
|
71
|
+
await program.parseAsync(['node', 'unbound', ...argv]);
|
|
72
|
+
};
|
|
73
|
+
const run = (...argv) => runWith(undefined, ...argv);
|
|
74
|
+
const cleanup = () => {
|
|
75
|
+
config.clearConfig = realClearConfig;
|
|
76
|
+
process.env.HOME = savedHome;
|
|
77
|
+
for (const k of Object.keys(require.cache)) if (k.startsWith(SRC)) delete require.cache[k];
|
|
78
|
+
fs.rmSync(home, { recursive: true, force: true });
|
|
79
|
+
};
|
|
80
|
+
return { setup, api, run, runWith, runs, log, cleanup };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const nonRoot = { skip: (typeof process.getuid === 'function' && process.getuid() === 0) || process.platform === 'win32' };
|
|
84
|
+
|
|
85
|
+
test('setup --clear: every clear script gets the CLI source, command and one removal id', nonRoot, async () => {
|
|
86
|
+
const cli = loadCli();
|
|
87
|
+
try {
|
|
88
|
+
await cli.run('setup', 'cursor', 'claude-code', '--clear');
|
|
89
|
+
const runs = cli.runs();
|
|
90
|
+
assert.equal(runs.length, 3, `expected cursor + both Claude Code modes, got ${JSON.stringify(runs)}`);
|
|
91
|
+
for (const r of runs) {
|
|
92
|
+
assert.ok(r.argv.includes('--clear'), r.argv.join(' '));
|
|
93
|
+
assert.equal(r.env.UNBOUND_CLEAR_SOURCE, 'unbound_cli');
|
|
94
|
+
assert.equal(r.env.UNBOUND_CLEAR_COMMAND, 'unbound setup --clear');
|
|
95
|
+
assert.match(r.env.UNBOUND_REMOVAL_ID, UUID_RE);
|
|
96
|
+
}
|
|
97
|
+
assert.equal(new Set(runs.map((r) => r.env.UNBOUND_REMOVAL_ID)).size, 1, 'one removal id per run');
|
|
98
|
+
} finally {
|
|
99
|
+
cli.cleanup();
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('setup run (not a clear): no removal env, even after a clear run began in-process', nonRoot, async () => {
|
|
104
|
+
const cli = loadCli();
|
|
105
|
+
try {
|
|
106
|
+
cli.setup.beginClearRun('unbound setup --clear');
|
|
107
|
+
await cli.setup.runSetupAllBundle('fake-device-key', { tools: ['cursor'] });
|
|
108
|
+
const runs = cli.runs();
|
|
109
|
+
assert.equal(runs.length, 1);
|
|
110
|
+
assert.ok(!runs[0].argv.includes('--clear'));
|
|
111
|
+
for (const k of CLEAR_KEYS) assert.equal(runs[0].env[k], null, `${k} leaked into a setup run`);
|
|
112
|
+
} finally {
|
|
113
|
+
cli.cleanup();
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('runBinaryClear: passes the run removal env and never claims an MDM initiator', () => {
|
|
118
|
+
const cli = loadCli();
|
|
119
|
+
const bin = path.join(os.tmpdir(), `unbound-hook-${process.pid}`);
|
|
120
|
+
fs.writeFileSync(bin, '#');
|
|
121
|
+
try {
|
|
122
|
+
const { removalId } = cli.setup.beginClearRun('unbound nuke');
|
|
123
|
+
const calls = [];
|
|
124
|
+
cli.setup.runBinaryClear({ binaryPath: bin, runner: (b, args, opts) => { calls.push({ args, opts }); return { status: 0 }; } });
|
|
125
|
+
assert.equal(calls.length, 1);
|
|
126
|
+
assert.deepEqual(calls[0].args, ['clear'], 'no --initiated-by from the CLI');
|
|
127
|
+
const env = calls[0].opts.env;
|
|
128
|
+
assert.equal(env.UNBOUND_CLEAR_SOURCE, 'unbound_cli');
|
|
129
|
+
assert.equal(env.UNBOUND_CLEAR_COMMAND, 'unbound nuke');
|
|
130
|
+
assert.equal(env.UNBOUND_REMOVAL_ID, removalId);
|
|
131
|
+
assert.equal(env.PATH, process.env.PATH, 'the rest of the env is inherited');
|
|
132
|
+
} finally {
|
|
133
|
+
fs.rmSync(bin, { force: true });
|
|
134
|
+
cli.cleanup();
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test('removeBinaryInstall: keeps a removals receipts dir even when a target holds it', () => {
|
|
139
|
+
const { setup, cleanup } = loadCli();
|
|
140
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'unbound-bin-receipts-'));
|
|
141
|
+
const optDir = path.join(tmp, 'opt', 'unbound');
|
|
142
|
+
const removals = path.join(optDir, 'removals');
|
|
143
|
+
fs.mkdirSync(removals, { recursive: true });
|
|
144
|
+
fs.writeFileSync(path.join(removals, 'cursor.json'), '{"tool_type":"cursor"}');
|
|
145
|
+
const logDir = path.join(tmp, 'log');
|
|
146
|
+
fs.mkdirSync(logDir);
|
|
147
|
+
try {
|
|
148
|
+
const { removed, failed } = setup.removeBinaryInstall({
|
|
149
|
+
optDir,
|
|
150
|
+
daemonPlist: path.join(tmp, 'plist'),
|
|
151
|
+
newsyslogConf: path.join(tmp, 'newsyslog'),
|
|
152
|
+
logDir,
|
|
153
|
+
runLaunchctl: false,
|
|
154
|
+
removalsDirs: [removals],
|
|
155
|
+
});
|
|
156
|
+
assert.ok(fs.existsSync(path.join(removals, 'cursor.json')), 'the receipt must survive nuke');
|
|
157
|
+
assert.ok(!fs.existsSync(logDir), 'other targets are still removed');
|
|
158
|
+
assert.ok(removed.some((s) => s.startsWith('log dir')), removed.join('; '));
|
|
159
|
+
assert.ok(failed.some((s) => s.startsWith('install tree')), 'a kept target is reported, not claimed as removed');
|
|
160
|
+
} finally {
|
|
161
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
162
|
+
cleanup();
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test('removeBinaryInstall: default receipts dirs are the per-OS removals paths', () => {
|
|
167
|
+
const { setup, cleanup } = loadCli();
|
|
168
|
+
try {
|
|
169
|
+
const dirs = setup.REMOVALS_DIRS;
|
|
170
|
+
assert.ok(dirs.includes('/Library/Application Support/Unbound/removals'));
|
|
171
|
+
assert.ok(dirs.includes('/var/lib/unbound/removals'));
|
|
172
|
+
assert.ok(dirs.some((d) => /\\Unbound\\removals$/.test(d) && /ProgramData/i.test(d)), dirs.join(', '));
|
|
173
|
+
} finally {
|
|
174
|
+
cleanup();
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
// Hook-mode tool_types, taken from the setup repo's notify_setup_complete calls.
|
|
179
|
+
// Gateway-mode tools (unbound-claude-code, unbound-codex, gemini-cli) report no removal.
|
|
180
|
+
const EXPECTED_TOOL_TYPES = [
|
|
181
|
+
'cursor', 'copilot', 'augment_code', 'antigravity', 'claude-code', 'codex', 'pi',
|
|
182
|
+
];
|
|
183
|
+
|
|
184
|
+
// root: true fakes `sudo nuke` with the binary teardown stubbed, so nothing privileged runs.
|
|
185
|
+
async function runNuke(cli, { root = true } = {}) {
|
|
186
|
+
const deps = root ? {
|
|
187
|
+
isRoot: () => true,
|
|
188
|
+
binaryClear: () => { cli.log.push('binaryClear'); return { ran: true, ok: true }; },
|
|
189
|
+
binaryRemove: () => { cli.log.push('binaryRemove'); return { removed: [], failed: [] }; },
|
|
190
|
+
} : undefined;
|
|
191
|
+
const saved = process.exitCode;
|
|
192
|
+
process.exitCode = 0;
|
|
193
|
+
try {
|
|
194
|
+
await cli.runWith(deps, 'nuke', '--yes');
|
|
195
|
+
return process.exitCode;
|
|
196
|
+
} finally {
|
|
197
|
+
process.exitCode = saved;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
test('sudo nuke: reports each removal before any clear and before the key is wiped', nonRoot, async () => {
|
|
202
|
+
const posts = [];
|
|
203
|
+
const cli = loadCli({ post: async (p, opts) => { posts.push({ p, opts }); return { recorded: true }; } });
|
|
204
|
+
try {
|
|
205
|
+
const before = Date.now();
|
|
206
|
+
const exitCode = await runNuke(cli);
|
|
207
|
+
assert.equal(exitCode, 0);
|
|
208
|
+
assert.deepEqual(posts.map((x) => x.opts.body.tool_type).sort(), [...EXPECTED_TOOL_TYPES].sort());
|
|
209
|
+
|
|
210
|
+
const firstOther = cli.log.findIndex((e) => !e.startsWith('post:'));
|
|
211
|
+
assert.equal(firstOther, posts.length, `events must precede every clear: ${cli.log.join(', ')}`);
|
|
212
|
+
for (const step of ['binaryClear', 'binaryRemove', 'clearConfig']) {
|
|
213
|
+
assert.ok(cli.log.indexOf(step) > firstOther, `${step} runs after the events`);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const runs = cli.runs();
|
|
217
|
+
assert.equal(runs.length, 20, 'every user and MDM tool is still cleared');
|
|
218
|
+
const removalId = runs[0].env.UNBOUND_REMOVAL_ID;
|
|
219
|
+
for (const r of runs) {
|
|
220
|
+
assert.equal(r.env.UNBOUND_CLEAR_COMMAND, 'unbound nuke');
|
|
221
|
+
assert.equal(r.env.UNBOUND_REMOVAL_ID, removalId);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
for (const { p, opts } of posts) {
|
|
225
|
+
assert.equal(p, '/api/v1/setup/removed/');
|
|
226
|
+
assert.equal(opts.apiKey, 'fake-device-key');
|
|
227
|
+
assert.equal(opts.baseUrl, 'https://backend.test');
|
|
228
|
+
assert.equal(opts.timeoutMs, 5000);
|
|
229
|
+
const { cleared_at: clearedAt, ...rest } = opts.body;
|
|
230
|
+
assert.deepEqual(rest, {
|
|
231
|
+
tool_type: rest.tool_type,
|
|
232
|
+
serial_number: 'FAKESERIAL123',
|
|
233
|
+
managed: true,
|
|
234
|
+
initiated_by: 'user',
|
|
235
|
+
source: 'unbound_cli',
|
|
236
|
+
command: 'unbound nuke',
|
|
237
|
+
local_user: process.env.SUDO_USER || os.userInfo().username,
|
|
238
|
+
removal_id: removalId,
|
|
239
|
+
});
|
|
240
|
+
assert.match(clearedAt, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/);
|
|
241
|
+
assert.ok(Date.parse(clearedAt) >= before - 1000);
|
|
242
|
+
}
|
|
243
|
+
} finally {
|
|
244
|
+
cli.cleanup();
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
test('sudo nuke: the events go out in parallel', nonRoot, async () => {
|
|
249
|
+
let inFlight = 0;
|
|
250
|
+
let peak = 0;
|
|
251
|
+
const cli = loadCli({
|
|
252
|
+
post: async () => {
|
|
253
|
+
inFlight += 1;
|
|
254
|
+
peak = Math.max(peak, inFlight);
|
|
255
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
256
|
+
inFlight -= 1;
|
|
257
|
+
return { recorded: true };
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
try {
|
|
261
|
+
await runNuke(cli);
|
|
262
|
+
assert.equal(peak, EXPECTED_TOOL_TYPES.length);
|
|
263
|
+
} finally {
|
|
264
|
+
cli.cleanup();
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
test('nuke without root: sends nothing (the backend drops unmanaged events) and still clears', nonRoot, async () => {
|
|
269
|
+
const cli = loadCli();
|
|
270
|
+
try {
|
|
271
|
+
const exitCode = await runNuke(cli, { root: false });
|
|
272
|
+
assert.equal(exitCode, 0);
|
|
273
|
+
assert.equal(cli.log.filter((e) => e.startsWith('post:')).length, 0);
|
|
274
|
+
assert.equal(cli.runs().length, 10);
|
|
275
|
+
assert.ok(!cli.log.includes('binaryClear'), 'no root, no binary teardown');
|
|
276
|
+
assert.ok(cli.log.includes('clearConfig'));
|
|
277
|
+
} finally {
|
|
278
|
+
cli.cleanup();
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
test('sudo nuke: no device key sends nothing and still clears', nonRoot, async () => {
|
|
283
|
+
const cli = loadCli({ deviceKey: null });
|
|
284
|
+
try {
|
|
285
|
+
const exitCode = await runNuke(cli);
|
|
286
|
+
assert.equal(exitCode, 0);
|
|
287
|
+
assert.equal(cli.log.filter((e) => e.startsWith('post:')).length, 0);
|
|
288
|
+
assert.equal(cli.runs().length, 20);
|
|
289
|
+
assert.ok(cli.log.includes('clearConfig'));
|
|
290
|
+
} finally {
|
|
291
|
+
cli.cleanup();
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
for (const [name, fail] of [
|
|
296
|
+
['an API error', () => { const e = new Error('HTTP 500'); e.statusCode = 500; throw e; }],
|
|
297
|
+
['a timeout', () => { const e = new Error('Request timed out'); e.code = 'ETIMEDOUT'; throw e; }],
|
|
298
|
+
]) {
|
|
299
|
+
test(`sudo nuke: ${name} on the event never stops the wipe or changes the exit code`, nonRoot, async () => {
|
|
300
|
+
const cli = loadCli({ post: async () => fail() });
|
|
301
|
+
try {
|
|
302
|
+
const exitCode = await runNuke(cli);
|
|
303
|
+
assert.equal(exitCode, 0);
|
|
304
|
+
assert.equal(cli.runs().length, 20);
|
|
305
|
+
assert.ok(cli.log.includes('clearConfig'));
|
|
306
|
+
} finally {
|
|
307
|
+
cli.cleanup();
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
test('sudo nuke: no device serial sends nothing (no entry could match) and still clears', nonRoot, async () => {
|
|
313
|
+
const cli = loadCli({ serial: null });
|
|
314
|
+
try {
|
|
315
|
+
assert.equal(await runNuke(cli), 0);
|
|
316
|
+
assert.equal(cli.log.filter((e) => e.startsWith('post:')).length, 0);
|
|
317
|
+
assert.equal(cli.runs().length, 20);
|
|
318
|
+
} finally {
|
|
319
|
+
cli.cleanup();
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
test('every hook-mode MDM tool has a backend tool_type, so sudo nuke reports them all', () => {
|
|
324
|
+
const { setup, cleanup } = loadCli();
|
|
325
|
+
try {
|
|
326
|
+
const hookTools = Object.entries(setup.MDM_TOOLS).filter(([, t]) => !t.script.includes('/gateway/'));
|
|
327
|
+
assert.equal(hookTools.length, EXPECTED_TOOL_TYPES.length);
|
|
328
|
+
for (const [name] of hookTools) {
|
|
329
|
+
assert.ok(EXPECTED_TOOL_TYPES.includes(setup.TOOL_TYPES[name]), `${name} -> ${setup.TOOL_TYPES[name]}`);
|
|
330
|
+
}
|
|
331
|
+
} finally {
|
|
332
|
+
cleanup();
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
test('sudo nuke: a report that never settles is cut off at 8 s and the wipe goes on', nonRoot, async () => {
|
|
337
|
+
let started = 0;
|
|
338
|
+
const cli = loadCli({ post: () => { started += 1; return new Promise(() => {}); } });
|
|
339
|
+
const flush = async () => { for (let i = 0; i < 50; i++) await new Promise((r) => setImmediate(r)); };
|
|
340
|
+
mock.timers.enable({ apis: ['setTimeout'] });
|
|
341
|
+
try {
|
|
342
|
+
const done = runNuke(cli);
|
|
343
|
+
await flush();
|
|
344
|
+
assert.equal(started, EXPECTED_TOOL_TYPES.length, 'all reports started');
|
|
345
|
+
mock.timers.tick(7999);
|
|
346
|
+
await flush();
|
|
347
|
+
assert.ok(!cli.log.some((e) => e.startsWith('clear:')), 'nothing is cleared while the deadline runs');
|
|
348
|
+
mock.timers.tick(1);
|
|
349
|
+
mock.timers.reset();
|
|
350
|
+
const hung = new Promise((_, reject) => setTimeout(() => reject(new Error('nuke still waits on the report')), 10000).unref());
|
|
351
|
+
assert.equal(await Promise.race([done, hung]), 0);
|
|
352
|
+
assert.equal(cli.runs().length, 20, 'every clear still runs after the deadline');
|
|
353
|
+
assert.ok(cli.log.includes('clearConfig'));
|
|
354
|
+
} finally {
|
|
355
|
+
mock.timers.reset();
|
|
356
|
+
cli.cleanup();
|
|
357
|
+
}
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
// Local backend: /api/v1/setup/removed/ sends headers, then one byte every 50 ms forever,
|
|
361
|
+
// which keeps resetting Node's idle timeout. /ok answers normally.
|
|
362
|
+
async function startDripServer() {
|
|
363
|
+
const state = { started: 0, closed: 0 };
|
|
364
|
+
const server = http.createServer((req, res) => {
|
|
365
|
+
if (req.url === '/ok') {
|
|
366
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
367
|
+
res.end('{"ok":true}');
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
state.started += 1;
|
|
371
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
372
|
+
res.write('{');
|
|
373
|
+
const drip = setInterval(() => res.write(' '), 50);
|
|
374
|
+
res.on('close', () => { clearInterval(drip); state.closed += 1; });
|
|
375
|
+
});
|
|
376
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
377
|
+
state.url = `http://127.0.0.1:${server.address().port}`;
|
|
378
|
+
state.connections = () => new Promise((resolve, reject) => server.getConnections((e, n) => (e ? reject(e) : resolve(n))));
|
|
379
|
+
state.stop = () => { server.closeAllConnections(); server.close(); };
|
|
380
|
+
return state;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// Yields to I/O without setTimeout, which a test may have mocked.
|
|
384
|
+
async function until(cond, label, ms = 5000) {
|
|
385
|
+
const start = Date.now();
|
|
386
|
+
while (!cond()) {
|
|
387
|
+
if (Date.now() - start > ms) throw new Error(`timed out waiting for ${label}`);
|
|
388
|
+
await new Promise((r) => setImmediate(r));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
test('sudo nuke: requests still dripping at the deadline are destroyed, leaving no open connection', nonRoot, async () => {
|
|
393
|
+
const srv = await startDripServer();
|
|
394
|
+
const cli = loadCli({ post: 'real', baseUrl: srv.url });
|
|
395
|
+
mock.timers.enable({ apis: ['setTimeout'] });
|
|
396
|
+
try {
|
|
397
|
+
const done = runNuke(cli);
|
|
398
|
+
await until(() => srv.started === EXPECTED_TOOL_TYPES.length, 'every report to reach the server');
|
|
399
|
+
mock.timers.tick(8000);
|
|
400
|
+
mock.timers.reset();
|
|
401
|
+
const hung = new Promise((_, reject) => setTimeout(() => reject(new Error('nuke still waits on the report')), 10000).unref());
|
|
402
|
+
assert.equal(await Promise.race([done, hung]), 0);
|
|
403
|
+
await until(() => srv.closed === EXPECTED_TOOL_TYPES.length, 'the server to see every request closed');
|
|
404
|
+
let open = await srv.connections();
|
|
405
|
+
for (let i = 0; open > 0 && i < 50; i++) {
|
|
406
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
407
|
+
open = await srv.connections();
|
|
408
|
+
}
|
|
409
|
+
assert.equal(open, 0, 'no connection is left open after nuke');
|
|
410
|
+
assert.equal(cli.runs().length, 20, 'every clear still runs');
|
|
411
|
+
} finally {
|
|
412
|
+
mock.timers.reset();
|
|
413
|
+
srv.stop();
|
|
414
|
+
cli.cleanup();
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
test('api request without a signal: unchanged, a normal answer still resolves', async () => {
|
|
419
|
+
const srv = await startDripServer();
|
|
420
|
+
const { api, cleanup } = loadCli({ baseUrl: srv.url });
|
|
421
|
+
try {
|
|
422
|
+
const body = await api.get('/ok', { apiKey: 'fake-device-key', baseUrl: srv.url, timeoutMs: 2000 });
|
|
423
|
+
assert.deepEqual(body, { ok: true });
|
|
424
|
+
} finally {
|
|
425
|
+
srv.stop();
|
|
426
|
+
cleanup();
|
|
427
|
+
}
|
|
428
|
+
});
|