nc-agent 0.1.1 → 0.1.4

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 CHANGED
@@ -2,44 +2,15 @@
2
2
 
3
3
  Node Command device pairing and agent installer.
4
4
 
5
- ## Install
5
+ ## Usage
6
6
 
7
7
  ```bash
8
+ # Interactive RFC 8628 pairing (8-character code displayed in terminal)
8
9
  npx nc-agent
9
- ```
10
10
 
11
- This starts the browser device authorization flow (RFC 8628). It prints a
12
- short confirmation code and a URL — open the URL in your browser, approve the
13
- prompt, and the agent is enrolled, downloaded from the control plane,
14
- installed, and verified automatically.
11
+ # Direct pairing with host ID and enrollment token
12
+ npx nc-agent <host_id> <enrollment_token>
15
13
 
16
- ```bash
17
- npx nc-agent setup # explicit setup (auto system/user mode)
18
- npx nc-agent setup --system # force system-level service install
19
- npx nc-agent setup --user # force non-elevated user install
20
- npx nc-agent remove # uninstall the agent
21
- npx nc-agent --diagnostics # preview a redacted support bundle
14
+ # Uninstall the agent from the canonical system directory
15
+ npx nc-agent uninstall
22
16
  ```
23
-
24
- The agent runtime is **not** bundled in this package. It is downloaded from
25
- the control plane at install time, so a fresh `npx nc-agent` always installs
26
- the latest release we serve. Updates after install flow through the Node
27
- Command OTA channel, not npm.
28
-
29
- ## Environment
30
-
31
- - `NC_BASE_URL` — auth host for the browser device flow (default `https://auth.nodecommand.app`)
32
- - `NC_API_URL` — agent API host for device endpoints and package downloads (default `https://agent.nodecommand.app`)
33
- - `NC_SERVER_URL` — agent server address written to the client env
34
-
35
- ## Manual install (fallback)
36
-
37
- ```bash
38
- git clone https://github.com/huseyincig/nc-agent.git
39
- cd nc-agent
40
- npm start
41
- ```
42
-
43
- ## License
44
-
45
- MIT — see [LICENSE](LICENSE).
package/bin/nc.mjs CHANGED
@@ -10,10 +10,12 @@ import child_process from 'node:child_process';
10
10
  import readline from 'node:readline';
11
11
  import { fileURLToPath } from 'node:url';
