unbound-cli 1.26.3 → 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/package.json +1 -1
- package/src/api.js +11 -1
- 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/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/package.json
CHANGED
package/src/api.js
CHANGED
|
@@ -31,7 +31,7 @@ class ApiError extends Error {
|
|
|
31
31
|
|
|
32
32
|
const DEFAULT_TIMEOUT_MS = 30000;
|
|
33
33
|
|
|
34
|
-
function request(method, path, { body, query, apiKey, baseUrl, timeoutMs } = {}) {
|
|
34
|
+
function request(method, path, { body, query, apiKey, baseUrl, timeoutMs, signal } = {}) {
|
|
35
35
|
// Explicit baseUrl wins over env-var-aware getBaseUrl(). Used by login /
|
|
36
36
|
// setup / onboard so a user's just-passed --backend-url isn't shadowed by a
|
|
37
37
|
// stale UNBOUND_API_URL env var from a prior shell session.
|
|
@@ -109,6 +109,16 @@ function request(method, path, { body, query, apiKey, baseUrl, timeoutMs } = {})
|
|
|
109
109
|
reject(new Error(`Network error: ${err.message}`));
|
|
110
110
|
}
|
|
111
111
|
});
|
|
112
|
+
// Optional AbortSignal: aborting destroys the request, even one whose body is still arriving.
|
|
113
|
+
if (signal) {
|
|
114
|
+
const onAbort = () => {
|
|
115
|
+
req.destroy();
|
|
116
|
+
reject(new Error(`Request to ${url.host} was cancelled.`));
|
|
117
|
+
};
|
|
118
|
+
if (signal.aborted) onAbort();
|
|
119
|
+
else signal.addEventListener('abort', onAbort, { once: true });
|
|
120
|
+
req.on('close', () => signal.removeEventListener('abort', onAbort));
|
|
121
|
+
}
|
|
112
122
|
if (payload) req.write(payload);
|
|
113
123
|
req.end();
|
|
114
124
|
});
|
package/src/commands/onboard.js
CHANGED
|
@@ -60,6 +60,7 @@ function register(program) {
|
|
|
60
60
|
.option('--domain <url>', 'Backend URL for discovery (defaults to configured backend)')
|
|
61
61
|
.option('--set-cron', 'Set up a daily background job to keep governance up to date (under sudo, schedules a discovery scan only — not a full tool re-install)')
|
|
62
62
|
.option('--backfill', 'Seed historical Claude Code / Codex / Copilot sessions from local transcripts into Unbound analytics (Cursor skipped automatically)')
|
|
63
|
+
.option('--skip-cowork', 'With sudo, leave Claude Cowork prompt capture off (it is on by default)')
|
|
63
64
|
.addOption(new Option('--backend-url <url>', 'Override backend URL for setup scripts (dev only)').hideHelp())
|
|
64
65
|
.addOption(new Option('--frontend-url <url>', 'Override frontend URL for setup scripts (dev only)').hideHelp())
|
|
65
66
|
.addOption(new Option('--gateway-url <url>', 'Override gateway URL for setup scripts (dev only)').hideHelp())
|
|
@@ -83,6 +84,7 @@ Only your API key is required — for both per-user and sudo/MDM onboarding.
|
|
|
83
84
|
Examples:
|
|
84
85
|
$ unbound onboard --api-key <USER_KEY>
|
|
85
86
|
$ sudo unbound onboard --api-key <ADMIN_KEY>
|
|
87
|
+
$ sudo unbound onboard --api-key <ADMIN_KEY> --skip-cowork
|
|
86
88
|
$ unbound onboard --api-key <USER_KEY> --backfill
|
|
87
89
|
$ unbound onboard --api-key <USER_KEY> --set-cron
|
|
88
90
|
`)
|
|
@@ -153,7 +155,7 @@ Examples:
|
|
|
153
155
|
output.info('Step 1/2: Installing MDM tool bundle (all users)');
|
|
154
156
|
const setUpPi = shouldSetUpPi(MDM_TOOLS.pi.label, { allUsers: true });
|
|
155
157
|
const { ok, skipped } = await runMdmSetupAllBundle(adminApiKey, {
|
|
156
|
-
backendUrl, frontendUrl, gatewayUrl, backfill: !!opts.backfill,
|
|
158
|
+
backendUrl, frontendUrl, gatewayUrl, backfill: !!opts.backfill, skipCowork: !!opts.skipCowork,
|
|
157
159
|
});
|
|
158
160
|
// A failed setup must NOT report onboarding success. runBatch already
|
|
159
161
|
// reported the failure to the ledger and set exitCode; make the
|
package/src/commands/setup.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const { spawn, spawnSync } = require('child_process');
|
|
2
2
|
const { Option } = require('commander');
|
|
3
|
+
const crypto = require('crypto');
|
|
3
4
|
const fs = require('fs');
|
|
4
5
|
const os = require('os');
|
|
5
6
|
const path = require('path');
|
|
@@ -8,7 +9,7 @@ const output = require('../output');
|
|
|
8
9
|
const telemetry = require('../telemetry');
|
|
9
10
|
const auth = require('../auth');
|
|
10
11
|
const { confirm, downloadToFile, withSecureTempFile } = require('../utils');
|
|
11
|
-
const { reportSetupFailure, exitCodeForError } = require('../setup-report');
|
|
12
|
+
const { reportSetupFailure, reportRemovals, exitCodeForError } = require('../setup-report');
|
|
12
13
|
const claudePaths = require('../claudePaths');
|
|
13
14
|
|
|
14
15
|
const SETUP_BASE_URL = 'https://raw.githubusercontent.com/websentry-ai/setup/refs/heads/main';
|
|
@@ -21,6 +22,29 @@ const SETUP_BASE_URL = 'https://raw.githubusercontent.com/websentry-ai/setup/ref
|
|
|
21
22
|
// branch, so clear/nuke operations never produce this code.
|
|
22
23
|
const EXIT_MDM_PRESENT = 3;
|
|
23
24
|
|
|
25
|
+
// One removal context per clear command run, passed to clear scripts and `unbound-hook clear` via env.
|
|
26
|
+
let clearRun = null;
|
|
27
|
+
|
|
28
|
+
function beginClearRun(command) {
|
|
29
|
+
clearRun = { command, removalId: crypto.randomUUID() };
|
|
30
|
+
return clearRun;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Env for a clear child process; undefined (inherit) when no clear run is active.
|
|
34
|
+
function clearRunEnv() {
|
|
35
|
+
if (!clearRun) return undefined;
|
|
36
|
+
return {
|
|
37
|
+
...process.env,
|
|
38
|
+
UNBOUND_CLEAR_SOURCE: 'unbound_cli',
|
|
39
|
+
UNBOUND_CLEAR_COMMAND: clearRun.command,
|
|
40
|
+
UNBOUND_REMOVAL_ID: clearRun.removalId,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function isClearArgs(args) {
|
|
45
|
+
return /(^|\s)--clear(\s|$)/.test(args);
|
|
46
|
+
}
|
|
47
|
+
|
|
24
48
|
// WSL reports as Linux via uname; only native Windows (cmd.exe / PowerShell)
|
|
25
49
|
// takes the Windows code path. WSL keeps using the Linux curl|python3 pipe.
|
|
26
50
|
function isWindowsNative() {
|
|
@@ -55,6 +79,17 @@ const MDM_TOOLS = {
|
|
|
55
79
|
'pi': { label: 'Pi Coding Agent', script: 'pi/mdm/setup.py' },
|
|
56
80
|
};
|
|
57
81
|
|
|
82
|
+
// Backend tool_type per hook-mode tool; must match the setup scripts' notify_setup_complete slugs.
|
|
83
|
+
const TOOL_TYPES = {
|
|
84
|
+
'cursor': 'cursor',
|
|
85
|
+
'copilot': 'copilot',
|
|
86
|
+
'augment': 'augment_code',
|
|
87
|
+
'antigravity': 'antigravity',
|
|
88
|
+
'claude-code-subscription': 'claude-code',
|
|
89
|
+
'codex-subscription': 'codex',
|
|
90
|
+
'pi': 'pi',
|
|
91
|
+
};
|
|
92
|
+
|
|
58
93
|
// Default MDM tools for `sudo unbound onboard` (subscription mode for Claude Code/Codex since only one can be active)
|
|
59
94
|
const MDM_ALL_TOOLS = ['cursor', 'claude-code-subscription', 'gemini-cli', 'codex-subscription', 'copilot', 'augment', 'antigravity'];
|
|
60
95
|
|
|
@@ -221,6 +256,7 @@ async function runPythonScript(scriptPath, args, { capture }) {
|
|
|
221
256
|
stdio: capture ? ['pipe', 'pipe', 'pipe'] : 'inherit',
|
|
222
257
|
shell: false,
|
|
223
258
|
windowsHide: true,
|
|
259
|
+
env: isClearArgs(args) ? clearRunEnv() : undefined,
|
|
224
260
|
});
|
|
225
261
|
let out = '';
|
|
226
262
|
// stderr is also kept on its own. Python block-buffers stdout when piped,
|
|
@@ -288,7 +324,7 @@ async function syncWslLogonTask(tools, clear) {
|
|
|
288
324
|
* their browser-auth host) and to MDM scripts as --frontend-url (persist-only,
|
|
289
325
|
* no auth flow). Either way it lands in ~/.unbound/config.json as frontend_url.
|
|
290
326
|
*/
|
|
291
|
-
function buildScriptArgs(apiKey, { backendUrl, frontendUrl, gatewayUrl, clear, mdm, backfill, configDir } = {}) {
|
|
327
|
+
function buildScriptArgs(apiKey, { backendUrl, frontendUrl, gatewayUrl, clear, mdm, backfill, skipCowork, configDir } = {}) {
|
|
292
328
|
// --clear runs no auth in the Python scripts, so the key may be absent. Omit
|
|
293
329
|
// the flag entirely rather than passing --api-key 'undefined'.
|
|
294
330
|
let args = apiKey ? `--api-key ${shellEscape(apiKey)}` : '';
|
|
@@ -298,9 +334,17 @@ function buildScriptArgs(apiKey, { backendUrl, frontendUrl, gatewayUrl, clear, m
|
|
|
298
334
|
if (configDir) args += ` --config-dir ${shellEscape(configDir)}`;
|
|
299
335
|
if (clear) args += ' --clear';
|
|
300
336
|
if (backfill) args += ' --backfill';
|
|
337
|
+
if (skipCowork) args += ' --skip-cowork';
|
|
301
338
|
return args.trim();
|
|
302
339
|
}
|
|
303
340
|
|
|
341
|
+
// Only the Claude Code MDM installer writes Claude Desktop's machine-wide config, where Cowork capture is on by default.
|
|
342
|
+
const COWORK_SCRIPT = MDM_TOOLS['claude-code-subscription'].script;
|
|
343
|
+
|
|
344
|
+
function scriptSupportsCowork(scriptPath) {
|
|
345
|
+
return scriptPath === COWORK_SCRIPT;
|
|
346
|
+
}
|
|
347
|
+
|
|
304
348
|
// User-level Claude install scripts that honor CLAUDE_CONFIG_DIR. MDM variants are
|
|
305
349
|
// excluded — they install per managed-user home, not the admin's env.
|
|
306
350
|
const CLAUDE_CONFIG_DIR_SCRIPTS = new Set([
|
|
@@ -374,7 +418,7 @@ async function runSetupScript(scriptPath, apiKey, { clear = false, backendUrl, f
|
|
|
374
418
|
* download exited 0 because dash has no pipefail — is closed.
|
|
375
419
|
*/
|
|
376
420
|
function runScriptPiped(scriptPath, args) {
|
|
377
|
-
const isClear =
|
|
421
|
+
const isClear = isClearArgs(args);
|
|
378
422
|
return runPythonScript(scriptPath, args, { capture: true }).then((r) => {
|
|
379
423
|
if (!isClear && !(r && r.mdmSkipped)) warnIfHooksMisplaced(scriptPath);
|
|
380
424
|
return r;
|
|
@@ -465,6 +509,21 @@ const BINARY_INSTALL_PATHS = Object.freeze({
|
|
|
465
509
|
logDir: '/var/log/unbound',
|
|
466
510
|
});
|
|
467
511
|
|
|
512
|
+
// Receipts MDM clears leave for the next managed setup run; nuke must never delete them.
|
|
513
|
+
const REMOVALS_DIRS = Object.freeze([
|
|
514
|
+
'/Library/Application Support/Unbound/removals',
|
|
515
|
+
'/var/lib/unbound/removals',
|
|
516
|
+
path.win32.join(process.env.ProgramData || 'C:\\ProgramData', 'Unbound', 'removals'),
|
|
517
|
+
]);
|
|
518
|
+
|
|
519
|
+
function holdsRemovalsDir(target, removalsDirs) {
|
|
520
|
+
// Skip another OS's path: resolving a relative one would join it onto the cwd.
|
|
521
|
+
return removalsDirs.filter((dir) => path.isAbsolute(dir)).some((dir) => {
|
|
522
|
+
const rel = path.relative(path.resolve(target), path.resolve(dir));
|
|
523
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
|
|
468
527
|
// Tears down the privileged binary install. Best-effort: a failure on any
|
|
469
528
|
// single path is logged via output.warn AND pushed onto the returned
|
|
470
529
|
// `failed` array, but never aborts the rest. Bootout the daemon FIRST so
|
|
@@ -484,6 +543,7 @@ function removeBinaryInstall({
|
|
|
484
543
|
newsyslogConf = BINARY_INSTALL_PATHS.newsyslogConf,
|
|
485
544
|
logDir = BINARY_INSTALL_PATHS.logDir,
|
|
486
545
|
runLaunchctl = process.platform === 'darwin',
|
|
546
|
+
removalsDirs = REMOVALS_DIRS,
|
|
487
547
|
_confirmProductionPaths = false,
|
|
488
548
|
} = {}) {
|
|
489
549
|
const usesProdDefaults =
|
|
@@ -522,6 +582,11 @@ function removeBinaryInstall({
|
|
|
522
582
|
for (const [label, p] of targets) {
|
|
523
583
|
try {
|
|
524
584
|
if (!fs.existsSync(p)) continue;
|
|
585
|
+
if (holdsRemovalsDir(p, removalsDirs)) {
|
|
586
|
+
output.warn(`nuke: kept ${label} (${p}): it holds removal receipts.`);
|
|
587
|
+
failed.push(`${label} (${p})`);
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
525
590
|
fs.rmSync(p, { recursive: true, force: true });
|
|
526
591
|
removed.push(`${label} (${p})`);
|
|
527
592
|
} catch (err) {
|
|
@@ -553,7 +618,8 @@ function runBinaryClear({
|
|
|
553
618
|
if (!present) return { ran: false, ok: true };
|
|
554
619
|
try {
|
|
555
620
|
// timeout so a hung clear can never block nuke from removing the binary.
|
|
556
|
-
|
|
621
|
+
// No `--initiated-by mdm`: the CLI is always run by a person.
|
|
622
|
+
const r = runner(binaryPath, ['clear'], { stdio: 'pipe', timeout: 120000, killSignal: 'SIGKILL', env: clearRunEnv() });
|
|
557
623
|
if (r.error) {
|
|
558
624
|
const why = r.error.code === 'ETIMEDOUT' ? 'timed out (120s)' : r.error.message;
|
|
559
625
|
output.warn(`nuke: unbound-hook clear ${why}; continuing.`);
|
|
@@ -770,7 +836,8 @@ async function clearToolsBestEffort(layer, tools, { mdm, backendUrl, gatewayUrl,
|
|
|
770
836
|
return failed;
|
|
771
837
|
}
|
|
772
838
|
|
|
773
|
-
|
|
839
|
+
// nuke's privileged steps are injectable so tests never touch the real machine.
|
|
840
|
+
function register(program, { isRoot = hasRootPrivileges, binaryClear = runBinaryClear, binaryRemove = removeBinaryInstall } = {}) {
|
|
774
841
|
const setup = program
|
|
775
842
|
.command('setup')
|
|
776
843
|
.argument('[tools...]', 'Tools to set up')
|
|
@@ -787,6 +854,7 @@ function register(program) {
|
|
|
787
854
|
.option('--gateway', 'Use gateway mode for Claude Code / Codex (Unbound as AI provider)')
|
|
788
855
|
.option('--all', 'Set up the default bundle: Cursor, Copilot, Augment, Antigravity, Claude Code (hooks), Codex (hooks)')
|
|
789
856
|
.option('--backfill', 'Seed historical Claude Code / Codex / Copilot sessions from local transcripts into Unbound analytics (subscription/hooks mode only; Cursor unsupported)')
|
|
857
|
+
.option('--skip-cowork', 'With sudo, leave Claude Cowork prompt capture off (it is on by default)')
|
|
790
858
|
.addOption(new Option('--backend-url <url>', 'Override backend URL for setup scripts (dev only)').hideHelp())
|
|
791
859
|
.addOption(new Option('--frontend-url <url>', 'Override frontend URL for setup scripts (dev only)').hideHelp())
|
|
792
860
|
.addOption(new Option('--gateway-url <url>', 'Override gateway URL for setup scripts (dev only)').hideHelp())
|
|
@@ -833,6 +901,7 @@ Examples:
|
|
|
833
901
|
Configure all users on the device (MDM/org scope — run with sudo):
|
|
834
902
|
$ sudo unbound setup --all --api-key <MDM_KEY> Configure all users (MDM)
|
|
835
903
|
$ sudo unbound setup cursor codex-subscription --api-key <MDM_KEY> Configure specific tools for all users
|
|
904
|
+
$ sudo unbound setup --all --api-key <MDM_KEY> --skip-cowork Leave Claude Cowork prompt capture off
|
|
836
905
|
$ sudo unbound setup --clear --all Remove config for all users
|
|
837
906
|
|
|
838
907
|
Seed historical sessions (Claude Code / Codex subscription mode + Copilot):
|
|
@@ -861,7 +930,9 @@ Examples:
|
|
|
861
930
|
|
|
862
931
|
When setting up, if you are not logged in and --api-key is not provided, the
|
|
863
932
|
browser opens automatically to authenticate first. Clearing (--clear) never
|
|
864
|
-
requires authentication.
|
|
933
|
+
requires authentication. Under sudo, clearing a tool reports the removal to
|
|
934
|
+
Unbound when a device key is present. Gateway-mode tools (Claude Code gateway,
|
|
935
|
+
Codex gateway, Gemini CLI) are not reported.
|
|
865
936
|
|
|
866
937
|
If an MDM (organization-managed) setup is already present for a tool, user-level
|
|
867
938
|
setup for that tool is skipped automatically — the managed configuration already
|
|
@@ -890,6 +961,7 @@ must update the MDM configuration.
|
|
|
890
961
|
// Scope is auto-detected from privileges: with sudo/root we configure
|
|
891
962
|
// every user on the device (MDM scope); without it, just the current
|
|
892
963
|
// user. URLs were already persisted above and apply to both scopes.
|
|
964
|
+
if (opts.clear) beginClearRun('unbound setup --clear');
|
|
893
965
|
const isMdm = hasRootPrivileges();
|
|
894
966
|
output.info(scopeNotice(isMdm));
|
|
895
967
|
if (isMdm) {
|
|
@@ -969,6 +1041,7 @@ must update the MDM configuration.
|
|
|
969
1041
|
clear: opts.clear,
|
|
970
1042
|
mdm: true,
|
|
971
1043
|
backfill: opts.backfill && scriptSupportsBackfill(tool.script),
|
|
1044
|
+
skipCowork: !!opts.skipCowork && !opts.clear && scriptSupportsCowork(tool.script),
|
|
972
1045
|
configDir: configDirForScript(tool.script),
|
|
973
1046
|
});
|
|
974
1047
|
return runScriptPiped(tool.script, toolArgs);
|
|
@@ -980,8 +1053,7 @@ must update the MDM configuration.
|
|
|
980
1053
|
return;
|
|
981
1054
|
}
|
|
982
1055
|
|
|
983
|
-
//
|
|
984
|
-
// files without calling the API — so don't force a login for --clear.
|
|
1056
|
+
// User-level clear scripts only remove files and call no API, so --clear needs no login.
|
|
985
1057
|
const apiKey = opts.clear ? config.getDeviceKey() : await auth.resolveDeviceKey({
|
|
986
1058
|
apiKey: opts.apiKey,
|
|
987
1059
|
baseUrl: written.base_url,
|
|
@@ -1218,9 +1290,11 @@ What it clears:
|
|
|
1218
1290
|
- Stored credentials and settings (~/.unbound/config.json and the CLI key in the OS keychain).
|
|
1219
1291
|
|
|
1220
1292
|
After it finishes, run \`unbound login\` (or \`unbound onboard\`) to set things up
|
|
1221
|
-
fresh.
|
|
1222
|
-
|
|
1223
|
-
|
|
1293
|
+
fresh. Nuke itself needs no login or API key. Under sudo, it reports each
|
|
1294
|
+
removal to Unbound before it clears anything, when a device key is present.
|
|
1295
|
+
Gateway-mode tools are not reported. The scheduled-scan teardown runs fully
|
|
1296
|
+
offline; the per-tool and MDM clears fetch their setup scripts, so those steps
|
|
1297
|
+
still need network.
|
|
1224
1298
|
|
|
1225
1299
|
Examples:
|
|
1226
1300
|
$ sudo unbound nuke Remove everything on the device (asks to confirm)
|
|
@@ -1235,7 +1309,7 @@ Examples:
|
|
|
1235
1309
|
// remove system-level MDM config for all users; otherwise we clear only
|
|
1236
1310
|
// this user. Detecting elevation up front keeps the confirmation honest
|
|
1237
1311
|
// (no promising MDM removal we can't perform).
|
|
1238
|
-
const includeMdm =
|
|
1312
|
+
const includeMdm = isRoot();
|
|
1239
1313
|
|
|
1240
1314
|
if (!opts.yes) {
|
|
1241
1315
|
output.warn(includeMdm
|
|
@@ -1248,12 +1322,28 @@ Examples:
|
|
|
1248
1322
|
}
|
|
1249
1323
|
}
|
|
1250
1324
|
|
|
1325
|
+
const run = beginClearRun('unbound nuke');
|
|
1326
|
+
|
|
1251
1327
|
// Resolve URLs before wiping config so the clear scripts get consistent
|
|
1252
1328
|
// flags. Clearing is URL-independent, but this matches the other clear paths.
|
|
1253
1329
|
const backendUrl = config.getBaseUrl();
|
|
1254
1330
|
const gatewayUrl = config.getGatewayUrl();
|
|
1255
1331
|
const frontendUrl = config.getFrontendUrl();
|
|
1256
1332
|
|
|
1333
|
+
// Root only (the backend drops unmanaged events), and before any clear removes the configs and the key.
|
|
1334
|
+
if (includeMdm) {
|
|
1335
|
+
await reportRemovals({
|
|
1336
|
+
// Gateway-mode tools report no removal, so the backend has nothing to match for them.
|
|
1337
|
+
toolTypes: Object.entries(MDM_TOOLS)
|
|
1338
|
+
.filter(([, tool]) => !tool.script.includes('/gateway/'))
|
|
1339
|
+
.map(([name]) => TOOL_TYPES[name]),
|
|
1340
|
+
removalId: run.removalId,
|
|
1341
|
+
command: run.command,
|
|
1342
|
+
managed: true,
|
|
1343
|
+
backendUrl,
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1257
1347
|
console.log('');
|
|
1258
1348
|
const userTools = Object.keys(SETUP_TOOL_MAP).map(name => ({ name, ...SETUP_TOOL_MAP[name] }));
|
|
1259
1349
|
const userFailed = await clearToolsBestEffort('user', userTools, { mdm: false, backendUrl, gatewayUrl, frontendUrl });
|
|
@@ -1274,8 +1364,8 @@ Examples:
|
|
|
1274
1364
|
// Deregister managed configs via the binary's own clear FIRST (works
|
|
1275
1365
|
// without python3, which a binary-only machine lacks); reuses the same
|
|
1276
1366
|
// clear_setup() as the python clears. Must precede the rm below.
|
|
1277
|
-
const binClear =
|
|
1278
|
-
const { removed: binaryRemoved, failed: bf } =
|
|
1367
|
+
const binClear = binaryClear();
|
|
1368
|
+
const { removed: binaryRemoved, failed: bf } = binaryRemove({ _confirmProductionPaths: true });
|
|
1279
1369
|
binaryFailed = bf;
|
|
1280
1370
|
if (binClear.ran && !binClear.ok) binaryFailed.push('unbound-hook clear');
|
|
1281
1371
|
if (binaryRemoved.length) {
|
|
@@ -1306,7 +1396,7 @@ Examples:
|
|
|
1306
1396
|
const keyRemoved = config.clearConfig();
|
|
1307
1397
|
output.success('Stored credentials and settings removed.');
|
|
1308
1398
|
// As root, the keychain reached is root's, not the invoking user's.
|
|
1309
|
-
if (
|
|
1399
|
+
if (isRoot()) output.info('Run `unbound logout` without sudo to remove your CLI key from the keychain.');
|
|
1310
1400
|
else if (!keyRemoved) output.warn('Could not remove the CLI key from the OS keychain. Unlock it and run `unbound logout`.');
|
|
1311
1401
|
|
|
1312
1402
|
console.log('');
|
|
@@ -1364,7 +1454,7 @@ async function runSetupAllBundle(apiKey, { backendUrl, frontendUrl, gatewayUrl,
|
|
|
1364
1454
|
* Caller must ensure the process is running as root.
|
|
1365
1455
|
* Returns true on success, false on failure.
|
|
1366
1456
|
*/
|
|
1367
|
-
async function runMdmSetupAllBundle(adminApiKey, { backendUrl, frontendUrl, gatewayUrl, backfill = false, tools = MDM_ALL_TOOLS } = {}) {
|
|
1457
|
+
async function runMdmSetupAllBundle(adminApiKey, { backendUrl, frontendUrl, gatewayUrl, backfill = false, skipCowork = false, tools = MDM_ALL_TOOLS } = {}) {
|
|
1368
1458
|
const resolvedTools = tools.map(name => ({ name, ...MDM_TOOLS[name] }));
|
|
1369
1459
|
if (backfill) {
|
|
1370
1460
|
for (const tool of resolvedTools) {
|
|
@@ -1375,6 +1465,7 @@ async function runMdmSetupAllBundle(adminApiKey, { backendUrl, frontendUrl, gate
|
|
|
1375
1465
|
const args = buildScriptArgs(adminApiKey, {
|
|
1376
1466
|
backendUrl, frontendUrl, gatewayUrl, mdm: true,
|
|
1377
1467
|
backfill: backfill && scriptSupportsBackfill(tool.script),
|
|
1468
|
+
skipCowork: skipCowork && scriptSupportsCowork(tool.script),
|
|
1378
1469
|
configDir: configDirForScript(tool.script),
|
|
1379
1470
|
});
|
|
1380
1471
|
return runScriptPiped(tool.script, args);
|
|
@@ -1397,9 +1488,11 @@ module.exports = {
|
|
|
1397
1488
|
MDM_ALL_TOOLS,
|
|
1398
1489
|
SETUP_TOOL_MAP,
|
|
1399
1490
|
MDM_TOOLS,
|
|
1491
|
+
TOOL_TYPES,
|
|
1400
1492
|
buildScriptArgs,
|
|
1401
1493
|
configDirForScript,
|
|
1402
1494
|
scriptSupportsBackfill,
|
|
1495
|
+
scriptSupportsCowork,
|
|
1403
1496
|
resolveSetupAllTools,
|
|
1404
1497
|
clearUnboundEnvsEverywhere,
|
|
1405
1498
|
failureReason,
|
|
@@ -1408,4 +1501,6 @@ module.exports = {
|
|
|
1408
1501
|
removeScheduledRun,
|
|
1409
1502
|
runBinaryClear,
|
|
1410
1503
|
BINARY_INSTALL_PATHS,
|
|
1504
|
+
REMOVALS_DIRS,
|
|
1505
|
+
beginClearRun,
|
|
1411
1506
|
};
|
package/src/index.js
CHANGED
|
@@ -104,7 +104,7 @@ MDM SETUP (all users on the device — run setup with sudo)
|
|
|
104
104
|
$ sudo unbound setup --all --api-key KEY
|
|
105
105
|
$ sudo unbound setup cursor copilot codex-subscription --api-key KEY
|
|
106
106
|
$ sudo unbound setup claude-code-subscription codex-subscription gemini-cli --api-key KEY
|
|
107
|
-
$ sudo unbound setup --clear cursor codex-subscription (no API key needed
|
|
107
|
+
$ sudo unbound setup --clear cursor codex-subscription (no API key needed; reports the removal when a device key is present)
|
|
108
108
|
|
|
109
109
|
MDM AI TOOLS DISCOVERY
|
|
110
110
|
--domain defaults to the configured backend URL (set via "unbound config set-backend-url")
|
package/src/setup-report.js
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
const os = require('os');
|
|
25
25
|
const api = require('./api');
|
|
26
26
|
const config = require('./config');
|
|
27
|
+
const deviceSerial = require('./device-serial');
|
|
27
28
|
|
|
28
29
|
// The failure report is best-effort telemetry that runs while the user is
|
|
29
30
|
// already waiting on a real setup failure. Bound it tightly (well under the
|
|
@@ -107,8 +108,61 @@ async function reportSetupFailure({ step, exitCode, apiKey, backendUrl } = {}) {
|
|
|
107
108
|
}
|
|
108
109
|
}
|
|
109
110
|
|
|
111
|
+
const REMOVAL_TIMEOUT_MS = 5000;
|
|
112
|
+
const REMOVAL_DEADLINE_MS = 8000;
|
|
113
|
+
|
|
114
|
+
function localUser() {
|
|
115
|
+
try {
|
|
116
|
+
return String(process.env.SUDO_USER || os.userInfo().username).slice(0, 100);
|
|
117
|
+
} catch {
|
|
118
|
+
return '';
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function sendRemovals({ toolTypes, removalId, command, managed, backendUrl }, signal) {
|
|
123
|
+
const key = config.getDeviceKey();
|
|
124
|
+
if (!key) return;
|
|
125
|
+
const serial = await deviceSerial.getDeviceSerial();
|
|
126
|
+
if (!serial) return;
|
|
127
|
+
const fields = {
|
|
128
|
+
serial_number: serial,
|
|
129
|
+
managed: Boolean(managed),
|
|
130
|
+
initiated_by: 'user',
|
|
131
|
+
source: 'unbound_cli',
|
|
132
|
+
command,
|
|
133
|
+
local_user: localUser(),
|
|
134
|
+
removal_id: removalId,
|
|
135
|
+
cleared_at: new Date().toISOString(),
|
|
136
|
+
};
|
|
137
|
+
await Promise.allSettled(toolTypes.map((toolType) => api.post('/api/v1/setup/removed/', {
|
|
138
|
+
apiKey: key,
|
|
139
|
+
baseUrl: backendUrl,
|
|
140
|
+
timeoutMs: REMOVAL_TIMEOUT_MS,
|
|
141
|
+
signal,
|
|
142
|
+
body: { tool_type: toolType, ...fields },
|
|
143
|
+
})));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Best-effort POST /api/v1/setup/removed/ per tool, in parallel; never rejects, so it can't change the clear's exit code.
|
|
147
|
+
async function reportRemovals(args = {}) {
|
|
148
|
+
let timer;
|
|
149
|
+
const controller = new AbortController();
|
|
150
|
+
// A response that stalls after its headers never settles api.post, so the whole report has a hard deadline.
|
|
151
|
+
const deadline = new Promise((resolve) => { timer = setTimeout(resolve, REMOVAL_DEADLINE_MS); });
|
|
152
|
+
try {
|
|
153
|
+
await Promise.race([sendRemovals(args, controller.signal), deadline]);
|
|
154
|
+
} catch {
|
|
155
|
+
// Same rule as reportSetupFailure: reporting never surfaces over the clear.
|
|
156
|
+
} finally {
|
|
157
|
+
clearTimeout(timer);
|
|
158
|
+
// Destroys any request still open, so a dripping server can't hold the process after nuke.
|
|
159
|
+
controller.abort();
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
110
163
|
module.exports = {
|
|
111
164
|
reportSetupFailure,
|
|
165
|
+
reportRemovals,
|
|
112
166
|
deviceIdentifier,
|
|
113
167
|
exitCodeForError,
|
|
114
168
|
EXIT_THROWN,
|
package/src/toolHealth.js
CHANGED
|
@@ -169,7 +169,7 @@ function keyHelperCheck(label, file, kind = 'structural') {
|
|
|
169
169
|
}
|
|
170
170
|
const ok = body.includes(UNBOUND_KEY_HELPER_TOKEN);
|
|
171
171
|
return {
|
|
172
|
-
name: label, ok, kind,
|
|
172
|
+
name: label, ok, kind, foreign: !ok,
|
|
173
173
|
detail: ok ? file : `present but not written by Unbound (${file})`,
|
|
174
174
|
summary: ok ? `${label.toLowerCase()} missing` : `${label.toLowerCase()} not ours`,
|
|
175
175
|
};
|
|
@@ -218,14 +218,15 @@ function configDeviceToken() {
|
|
|
218
218
|
// Env wins when present so a stale exported key is still validated; setup keeps the token in ~/.unbound/config.json and removes the env var.
|
|
219
219
|
function deviceTokenCheck(legacyName) {
|
|
220
220
|
const check = envKeyCheck('API key env', 'UNBOUND_DEVICE_TOKEN');
|
|
221
|
-
|
|
221
|
+
// deviceWide: login state shared by every mode, so it doesn't show which mode is installed.
|
|
222
|
+
if (check.ok) return { ...check, deviceWide: true };
|
|
222
223
|
const legacy = envKeyCheck('API key env', legacyName);
|
|
223
224
|
if (legacy.ok) return legacy;
|
|
224
225
|
const value = configDeviceToken();
|
|
225
226
|
if (!value) return check;
|
|
226
227
|
return {
|
|
227
228
|
name: 'API key env', ok: true, kind: 'aux', detail: 'device token set (config.json)', summary: 'API key set',
|
|
228
|
-
keyCheck: true, envName: 'device token', value, candidates: [value],
|
|
229
|
+
keyCheck: true, envName: 'device token', value, candidates: [value], deviceWide: true,
|
|
229
230
|
};
|
|
230
231
|
}
|
|
231
232
|
|
|
@@ -349,6 +350,11 @@ function refsUnbound(obj) {
|
|
|
349
350
|
// equality-checked (WEB-4949) — per-tool keys can legitimately differ from
|
|
350
351
|
// the stored login key. Use `validateToolKeys` post-detection to verify each
|
|
351
352
|
// captured key against the gateway.
|
|
353
|
+
// Root-level openai_base_url, as Codex reads it (a comment or a key in a table doesn't count).
|
|
354
|
+
function codexBaseUrl() {
|
|
355
|
+
try { return TOML.parse((readText('~/.codex/config.toml') || '').replace(/^\uFEFF/, '')).openai_base_url; } catch { return undefined; }
|
|
356
|
+
}
|
|
357
|
+
|
|
352
358
|
function buildVariants(gatewayUrl, binaryPath) {
|
|
353
359
|
const gw = (gatewayUrl || GATEWAY_DEFAULT).replace(/\/+$/, ''); // setup rstrips too
|
|
354
360
|
return [
|
|
@@ -388,13 +394,14 @@ function buildVariants(gatewayUrl, binaryPath) {
|
|
|
388
394
|
// winning when both are set. Both live under [features], so a hooks key in any
|
|
389
395
|
// other table isn't this flag; an unparseable config (which Codex couldn't load
|
|
390
396
|
// either) reads as not enabled.
|
|
391
|
-
|
|
397
|
+
// configOnly: a config line like the hooks entry, so on its own it doesn't show the mode is installed.
|
|
398
|
+
{ ...configCheck('Hooks feature flag', '~/.codex/config.toml', { json: false, test: (t) => {
|
|
392
399
|
let cfg;
|
|
393
400
|
try { cfg = TOML.parse(t.replace(/^\uFEFF/, '')); } catch { return false; } // tolerate a UTF-8 BOM, like readJson
|
|
394
401
|
const features = cfg.features;
|
|
395
402
|
if (!features || typeof features !== 'object') return false;
|
|
396
403
|
return features.hooks === undefined ? features.codex_hooks === true : features.hooks === true;
|
|
397
|
-
} }, { short: 'codex hooks not enabled', kind: 'aux' }), // aux: an org install leaves it set with no user hook
|
|
404
|
+
} }, { short: 'codex hooks not enabled', kind: 'aux' }), configOnly: true }, // aux: an org install leaves it set with no user hook
|
|
398
405
|
scriptCheck('Hook script', '~/.codex/hooks/unbound.py'),
|
|
399
406
|
deviceTokenCheck('UNBOUND_CODEX_API_KEY'),
|
|
400
407
|
],
|
|
@@ -402,7 +409,8 @@ function buildVariants(gatewayUrl, binaryPath) {
|
|
|
402
409
|
{
|
|
403
410
|
key: 'codex-gateway', label: 'Codex (gateway)', family: 'codex', mode: 'gateway',
|
|
404
411
|
checks: () => [
|
|
405
|
-
|
|
412
|
+
// foreign: a base url that isn't our gateway is the user's own endpoint, never a leftover to fix.
|
|
413
|
+
{ ...configCheck('Config', '~/.codex/config.toml', { json: false, test: (t) => /openai_base_url\s*=/.test(t) }), foreign: codexBaseUrl() !== `${gw}/v1` },
|
|
406
414
|
envKeyCheck('API key env', 'OPENAI_API_KEY'),
|
|
407
415
|
],
|
|
408
416
|
},
|
|
@@ -511,7 +519,15 @@ function detectTools({ gatewayUrl, _mdmDirs, _binaryPath, _codexManagedOnly } =
|
|
|
511
519
|
if (present.length) {
|
|
512
520
|
// Prefer a tampered variant so a conflicting/partial install surfaces (and
|
|
513
521
|
// `--fix` reinstalls it). Flag when more than one mode is present at once.
|
|
514
|
-
|
|
522
|
+
// A healthy mode beside config-only leftovers is the real install: report it so `--fix` reinstalls it.
|
|
523
|
+
const leftover = (x) => x.status === 'tampered' && x.checks.every((c, i) => c.deviceWide || c.configOnly || (i === 0 ? c.ok : !c.ok && !c.warn));
|
|
524
|
+
const healthy = present.filter((x) => x.status === 'healthy');
|
|
525
|
+
const keep = present.length > 1 && healthy.length === 1 && !healthy[0].checks.some((c) => c.foreign)
|
|
526
|
+
&& present.every((x) => x === healthy[0] || leftover(x));
|
|
527
|
+
// Setup keeps a key helper it didn't write, so a leftover holding one leaves nothing to fix.
|
|
528
|
+
const fixable = !present.some((x) => x.checks.some((c) => c.foreign));
|
|
529
|
+
const active = keep ? Object.assign(healthy[0], { status: fixable ? 'tampered' : 'healthy' })
|
|
530
|
+
: present.find((x) => x.status === 'tampered') || present[0];
|
|
515
531
|
if (present.length > 1) active.conflict = true;
|
|
516
532
|
active.label = active.label.replace(/ \(.*\)$/, ''); // mode is shown via .mode
|
|
517
533
|
families.push(active);
|
|
@@ -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
|
+
});
|
package/test/tool-health.test.js
CHANGED
|
@@ -143,6 +143,167 @@ test('detectTools: both claude-code modes present at once → one line, flagged
|
|
|
143
143
|
});
|
|
144
144
|
});
|
|
145
145
|
|
|
146
|
+
// --- a healthy mode beside a config-only leftover of the other mode ---
|
|
147
|
+
const MODE_ENVS = ['UNBOUND_API_KEY', 'ANTHROPIC_BASE_URL', 'OPENAI_API_KEY', 'UNBOUND_DEVICE_TOKEN', 'UNBOUND_CLAUDE_API_KEY', 'UNBOUND_CODEX_API_KEY', 'CLAUDE_CONFIG_DIR'];
|
|
148
|
+
function withEnv(vars, fn) {
|
|
149
|
+
const saved = Object.fromEntries(MODE_ENVS.map((n) => [n, process.env[n]]));
|
|
150
|
+
for (const n of MODE_ENVS) delete process.env[n];
|
|
151
|
+
Object.assign(process.env, vars);
|
|
152
|
+
try { return fn(); } finally {
|
|
153
|
+
for (const n of MODE_ENVS) { if (saved[n] === undefined) delete process.env[n]; else process.env[n] = saved[n]; }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const loggedIn = (tmp) => writeFile(path.join(tmp, '.unbound', 'config.json'), JSON.stringify({ api_key: 'k' }));
|
|
157
|
+
const claudeOf = (th) => th.detectTools().find((t) => t.family === 'claude-code');
|
|
158
|
+
|
|
159
|
+
test('detectTools: healthy claude subscription + dangling gateway key helper → reports subscription so --fix keeps that mode', () => {
|
|
160
|
+
withHome((tmp, th) => withEnv({}, () => {
|
|
161
|
+
loggedIn(tmp);
|
|
162
|
+
const hook = path.join(tmp, '.claude', 'hooks', 'unbound.py');
|
|
163
|
+
writeFile(path.join(tmp, '.claude', 'settings.json'), JSON.stringify({
|
|
164
|
+
hooks: { PreToolUse: [{ command: hook }] },
|
|
165
|
+
apiKeyHelper: path.join(tmp, '.claude', 'anthropic_key.sh'), // script is gone
|
|
166
|
+
}));
|
|
167
|
+
writeFile(hook, '#');
|
|
168
|
+
const claude = claudeOf(th);
|
|
169
|
+
assert.equal(claude.key, 'claude-code-subscription');
|
|
170
|
+
assert.equal(claude.mode, 'subscription');
|
|
171
|
+
assert.equal(claude.conflict, true);
|
|
172
|
+
assert.equal(claude.status, 'tampered', 'still flagged so --fix clears the leftover');
|
|
173
|
+
}));
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test('detectTools: healthy claude gateway + stale subscription hooks → reports gateway', () => {
|
|
177
|
+
withHome((tmp, th) => withEnv({ UNBOUND_API_KEY: 'k', ANTHROPIC_BASE_URL: 'https://api.getunbound.ai' }, () => {
|
|
178
|
+
loggedIn(tmp);
|
|
179
|
+
const helper = path.join(tmp, '.claude', 'anthropic_key.sh');
|
|
180
|
+
writeFile(path.join(tmp, '.claude', 'settings.json'), JSON.stringify({
|
|
181
|
+
hooks: { PreToolUse: [{ command: path.join(tmp, '.claude', 'hooks', 'unbound.py') }] }, // script is gone
|
|
182
|
+
apiKeyHelper: helper,
|
|
183
|
+
}));
|
|
184
|
+
writeFile(helper, 'echo $UNBOUND_API_KEY');
|
|
185
|
+
const claude = claudeOf(th);
|
|
186
|
+
assert.equal(claude.key, 'claude-code-gateway');
|
|
187
|
+
assert.equal(claude.conflict, true);
|
|
188
|
+
assert.equal(claude.status, 'tampered');
|
|
189
|
+
}));
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
test('detectTools: gateway with real env exports beside intact hooks → still reports the tampered gateway', () => {
|
|
193
|
+
withHome((tmp, th) => withEnv({ UNBOUND_API_KEY: 'k', ANTHROPIC_BASE_URL: 'https://api.getunbound.ai' }, () => {
|
|
194
|
+
loggedIn(tmp);
|
|
195
|
+
const hook = path.join(tmp, '.claude', 'hooks', 'unbound.py');
|
|
196
|
+
writeFile(path.join(tmp, '.claude', 'settings.json'), JSON.stringify({
|
|
197
|
+
hooks: { PreToolUse: [{ command: hook }] },
|
|
198
|
+
apiKeyHelper: path.join(tmp, '.claude', 'anthropic_key.sh'), // script is gone
|
|
199
|
+
}));
|
|
200
|
+
writeFile(hook, '#');
|
|
201
|
+
const claude = claudeOf(th);
|
|
202
|
+
assert.equal(claude.key, 'claude-code-gateway', 'real gateway wiring is not overridden');
|
|
203
|
+
assert.equal(claude.conflict, true);
|
|
204
|
+
assert.equal(claude.status, 'tampered');
|
|
205
|
+
}));
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test('detectTools: healthy claude subscription + the user\'s own key helper script → reports subscription', () => {
|
|
209
|
+
withHome((tmp, th) => withEnv({}, () => {
|
|
210
|
+
loggedIn(tmp);
|
|
211
|
+
const hook = path.join(tmp, '.claude', 'hooks', 'unbound.py');
|
|
212
|
+
const helper = path.join(tmp, '.claude', 'anthropic_key.sh');
|
|
213
|
+
writeFile(path.join(tmp, '.claude', 'settings.json'), JSON.stringify({
|
|
214
|
+
hooks: { PreToolUse: [{ command: hook }] },
|
|
215
|
+
apiKeyHelper: helper,
|
|
216
|
+
}));
|
|
217
|
+
writeFile(hook, '#');
|
|
218
|
+
writeFile(helper, '#!/bin/sh\nsecurity find-generic-password -s my-llm -w\n');
|
|
219
|
+
const claude = claudeOf(th);
|
|
220
|
+
assert.equal(claude.key, 'claude-code-subscription', 'hooks setup keeps a helper it did not write');
|
|
221
|
+
assert.equal(claude.conflict, true);
|
|
222
|
+
assert.equal(claude.status, 'healthy', '--fix cannot remove a helper setup keeps, so doctor must not stay red');
|
|
223
|
+
}));
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
test('detectTools: healthy claude subscription + gateway config + customer ANTHROPIC_BASE_URL → still reports gateway', () => {
|
|
227
|
+
withHome((tmp, th) => withEnv({ ANTHROPIC_BASE_URL: 'https://llm.example.invalid' }, () => {
|
|
228
|
+
loggedIn(tmp);
|
|
229
|
+
const hook = path.join(tmp, '.claude', 'hooks', 'unbound.py');
|
|
230
|
+
writeFile(path.join(tmp, '.claude', 'settings.json'), JSON.stringify({
|
|
231
|
+
hooks: { PreToolUse: [{ command: hook }] },
|
|
232
|
+
apiKeyHelper: path.join(tmp, '.claude', 'anthropic_key.sh'),
|
|
233
|
+
}));
|
|
234
|
+
writeFile(hook, '#');
|
|
235
|
+
const claude = claudeOf(th);
|
|
236
|
+
assert.equal(claude.key, 'claude-code-gateway', 'an endpoint that differs from setup is wiring, not a leftover');
|
|
237
|
+
assert.equal(claude.status, 'tampered');
|
|
238
|
+
}));
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
test('detectTools: healthy codex subscription + leftover openai_base_url line → reports subscription', () => {
|
|
242
|
+
withHome((tmp, th) => withEnv({}, () => {
|
|
243
|
+
loggedIn(tmp);
|
|
244
|
+
const hook = path.join(tmp, '.codex', 'hooks', 'unbound.py');
|
|
245
|
+
writeFile(path.join(tmp, '.codex', 'hooks.json'), JSON.stringify({ hooks: { PreToolUse: [{ command: hook }] } }));
|
|
246
|
+
writeFile(hook, '#');
|
|
247
|
+
writeFile(path.join(tmp, '.codex', 'config.toml'), 'openai_base_url = "https://api.getunbound.ai/v1"\n\n[features]\nhooks = true\n');
|
|
248
|
+
const codex = th.detectTools({ _codexManagedOnly: null }).find((t) => t.family === 'codex');
|
|
249
|
+
assert.equal(codex.key, 'codex-subscription');
|
|
250
|
+
assert.equal(codex.conflict, true);
|
|
251
|
+
assert.equal(codex.status, 'tampered');
|
|
252
|
+
}));
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
test('detectTools: healthy codex gateway + stale hooks entry and hooks flag (script gone) → reports gateway', () => {
|
|
256
|
+
withHome((tmp, th) => withEnv({ OPENAI_API_KEY: 'k' }, () => {
|
|
257
|
+
loggedIn(tmp);
|
|
258
|
+
const hook = path.join(tmp, '.codex', 'hooks', 'unbound.py'); // script is gone
|
|
259
|
+
writeFile(path.join(tmp, '.codex', 'hooks.json'), JSON.stringify({ hooks: { PreToolUse: [{ command: hook }] } }));
|
|
260
|
+
writeFile(path.join(tmp, '.codex', 'config.toml'), 'openai_base_url = "https://api.getunbound.ai/v1"\n\n[features]\nhooks = true\n');
|
|
261
|
+
const codex = th.detectTools({ _codexManagedOnly: null }).find((t) => t.family === 'codex');
|
|
262
|
+
assert.equal(codex.key, 'codex-gateway', 'the hooks flag is a config line, not proof the hooks are installed');
|
|
263
|
+
assert.equal(codex.conflict, true);
|
|
264
|
+
assert.equal(codex.status, 'tampered');
|
|
265
|
+
}));
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
const codexSub = (tmp, { script = true } = {}) => {
|
|
269
|
+
const hook = path.join(tmp, '.codex', 'hooks', 'unbound.py');
|
|
270
|
+
writeFile(path.join(tmp, '.codex', 'hooks.json'), JSON.stringify({ hooks: { PreToolUse: [{ command: hook }] } }));
|
|
271
|
+
if (script) writeFile(hook, '#');
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
test('detectTools: healthy codex subscription + the user\'s own openai_base_url → healthy, nothing for --fix to strip', () => {
|
|
275
|
+
withHome((tmp, th) => withEnv({}, () => {
|
|
276
|
+
loggedIn(tmp);
|
|
277
|
+
codexSub(tmp);
|
|
278
|
+
writeFile(path.join(tmp, '.codex', 'config.toml'), 'openai_base_url = "https://openrouter.ai/api/v1"\n\n[features]\nhooks = true\n');
|
|
279
|
+
const codex = th.detectTools({ _codexManagedOnly: null }).find((t) => t.family === 'codex');
|
|
280
|
+
assert.equal(codex.key, 'codex-subscription');
|
|
281
|
+
assert.equal(codex.status, 'healthy');
|
|
282
|
+
}));
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
test('detectTools: healthy codex subscription + a commented-out openai_base_url → healthy', () => {
|
|
286
|
+
withHome((tmp, th) => withEnv({}, () => {
|
|
287
|
+
loggedIn(tmp);
|
|
288
|
+
codexSub(tmp);
|
|
289
|
+
writeFile(path.join(tmp, '.codex', 'config.toml'), '# openai_base_url = "https://api.getunbound.ai/v1"\n\n[features]\nhooks = true\n');
|
|
290
|
+
const codex = th.detectTools({ _codexManagedOnly: null }).find((t) => t.family === 'codex');
|
|
291
|
+
assert.equal(codex.key, 'codex-subscription');
|
|
292
|
+
assert.equal(codex.status, 'healthy');
|
|
293
|
+
}));
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
test('detectTools: codex subscription with its script deleted + the user\'s own endpoint and key → still reports subscription', () => {
|
|
297
|
+
withHome((tmp, th) => withEnv({ OPENAI_API_KEY: 'sk-own' }, () => {
|
|
298
|
+
loggedIn(tmp);
|
|
299
|
+
codexSub(tmp, { script: false });
|
|
300
|
+
writeFile(path.join(tmp, '.codex', 'config.toml'), 'openai_base_url = "https://my-azure.example/openai/v1"\n\n[features]\nhooks = true\n');
|
|
301
|
+
const codex = th.detectTools({ _codexManagedOnly: null }).find((t) => t.family === 'codex');
|
|
302
|
+
assert.equal(codex.key, 'codex-subscription', '--fix must reinstall the hooks, not switch to gateway over the user\'s endpoint');
|
|
303
|
+
assert.equal(codex.status, 'tampered');
|
|
304
|
+
}));
|
|
305
|
+
});
|
|
306
|
+
|
|
146
307
|
// --- MDM (org-managed) scenarios, exercised via the _mdmDirs test override ---
|
|
147
308
|
test('MDM: managed config references unbound + hook present → managed by MDM', () => {
|
|
148
309
|
withHome((tmp, th) => {
|