12
12
  import {
13
+ canElevate,
13
14
  decideInstallMode,
14
15
  findRemovalTargets,
15
16
  getNcRootForMode,
16
17
  installerEnvForMode,
18
+ isElevated,
17
19
  modeWarningFor,
18
20
  runUninstallerScript,
19
21
  uninstallFailureSuggestion,
@@ -218,7 +220,7 @@ export function buildDeviceDownloadHeaders({ hostId, hostToken, privateKey }, ab
218
220
  * @param {Record<string, string>} [extraHeaders]
219
221
  * @returns {Promise<import('node:http').IncomingMessage>}
220
222
  */
221
- function httpGet(targetUrl, maxRedirects = 5, extraHeaders = {}) {
223
+ export function httpGet(targetUrl, maxRedirects = 5, extraHeaders = {}, options = {}) {
222
224
  if (typeof maxRedirects === 'object' && maxRedirects !== null) {
223
225
  extraHeaders = /** @type {Record<string, string>} */ (maxRedirects);
224
226
  maxRedirects = 5;
@@ -229,10 +231,13 @@ function httpGet(targetUrl, maxRedirects = 5, extraHeaders = {}) {
229
231
  }
230
232
  const u = new URL(targetUrl);
231
233
  const client = u.protocol === 'http:' ? http : https;
234
+ const timeoutMs = options.timeoutMs ?? getCliRequestTimeoutMs();
235
+ const signal = options.signal ?? (timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined);
232
236
 
233
237
  const req = client.get(
234
238
  u,
235
239
  {
240
+ signal,
236
241
  headers: {
237
242
  'User-Agent': 'nc-cli/0.1.0',
238
243
  Accept: '*/*',
@@ -249,7 +254,7 @@ function httpGet(targetUrl, maxRedirects = 5, extraHeaders = {}) {
249
254
  const redirectUrl = new URL(res.headers.location, targetUrl).toString();
250
255
  res.resume();
251
256
  const forwarded = isSameOrigin(targetUrl, redirectUrl) ? extraHeaders : {};
252
- return resolve(httpGet(redirectUrl, maxRedirects - 1, forwarded));
257
+ return resolve(httpGet(redirectUrl, maxRedirects - 1, forwarded, { signal, timeoutMs }));
253
258
  }
254
259
 
255
260
  if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
@@ -269,27 +274,17 @@ function httpGet(targetUrl, maxRedirects = 5, extraHeaders = {}) {
269
274
  * Fetches and parses a JSON endpoint. The update manifest (`/api/updates`)
270
275
  * is admin-only and never takes device headers, so this stays anonymous;
271
276
  * device identity is only attached to per-client package downloads.
277
+ * Delegates to requestJson to enforce request timeout and response byte limits.
272
278
  * @param {string} targetUrl
273
279
  * @param {Record<string, string>} [extraHeaders]
274
280
  * @returns {Promise<any>}
275
281
  */
276
- async function fetchJson(targetUrl, extraHeaders = {}) {
277
- const res = await httpGet(targetUrl, 5, extraHeaders);
278
- return new Promise((resolve, reject) => {
279
- let raw = '';
280
- res.setEncoding('utf8');
281
- res.on('data', (chunk) => {
282
- raw += chunk;
283
- });
284
- res.on('end', () => {
285
- try {
286
- resolve(JSON.parse(raw));
287
- } catch (err) {
288
- reject(new Error(`Failed to parse JSON from ${targetUrl}: ${err.message}`));
289
- }
290
- });
291
- res.on('error', reject);
292
- });
282
+ export async function fetchJson(targetUrl, extraHeaders = {}) {
283
+ const res = await requestJson('GET', targetUrl, null, extraHeaders);
284
+ if (res.status < 200 || res.status >= 300) {
285
+ throw new Error(`Request to ${targetUrl} failed with status ${res.status}`);
286
+ }
287
+ return res.data;
293
288
  }
294
289
 
295
290
  /**
@@ -297,10 +292,11 @@ async function fetchJson(targetUrl, extraHeaders = {}) {
297
292
  * @param {string} targetUrl
298
293
  * @param {string} destinationPath
299
294
  * @param {Record<string, string>} [extraHeaders] Device headers for `/api/clients/...` package URLs; empty for public `/releases/...` URLs.
295
+ * @param {{ timeoutMs?: number, signal?: AbortSignal }} [options]
300
296
  * @returns {Promise<string>}
301
297
  */
302
- async function downloadToFile(targetUrl, destinationPath, extraHeaders = {}) {
303
- const res = await httpGet(targetUrl, 5, extraHeaders);
298
+ export async function downloadToFile(targetUrl, destinationPath, extraHeaders = {}, options = {}) {
299
+ const res = await httpGet(targetUrl, 5, extraHeaders, options);
304
300
  return new Promise((resolve, reject) => {
305
301
  const fileStream = fs.createWriteStream(destinationPath);
306
302
  let resolved = false;
@@ -329,21 +325,24 @@ async function downloadToFile(targetUrl, destinationPath, extraHeaders = {}) {
329
325
  }
330
326
 
331
327
  /**
332
- * Determines the installation root (NC_ROOT) dynamically based on OS:
333
- * - Windows: %LOCALAPPDATA%\nc
328
+ * Determines the canonical installation root (NC_ROOT) dynamically based on
329
+ * OS:
330
+ * - Windows: %ProgramData%\NC (the machine-wide root; user-space
331
+ * %LOCALAPPDATA%\nc is never a default — see getNcRootForMode('user'))
334
332
  * - macOS: ~/Library/Application Support/nc
335
333
  * - Linux (root): /opt/nc
336
334
  * - Linux (non-root): ~/.local/share/nc
335
+ * An explicit NC_ROOT always wins. Probes are injectable for deterministic
336
+ * tests.
337
+ * @param {{ platform?: string, env?: NodeJS.ProcessEnv }} [options]
337
338
  * @returns {string}
338
339
  */
339
- export function getNcRoot() {
340
- if (process.env.NC_ROOT) {
341
- return process.env.NC_ROOT;
340
+ export function getNcRoot({ platform = os.platform(), env = process.env } = {}) {
341
+ if (env.NC_ROOT) {
342
+ return env.NC_ROOT;
342
343
  }
343
- const platform = os.platform();
344
344
  if (platform === 'win32') {
345
- const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
346
- return path.join(localAppData, 'nc');
345
+ return path.join(env.ProgramData || 'C:\\ProgramData', 'NC');
347
346
  }
348
347
  if (platform === 'darwin') {
349
348
  return path.join(os.homedir(), 'Library', 'Application Support', 'nc');
@@ -960,8 +959,13 @@ export async function verifyHostRegistration({ baseUrl: baseUrlOpt = undefined,
960
959
  * admin-only GET /api/updates manifest is NEVER fetched: the release already
961
960
  * carries concrete per-client bootstrap/package URLs plus integrity pins,
962
961
  * and the CLI is not an admin so the manifest would answer 401 anyway.
963
- * Relative URLs resolve against `serverUrl`/`NC_SERVER_URL`. Without a
964
- * release the legacy manifest fetch is attempted, and an admin-auth refusal
962
+ * Relative URLs resolve against `serverUrl`/`NC_SERVER_URL`. When no release
963
+ * is present but host identity (`hostId` + `hostToken` + `privateKey`) is
964
+ * available — the resume and already-redeemed paths — the release is
965
+ * resolved from the client-authenticated per-host manifest
966
+ * (GET /api/clients/<id>/update/manifest with NC-Device + Device Proof v1,
967
+ * the same identity the agent updater sends); /api/updates stays reserved
968
+ * for callers with no device identity at all, and an admin-auth refusal
965
969
  * surfaces an explanatory error pointing at enrollment-based setup.
966
970
  * The /api/updates endpoint stays admin-only (Caddy and control-plane are
967
971
  * intentionally untouched): opening it on the agent edge would only trade a
@@ -974,11 +978,12 @@ export async function verifyHostRegistration({ baseUrl: baseUrlOpt = undefined,
974
978
  * client token, exactly like redeemEnrollment.
975
979
  * @param {{ ncRoot?: string, updatesUrl?: string, serverUrl?: string, release?: Record<string, unknown>|null, installMode?: 'system'|'user', runInstaller?: (scriptPath: string, ncRoot: string) => void, hostId?: string, hostToken?: string, privateKey?: import('node:crypto').KeyObject }} options
976
980
  */
977
- export async function downloadAndInstallAgent({ ncRoot = getNcRoot(), updatesUrl = undefined, serverUrl = undefined, release = undefined, installMode = undefined, runInstaller = undefined, hostId = undefined, hostToken = undefined, privateKey = undefined } = {}) {
981
+ export async function downloadAndInstallAgent({ ncRoot = undefined, updatesUrl = undefined, serverUrl = undefined, release = undefined, installMode = undefined, runInstaller = undefined, hostId = undefined, hostToken = undefined, privateKey = undefined } = {}) {
982
+ ncRoot = ncRoot || (installMode ? getNcRootForMode(installMode) : getNcRoot());
978
983
  const modeEnv = installMode ? installerEnvForMode(installMode) : {};
979
984
  const invokeInstaller =
980
985
  runInstaller || ((scriptPath, root) => runInstallerScript(scriptPath, root, modeEnv));
981
- const root = ncRoot || getNcRoot();
986
+ const root = ncRoot;
982
987
  console.log(`📍 Installation root: ${root}`);
983
988
 
984
989
  // Package/release resolution stays on the agent edge: an explicit
@@ -990,11 +995,39 @@ export async function downloadAndInstallAgent({ ncRoot = getNcRoot(), updatesUrl
990
995
  /** @type {Record<string, any>} */
991
996
  let activeRelease;
992
997
  if (release && typeof release === 'object') {
993
- // Redemption release wins: skip the admin-only manifest entirely, so its
994
- // URL is never logged as a misleading signal.
998
+ // Redemption release wins: skip the manifest entirely, so its URL is
999
+ // never logged as a misleading signal.
995
1000
  activeRelease = /** @type {Record<string, any>} */ (release);
996
1001
  const releaseVersion = activeRelease.version ? ` ${activeRelease.version}` : '';
997
1002
  console.log(`📦 Using release${releaseVersion} from enrollment redemption; skipping update manifest.`);
1003
+ } else if (
1004
+ typeof hostId === 'string' &&
1005
+ hostId &&
1006
+ typeof hostToken === 'string' &&
1007
+ hostToken &&
1008
+ privateKey
1009
+ ) {
1010
+ // Resume paths (verified stored credentials, already-redeemed enrollment)
1011
+ // carry no redemption release, but they DO hold device identity. Resolve
1012
+ // the release from the client-authenticated per-host manifest the agent
1013
+ // updater itself uses, never from the admin-only /api/updates manifest
1014
+ // (which can only answer 401/404 to a non-admin CLI).
1015
+ const clientManifestUrl = `${defaultBaseUrl}/api/clients/${encodeURIComponent(hostId)}/update/manifest`;
1016
+ console.log(`📡 Fetching client update manifest from ${clientManifestUrl}...`);
1017
+ let manifestData;
1018
+ try {
1019
+ manifestData = await fetchJson(
1020
+ clientManifestUrl,
1021
+ buildDeviceDownloadHeaders({ hostId, hostToken, privateKey }, clientManifestUrl)
1022
+ );
1023
+ } catch (err) {
1024
+ const detail = err instanceof Error ? err.message : String(err);
1025
+ throw new PairingError(
1026
+ 'INSTALL_MANIFEST_ERROR',
1027
+ `Could not fetch the client update manifest: ${detail}`
1028
+ );
1029
+ }
1030
+ activeRelease = manifestData?.release || manifestData || {};
998
1031
  } else {
999
1032
  const manifestOrigin = String(process.env.NC_API_URL || apiBase).replace(/\/$/, '');
1000
1033
  const manifestUrl = updatesUrl || process.env.NC_UPDATES_URL || `${manifestOrigin}/api/updates`;
@@ -1220,7 +1253,12 @@ export async function pairDeviceAndInstall({
1220
1253
  writePairState(statePath, { host_id: localEnv.NC_CLIENT_ID, phase: 'verified' });
1221
1254
  return { hostId: localEnv.NC_CLIENT_ID, serverUrl: localEnv.NC_SERVER_URL, resumed: true };
1222
1255
  } catch (err) {
1223
- if (err instanceof PairingError && (err.code === 'VERIFY_TIMEOUT' || err.code === 'VERIFY_FAILED')) {
1256
+ // Only a definitive 404 (VERIFY_FAILED) falls through to a fresh
1257
+ // enrollment. A timeout (VERIFY_TIMEOUT) rethrows with the timeout
1258
+ // guidance: wiping stored credentials on a transient stall would
1259
+ // orphan a healthy host identity. The caller reports the stored-
1260
+ // credentials connectivity hint via suggestedActionFor.
1261
+ if (err instanceof PairingError && err.code === 'VERIFY_FAILED') {
1224
1262
  // Stored credentials no longer authenticate (rotated, revoked, or
1225
1263
  // server reset): fall through to a fresh enrollment, which
1226
1264
  // overwrites the stale files below.
@@ -1341,6 +1379,7 @@ function printCliHelp() {
1341
1379
  'Usage:',
1342
1380
  ' nodecommand pair this machine via the browser device flow',
1343
1381
  ' nodecommand setup [host_id token] install the agent (auto system/user mode; no args = browser device flow)',
1382
+ ' nodecommand uninstall [--yes] remove the agent from the canonical root (alias: remove)',
1344
1383
  ' nodecommand remove [--yes] uninstall the agent (asks for confirmation unless --yes)',
1345
1384
  ' nodecommand --diagnostics preview a redacted diagnostics bundle (dry-run, writes nothing)',
1346
1385
  ' nodecommand --diagnostics --apply write the diagnostics bundle (.tar.gz) for a support ticket',
@@ -1372,6 +1411,10 @@ async function main() {
1372
1411
  await runSetup(subArgs);
1373
1412
  return;
1374
1413
  }
1414
+ if (subcommand === 'uninstall') {
1415
+ await runUninstall(subArgs);
1416
+ return;
1417
+ }
1375
1418
  if (subcommand === 'remove') {
1376
1419
  await runRemove(subArgs);
1377
1420
  return;
@@ -1491,11 +1534,53 @@ function printSetupSuccess({ hostId, serverUrl, installMode = undefined, resumed
1491
1534
  console.log('status: agent credentials verified online');
1492
1535
  }
1493
1536
 
1537
+ /**
1538
+ * Guidance printed when Windows UAC elevation for a system-wide install is
1539
+ * unavailable (headless shell) or was declined by the operator.
1540
+ */
1541
+ const WINDOWS_ELEVATION_INSTALL_DECLINED =
1542
+ 'Elevation unavailable or declined. Please run as Administrator in an elevated shell for a system-wide install at C:\\ProgramData\\NC.';
1543
+
1544
+ /**
1545
+ * Guidance printed when Windows UAC elevation for uninstallation is
1546
+ * unavailable (headless shell) or was declined by the operator.
1547
+ */
1548
+ const WINDOWS_ELEVATION_UNINSTALL_DECLINED =
1549
+ 'Elevation unavailable or declined. Please run as Administrator in an elevated shell to uninstall the agent from C:\\ProgramData\\NC.';
1550
+
1551
+ /**
1552
+ * Re-runs the current CLI invocation elevated through the Windows UAC prompt
1553
+ * (`Start-Process -Verb RunAs -Wait`; stdio stays inherited so the elevated
1554
+ * console is visible) and returns the spawnSync result. Never throws: a
1555
+ * missing powershell or a declined prompt resolves to null/non-zero.
1556
+ */
1557
+ function requestWindowsElevation() {
1558
+ const args = [...process.argv.slice(1)];
1559
+ try {
1560
+ return child_process.spawnSync(
1561
+ 'powershell',
1562
+ [
1563
+ '-NoProfile',
1564
+ '-Command',
1565
+ `Start-Process -FilePath "${process.execPath}" -ArgumentList ${args
1566
+ .map((a) => `"${String(a).replace(/"/g, '`"')}"`)
1567
+ .join(',')} -Verb RunAs -Wait`
1568
+ ],
1569
+ { stdio: 'inherit' }
1570
+ );
1571
+ } catch {
1572
+ return null;
1573
+ }
1574
+ }
1575
+
1494
1576
  /**
1495
1577
  * `nodecommand setup [host_id enrollment_token]`.
1496
1578
  *
1497
- * Mode is automatic (never prompted): elevated processes install system-wide,
1498
- * everything else installs per-user with a single-line capability notice.
1579
+ * Mode is automatic (never prompted): elevated processes install machine-wide.
1580
+ * POSIX: a non-root admin requests sudo; a refusal falls back to a per-user
1581
+ * install with a single-line capability notice. Windows: a standard shell
1582
+ * requests UAC elevation instead and hard-stops (exit 1) when elevation is
1583
+ * unavailable or declined — never a silent %LOCALAPPDATA% degradation.
1499
1584
  * Without arguments a fresh enrollment is requested via the browser device
1500
1585
  * flow; with `host_id` + `token` (dashboard flow) the supplied enrollment is
1501
1586
  * redeemed directly. Enrollment always goes through POST /api/enroll with the
@@ -1527,7 +1612,32 @@ export async function runSetup(args = []) {
1527
1612
  console.error('suggested_action: Re-run as `nodecommand setup` or `nodecommand setup <host_id> <token>`.');
1528
1613
  process.exit(1);
1529
1614
  }
1530
- const installMode = decideInstallMode();
1615
+ let installMode = decideInstallMode();
1616
+ // A non-root admin must not silently fall back to a per-user install: the
1617
+ // install root, service scope and privileged helper all differ. POSIX
1618
+ // requests sudo and re-runs elevated; Windows requests UAC (Start-Process
1619
+ // -Verb RunAs) so the install lands machine-wide at the canonical system
1620
+ // root. A refused or unavailable Windows elevation is a hard stop: the CLI
1621
+ // never silently degrades a system install into %LOCALAPPDATA%.
1622
+ if (installMode === 'user' && canElevate() && !process.env.NC_ELEVATED) {
1623
+ if (os.platform() === 'win32') {
1624
+ if (process.stdin.isTTY) {
1625
+ console.log('Admin rights required for a system-wide install. Requesting UAC elevation…');
1626
+ const elevated = requestWindowsElevation();
1627
+ if (elevated && elevated.status === 0) process.exit(0);
1628
+ }
1629
+ console.error(WINDOWS_ELEVATION_INSTALL_DECLINED);
1630
+ process.exit(1);
1631
+ }
1632
+ console.log('Admin rights required for a system-wide install. Requesting sudo…');
1633
+ const elevated = child_process.spawnSync(
1634
+ 'sudo',
1635
+ ['-E', process.execPath, ...process.argv.slice(1)],
1636
+ { stdio: 'inherit', env: { ...process.env, NC_ELEVATED: '1' } }
1637
+ );
1638
+ if (elevated && elevated.status === 0) process.exit(0);
1639
+ console.warn('Elevation unavailable or declined; continuing with a per-user install.');
1640
+ }
1531
1641
  // Mode-aware root: on win32 a system install lives in %ProgramData%\NC,
1532
1642
  // not the %LOCALAPPDATA% tree getNcRoot() returns, so credentials must be
1533
1643
  // written where the system installer will actually read them.
@@ -1588,30 +1698,47 @@ export function confirmPrompt(question, openInterface = null) {
1588
1698
  }
1589
1699
 
1590
1700
  /**
1591
- * `nodecommand remove [--yes]`. Idempotent: no install found means success
1592
- * (exit 0). Otherwise the uninstaller living inside each installed tree is
1593
- * executed (never a downloaded copy) and its exit status is reported.
1701
+ * Shared engine for `remove`/`uninstall`: idempotent (no install found means
1702
+ * success, exit 0); otherwise the uninstaller living inside each installed
1703
+ * tree is executed (never a downloaded copy) and its exit status is reported.
1704
+ * Target discovery is centered on the canonical root (candidateInstallRoots
1705
+ * lists it first) and treats an unreadable system tree as installed, so a
1706
+ * non-root shell routes it to the elevated uninstaller instead of reporting
1707
+ * "nothing to remove".
1594
1708
  * @param {string[]} args
1709
+ * @param {{ command: string, emptyMessage: string, elevateOnWindows?: boolean, completionMessage: string }} options
1595
1710
  */
1596
- export async function runRemove(args = []) {
1711
+ async function runRemoval(args, { command, emptyMessage, elevateOnWindows = false, completionMessage }) {
1597
1712
  if (args.includes('--help') || args.includes('-h') || args.includes('help')) {
1598
1713
  printCliHelp();
1599
1714
  return;
1600
1715
  }
1601
- assertKnownFlags(args, ['--yes', '-y', '--help', '-h'], 'remove');
1716
+ assertKnownFlags(args, ['--yes', '-y', '--help', '-h'], command);
1602
1717
  const stray = args.filter((a) => !a.startsWith('-') && a !== 'help');
1603
1718
  if (stray.length > 0) {
1604
- console.error(`error: [UNKNOWN_ARGUMENT] \`remove\` takes no positional arguments (got: ${stray.join(', ')}).`);
1605
- console.error('suggested_action: Run `nodecommand remove --yes` (or plain `nodecommand remove` to be asked).');
1719
+ console.error(`error: [UNKNOWN_ARGUMENT] \`${command}\` takes no positional arguments (got: ${stray.join(', ')}).`);
1720
+ console.error(`suggested_action: Run \`nodecommand ${command} --yes\` (or plain \`nodecommand ${command}\` to be asked).`);
1606
1721
  process.exit(1);
1607
1722
  }
1608
1723
  const yes = args.includes('--yes') || args.includes('-y');
1609
1724
  const { install, unreadable } = findRemovalTargets();
1610
1725
  const targets = [...install, ...unreadable];
1611
1726
  if (targets.length === 0) {
1612
- console.log('No Node Command installation found (nothing to remove).');
1727
+ console.log(emptyMessage);
1613
1728
  return;
1614
1729
  }
1730
+ // Windows: a machine-wide tree at C:\ProgramData\NC cannot be removed from
1731
+ // a standard shell — request UAC (Start-Process -Verb RunAs) and re-run this
1732
+ // same command elevated. Declined or headless elevation is a hard stop.
1733
+ if (elevateOnWindows && os.platform() === 'win32' && !isElevated()) {
1734
+ if (process.stdin.isTTY) {
1735
+ console.log('Admin rights required to remove the system-wide agent. Requesting UAC elevation…');
1736
+ const elevated = requestWindowsElevation();
1737
+ if (elevated && elevated.status === 0) process.exit(0);
1738
+ }
1739
+ console.error(WINDOWS_ELEVATION_UNINSTALL_DECLINED);
1740
+ process.exit(1);
1741
+ }
1615
1742
  console.log(`Found Node Command installation(s): ${targets.join(', ')}`);
1616
1743
  if (unreadable.length > 0) {
1617
1744
  console.log(
@@ -1620,11 +1747,11 @@ export async function runRemove(args = []) {
1620
1747
  }
1621
1748
  if (!yes) {
1622
1749
  if (!process.stdin.isTTY) {
1623
- console.error('error: [CONFIRMATION_REQUIRED] remove needs confirmation in non-interactive shells.');
1624
- console.error('suggested_action: Re-run as `nodecommand remove --yes`.');
1750
+ console.error(`error: [CONFIRMATION_REQUIRED] ${command} needs confirmation in non-interactive shells.`);
1751
+ console.error(`suggested_action: Re-run as \`nodecommand ${command} --yes\`.`);
1625
1752
  process.exit(1);
1626
1753
  }
1627
- const confirmed = await confirmPrompt(`Remove ${targets.length === 1 ? 'this installation' : 'these installations'}? [y/N] `);
1754
+ const confirmed = await confirmPrompt(`${command === 'uninstall' ? 'Uninstall' : 'Remove'} ${targets.length === 1 ? 'this installation' : 'these installations'}? [y/N] `);
1628
1755
  if (!confirmed) {
1629
1756
  console.log('Aborted (nothing removed).');
1630
1757
  return;
@@ -1665,7 +1792,40 @@ export async function runRemove(args = []) {
1665
1792
  }
1666
1793
  }
1667
1794
  if (failed > 0) process.exit(1);
1668
- console.log('Remove complete.');
1795
+ console.log(completionMessage);
1796
+ }
1797
+
1798
+ /**
1799
+ * `nodecommand remove [--yes]` — legacy name for the canonical uninstall.
1800
+ * @param {string[]} args
1801
+ */
1802
+ export async function runRemove(args = []) {
1803
+ return runRemoval(args, {
1804
+ command: 'remove',
1805
+ emptyMessage: 'No Node Command installation found (nothing to remove).',
1806
+ completionMessage: 'Remove complete.'
1807
+ });
1808
+ }
1809
+
1810
+ /**
1811
+ * `nodecommand uninstall [--yes]` (alias: `remove`). Resolves the canonical
1812
+ * install root (`getNcRoot()`), verifies an agent tree actually lives there
1813
+ * (readable markers, or an unreadable system tree that requires elevation),
1814
+ * and invokes the in-tree platform uninstaller:
1815
+ * - Windows: `powershell -NoProfile -ExecutionPolicy Bypass -File <root>\uninstall.ps1`
1816
+ * after requesting UAC (`Start-Process -Verb RunAs`) when not elevated
1817
+ * - POSIX: `sudo <root>/uninstall.sh`, run directly when already root
1818
+ * When no agent is installed the command reports the canonical root and
1819
+ * exits cleanly.
1820
+ * @param {string[]} args
1821
+ */
1822
+ export async function runUninstall(args = []) {
1823
+ return runRemoval(args, {
1824
+ command: 'uninstall',
1825
+ emptyMessage: `No active NC agent installation found at ${getNcRoot()}.`,
1826
+ elevateOnWindows: true,
1827
+ completionMessage: 'Uninstall complete.'
1828
+ });
1669
1829
  }
1670
1830
 
1671
1831
  /**
@@ -1712,7 +1872,8 @@ async function runDeviceFlow({ installMode = undefined, ncRoot = undefined } = {
1712
1872
  user_code,
1713
1873
  verification_uri_complete,
1714
1874
  verification_uri,
1715
- interval = 3
1875
+ interval = 3,
1876
+ expires_in = 600
1716
1877
  } = initRes.data;
1717
1878
 
1718
1879
  const bold = '\x1b[1m';
@@ -1745,9 +1906,20 @@ async function runDeviceFlow({ installMode = undefined, ncRoot = undefined } = {
1745
1906
 
1746
1907
  let isPolling = false;
1747
1908
  let currentIntervalMs = pollIntervalMs;
1909
+ // Poll bounds (RFC 8628 §3.5): the device_code lives ~expires_in seconds
1910
+ // server-side, and consecutive network failures must not spin forever.
1911
+ const lifetimeSec = Number(expires_in) > 0 ? Number(expires_in) : 600;
1912
+ const flowDeadline = Date.now() + lifetimeSec * 1000;
1913
+ let consecutiveNetErrors = 0;
1914
+ const MAX_NET_ERROR_RETRIES = 10;
1748
1915
 
1749
1916
  const poll = async () => {
1750
1917
  if (isPolling) return;
1918
+ if (Date.now() >= flowDeadline) {
1919
+ console.error(`\nerror: [DEVICE_FLOW_CONNECT] Device authorization window expired before approval (no approval within ~${lifetimeSec}s).`);
1920
+ console.error('suggested_action: Re-run the command and approve the prompt in the browser within the time window.');
1921
+ process.exit(1);
1922
+ }
1751
1923
  isPolling = true;
1752
1924
 
1753
1925
  try {
@@ -1757,6 +1929,7 @@ async function runDeviceFlow({ installMode = undefined, ncRoot = undefined } = {
1757
1929
  client_id: clientId,
1758
1930
  code_verifier: deviceCodeVerifier
1759
1931
  });
1932
+ consecutiveNetErrors = 0;
1760
1933
 
1761
1934
  if (tokenRes.status === 200 && tokenRes.data?.access_token) {
1762
1935
  // The OAuth token authorizes enrollment ONLY. It stays in memory:
@@ -1806,7 +1979,15 @@ async function runDeviceFlow({ installMode = undefined, ncRoot = undefined } = {
1806
1979
  process.exit(1);
1807
1980
  }
1808
1981
  } catch (pollErr) {
1809
- // Ephemeral network glitch during poll, continue polling
1982
+ // Ephemeral network glitch during poll: retry a bounded number of
1983
+ // times, then fail loudly instead of polling forever.
1984
+ consecutiveNetErrors += 1;
1985
+ if (consecutiveNetErrors >= MAX_NET_ERROR_RETRIES) {
1986
+ const detail = pollErr instanceof Error ? pollErr.message : String(pollErr);
1987
+ console.error(`\nerror: [DEVICE_FLOW_CONNECT] Could not reach ${tokenEndpoint} after ${consecutiveNetErrors} attempts: ${detail}`);
1988
+ console.error('suggested_action: Check network access to the control plane (or NC_BASE_URL), then re-run.');
1989
+ process.exit(1);
1990
+ }
1810
1991
  } finally {
1811
1992
  isPolling = false;
1812
1993
  setTimeout(poll, currentIntervalMs);
@@ -17,6 +17,7 @@ import os from 'node:os';
17
17
  import path from 'node:path';
18
18
  import zlib from 'node:zlib';
19
19
  import child_process from 'node:child_process';
20
+ import { candidateInstallRoots, decideInstallMode, getNcRootForMode, probeInstallRoot } from './setup.mjs';
20
21
 
21
22
  export const CLI_DIAGNOSTICS_VERSION = '1.0.0';
22
23
  export const CLI_DIAGNOSTICS_MAX_LOG_BYTES = 65536;
@@ -485,21 +486,48 @@ export function renderCliSummary(bundle, { wrote = null, dryRun = true } = {}) {
485
486
  * @param {(file: string, data: Uint8Array) => void} [options.writeFile]
486
487
  * @param {string} [options.cwd]
487
488
  */
489
+ /**
490
+ * Default agent root for diagnostics. Explicit roots win; otherwise the
491
+ * shared installer layout table is probed so machine-wide installs
492
+ * (`/opt/nc`, `%ProgramData%\\NC`) resolve instead of silently falling back
493
+ * to the per-user tree the agent never reads. `mode` overrides the
494
+ * privilege probe (deterministic tests); callers without one get the live
495
+ * `decideInstallMode()` fallback for the nothing-installed case.
496
+ * @param {{ env?: Record<string, string|undefined>, platform?: string, homedir?: string, mode?: 'system'|'user' }} [options]
497
+ */
498
+ export function resolveDefaultCliRoot({ env = process.env, platform = os.platform(), homedir = undefined, mode = undefined } = {}) {
499
+ const e = env || {};
500
+ if (e.NC_ROOT) return e.NC_ROOT;
501
+ const base = { env: e, platform };
502
+ if (homedir !== undefined) base.homedir = homedir;
503
+ let roots = [];
504
+ try {
505
+ roots = candidateInstallRoots(base);
506
+ } catch {
507
+ roots = [];
508
+ }
509
+ for (const r of roots) {
510
+ let status = '';
511
+ try {
512
+ status = probeInstallRoot(r);
513
+ } catch {
514
+ status = '';
515
+ }
516
+ if (status === 'install' || status === 'unreadable') return r;
517
+ }
518
+ try {
519
+ const fallbackMode = mode === 'system' || mode === 'user' ? mode : decideInstallMode({ platform });
520
+ return getNcRootForMode(fallbackMode, base);
521
+ } catch {
522
+ return roots.length ? roots[roots.length - 1] : null;
523
+ }
524
+ }
525
+
488
526
  export function runCliDiagnostics(argv = [], { ncRoot = null, env = process.env, cliVersion = '0.1.0', baseUrl = null, writeFile = null, cwd = null } = {}) {
489
527
  const parsed = parseCliDiagnosticsArgs(argv);
490
528
  if (!parsed.enabled) return { handled: false, ok: false, summary: '', outputPath: null };
491
529
  try {
492
- let root = ncRoot;
493
- if (!root) {
494
- const e = env || {};
495
- if (e.NC_ROOT) root = e.NC_ROOT;
496
- else {
497
- const plat = os.platform();
498
- if (plat === 'win32') root = path.join(e.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'nc');
499
- else if (plat === 'darwin') root = path.join(os.homedir(), 'Library', 'Application Support', 'nc');
500
- else root = path.join(os.homedir(), '.local', 'share', 'nc');
501
- }
502
- }
530
+ const root = ncRoot || resolveDefaultCliRoot({ env });
503
531
  const bundle = collectCliDiagnostics({ ncRoot: root, env, cliVersion, baseUrl });
504
532
  if (!parsed.apply) {
505
533
  return { handled: true, ok: true, dryRun: true, outputPath: null, bundle, summary: renderCliSummary(bundle, { dryRun: true }) };
package/lib/setup.mjs CHANGED
@@ -72,6 +72,30 @@ export function decideInstallMode(options = {}) {
72
72
  return isElevated(options) ? 'system' : 'user';
73
73
  }
74
74
 
75
+ /**
76
+ * True when the current user CAN elevate to a machine-wide install even when
77
+ * the process is not root yet: an already-elevated process, a Windows
78
+ * standard shell (UAC `Start-Process -Verb RunAs` is always available), or
79
+ * POSIX admin groups (sudo/admin/wheel). Used so a non-root admin is asked
80
+ * for elevation instead of silently degrading to a per-user install
81
+ * (different root, service scope and no privileged helper).
82
+ * @param {{ platform?: string, getuid?: (() => number)|null, isAdmin?: boolean|null, runAdminCheck?: (() => boolean)|null }} [options]
83
+ */
84
+ export function canElevate(options = {}) {
85
+ if (isElevated(options)) return true;
86
+ const platform = options.platform || os.platform();
87
+ // Windows: a non-elevated process can still relaunch itself through the
88
+ // UAC prompt, so elevation is available even when not administrator.
89
+ if (platform === 'win32') return true;
90
+ try {
91
+ const r = child_process.spawnSync('id', ['-nG'], { encoding: 'utf8' });
92
+ const groups = r && typeof r.stdout === 'string' ? r.stdout : '';
93
+ return /\b(sudo|admin|wheel)\b/.test(groups);
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+
75
99
  /**
76
100
  * Warning text for the given mode: a single line for user mode, null for
77
101
  * system mode (callers assert presence/absence on this, not on stdout).
package/package.json CHANGED
@@ -1,23 +1,15 @@
1
1
  {
2
2
  "name": "nc-agent",
3
- "version": "0.1.1",
4
- "license": "Apache-2.0",
3
+ "version": "0.1.4",
4
+ "description": "Node Command device pairing and agent installer. Run npx nc-agent to pair this machine with your Node Command workspace.",
5
5
  "type": "module",
6
+ "license": "Apache-2.0",
6
7
  "bin": {
7
- "nc-agent": "bin/nc.mjs"
8
+ "nc-agent": "./bin/nc.mjs"
8
9
  },
9
10
  "files": [
10
- "bin",
11
- "lib",
12
- "README.md",
13
- "LICENSE"
14
- ],
15
- "engines": {
16
- "node": ">=24"
17
- },
18
- "scripts": {
19
- "start": "node src/client/launcher.mjs",
20
- "test": "node --test tests/*.mjs"
21
- },
22
- "description": "Node Command device pairing and agent installer. Run npx nc-agent to pair this machine via the browser device flow; the agent is downloaded from the control plane."
11
+ "bin/",
12
+ "lib/",
13
+ "README.md"
14
+ ]
23
15
  }
package/LICENSE DELETED
@@ -1,176 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS