@codingfrees/uap-device-control 0.1.16 → 0.1.18

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
@@ -15,10 +15,10 @@ Runner, WSL, `cloudflared`, a separately installed Device Agent and an inbound d
15
15
  The public npm package does not embed a development, staging or production hostname. Select the intended UAP environment explicitly on first login:
16
16
 
17
17
  ```bash
18
- npx @codingfrees/uap-device-control@latest login --origin https://<uap-device-control-origin>
18
+ npx @codingfrees/uap-device-control@latest login --origin https://<uap-device-control-origin> --pairing-code <temporary-admin-code>
19
19
  ```
20
20
 
21
- The browser OAuth flow stores a device-scoped credential for that exact origin. Later commands reuse the stored origin. To change environments, logout first and then login against the other origin.
21
+ Open the UAP Device Control /admin console, select the authorized owner or workspace identity, and generate a one-time pairing code (valid for five minutes). The CLI exchanges this code via OAuth PKCE and stores a revocable device-scoped credential for the exact origin; it does not require GitHub/Google login. Later commands reuse the saved origin and credential. To change environments, logout first and then pair with the other origin.
22
22
 
23
23
  You can also provide the origin through `UAP_DEVICE_CONTROL_ORIGIN`.
24
24
 
@@ -98,4 +98,4 @@ Validate the exact release without publishing with `pnpm publish:public -- --dry
98
98
 
99
99
  For `npm whoami` HTTP 401 in Linux/WSL, renew authentication locally using `npm login --registry=https://registry.npmjs.org/ --auth-type=web`, then confirm `npm whoami`. Do not paste credentials into issue reports or logs. npm versions are immutable: bump the package version and commit a clean tree before publishing.
100
100
 
101
- The script requires a clean repository, refuses an already-published version, builds and dry-runs the package, then calls npm publish and verifies the registry version plus the `latest` dist-tag. npm account 2FA remains mandatory and is handled by npm during the publish step.
101
+ The script requires clean package inputs, refuses an already-published version, builds and dry-runs the package, then calls npm publish and verifies the registry version plus the `latest` dist-tag. The root `pnpm deploy:npm` entrypoint invokes the publisher directly; a separate package-local node_modules directory is unnecessary when workspace dependencies are installed. npm account 2FA remains mandatory and is handled by npm during the publish step.
@@ -5,8 +5,6 @@ import path6 from "node:path";
5
5
 
6
6
  // src/auth.ts
7
7
  import { createServer } from "node:http";
8
- import { execFile } from "node:child_process";
9
- import { promisify } from "node:util";
10
8
 
11
9
  // ../../packages/web-crypto/src/index.ts
12
10
  var encoder = new TextEncoder();
@@ -62,25 +60,6 @@ import os from "node:os";
62
60
  import path from "node:path";
63
61
  import { link, mkdir, readFile, rm, rename, writeFile } from "node:fs/promises";
64
62
  import { randomUUID } from "node:crypto";
65
- function defaultOwnerBootstrapPath(home = os.homedir(), platform = process.platform) {
66
- if (platform === "win32") return path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "UAP", "DeviceControl", "owner-bootstrap.json");
67
- if (platform === "darwin") return path.join(home, "Library", "Application Support", "UAP", "DeviceControl", "owner-bootstrap.json");
68
- return path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "uap-device-control", "owner-bootstrap.json");
69
- }
70
- async function loadOwnerBootstrapCredential(expectedOrigin, file = defaultOwnerBootstrapPath()) {
71
- try {
72
- const raw = JSON.parse(await readFile(file, "utf8"));
73
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("owner bootstrap credential is invalid");
74
- const value = raw;
75
- if (value.origin !== expectedOrigin || typeof value.secret !== "string" || value.secret.length < 24 || value.secret.length > 512 || /[\u0000-\u001f\u007f]/.test(value.secret)) {
76
- throw new TypeError("owner bootstrap credential is invalid");
77
- }
78
- return { origin: expectedOrigin, secret: value.secret };
79
- } catch (error) {
80
- if (missing(error)) return void 0;
81
- throw error;
82
- }
83
- }
84
63
  function defaultDeviceControlStateDirectory(home = os.homedir(), platform = process.platform) {
85
64
  if (platform === "win32") return path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "UAP", "DeviceControl");
86
65
  if (platform === "darwin") return path.join(home, "Library", "Application Support", "UAP", "DeviceControl");
@@ -200,9 +179,9 @@ function exists(error) {
200
179
  }
201
180
 
202
181
  // src/auth.ts
203
- var execute = promisify(execFile);
204
182
  var scopes = "device-control:device offline_access";
205
183
  async function loginDeviceControl(origin, stateDirectory, options = {}) {
184
+ if (!options.pairingCode || !/^[A-Za-z0-9_-]{32}$/.test(options.pairingCode)) throw new TypeError("A single-use pairing code from the admin console is required");
206
185
  const fetcher = options.fetcher ?? fetch;
207
186
  const issuer = canonicalOrigin(origin);
208
187
  const metadata = await json(fetcher(new URL("/.well-known/oauth-authorization-server", issuer), { redirect: "error", cache: "no-store" }));
@@ -229,8 +208,7 @@ async function loginDeviceControl(origin, stateDirectory, options = {}) {
229
208
  authorize2.searchParams.set("state", pkce.state);
230
209
  authorize2.searchParams.set("code_challenge", pkce.challenge);
231
210
  authorize2.searchParams.set("code_challenge_method", "S256");
232
- const configuredBootstrap = options.ownerBootstrapSecret === void 0 ? await loadOwnerBootstrapCredential(issuer).then((value) => value?.secret) : options.ownerBootstrapSecret ?? void 0;
233
- const result = configuredBootstrap ? await automaticPairing(fetcher, issuer, authorize2, configuredBootstrap, pkce.state) : await browserAuthorization(options.open ?? openBrowser, authorize2.href, callback.result);
211
+ const result = await automaticPairing(fetcher, issuer, authorize2, options.pairingCode, pkce.state);
234
212
  if (result.state !== pkce.state || !result.code) throw new TypeError("OAuth callback is invalid");
235
213
  const token = await json(
236
214
  fetcher(tokenEndpoint, {
@@ -261,7 +239,8 @@ async function accessToken(stateDirectory, fetcher = fetch, forceRefresh = false
261
239
  fetcher(tokenEndpoint, {
262
240
  method: "POST",
263
241
  headers: { "content-type": "application/x-www-form-urlencoded" },
264
- body: new URLSearchParams({ grant_type: "refresh_token", client_id: auth.clientId, refresh_token: auth.refreshToken, resource: auth.origin + "/mcp" })
242
+ body: new URLSearchParams({ grant_type: "refresh_token", client_id: auth.clientId, refresh_token: auth.refreshToken, resource: auth.origin + "/mcp" }),
243
+ signal: AbortSignal.timeout(1e4)
265
244
  })
266
245
  );
267
246
  const next = {
@@ -286,7 +265,7 @@ async function logoutDeviceControl(stateDirectory, fetcher = fetch) {
286
265
  await clearRemoteAuth(stateDirectory);
287
266
  return true;
288
267
  }
289
- async function automaticPairing(fetcher, issuer, authorize2, ownerSecret, expectedState) {
268
+ async function automaticPairing(fetcher, issuer, authorize2, pairingCode, expectedState) {
290
269
  const started = await json(
291
270
  fetcher(new URL("/pairing/start", issuer), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ authorizeUrl: authorize2.href }), redirect: "error", cache: "no-store" })
292
271
  );
@@ -295,7 +274,7 @@ async function automaticPairing(fetcher, issuer, authorize2, ownerSecret, expect
295
274
  await json(
296
275
  fetcher(new URL("/pairing/approve", issuer), {
297
276
  method: "POST",
298
- headers: { "content-type": "application/json", authorization: "Bearer " + ownerSecret },
277
+ headers: { "content-type": "application/json", "x-uap-pairing-code": pairingCode },
299
278
  body: JSON.stringify({ pairingId }),
300
279
  redirect: "error",
301
280
  cache: "no-store"
@@ -309,10 +288,6 @@ async function automaticPairing(fetcher, issuer, authorize2, ownerSecret, expect
309
288
  if (redirect.searchParams.get("state") !== expectedState) throw new TypeError("pairing callback state is invalid");
310
289
  return { code: redirect.searchParams.get("code") ?? void 0, state: redirect.searchParams.get("state") ?? void 0 };
311
290
  }
312
- async function browserAuthorization(open, authorizeUrl, result) {
313
- await open(authorizeUrl);
314
- return result;
315
- }
316
291
  async function callbackServer(timeoutMs) {
317
292
  let settle;
318
293
  let reject;
@@ -344,15 +319,6 @@ async function callbackServer(timeoutMs) {
344
319
  }
345
320
  };
346
321
  }
347
- function browserOpenCommand(platform, url) {
348
- if (platform === "win32") return { command: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url] };
349
- if (platform === "darwin") return { command: "open", args: [url] };
350
- return { command: "xdg-open", args: [url] };
351
- }
352
- async function openBrowser(url) {
353
- const launch = browserOpenCommand(process.platform, url);
354
- await execute(launch.command, launch.args, { windowsHide: true });
355
- }
356
322
  async function requiredDeviceAuth(stateDirectory) {
357
323
  const auth = await loadRemoteAuth(stateDirectory);
358
324
  if (!auth) throw new TypeError("not logged in");
@@ -415,8 +381,8 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
415
381
  if (!Number.isInteger(requestedPort) || requestedPort !== 0 && (requestedPort < 1024 || requestedPort > 65535)) throw new TypeError("browser bridge port is invalid");
416
382
  await mkdir2(stateDirectory, { recursive: true, mode: 448 });
417
383
  const statePath = path2.join(stateDirectory, "browser-bridge.json");
418
- let pairing = await loadPairing(statePath);
419
- let pairingCode = pairing ? void 0 : createPairingCode();
384
+ let pairing2 = await loadPairing(statePath);
385
+ let pairingCode = pairing2 ? void 0 : createPairingCode();
420
386
  let pairingExpiresAt = pairingCode ? Date.now() + 10 * 6e4 : 0;
421
387
  let lastSeen = 0;
422
388
  let permissionsGranted = false;
@@ -433,7 +399,7 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
433
399
  const body = await jsonBody(request2);
434
400
  const extensionId = extensionIdValue(body.extensionId);
435
401
  if (origin !== "chrome-extension://" + extensionId) throw new TypeError("browser extension origin is invalid");
436
- if (pairing) throw new TypeError("browser bridge is already paired");
402
+ if (pairing2) throw new TypeError("browser bridge is already paired");
437
403
  const candidate = pairingCodeValue(body.pairingCode);
438
404
  if (!pairingCode || Date.now() > pairingExpiresAt) {
439
405
  pairingCode = createPairingCode();
@@ -443,14 +409,14 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
443
409
  }
444
410
  if (!secureEqual(candidate, pairingCode)) throw new TypeError("browser pairing code is invalid");
445
411
  const token = randomBytes2(32).toString("base64url");
446
- pairing = { extensionId, tokenHash: digest(token) };
412
+ pairing2 = { extensionId, tokenHash: digest(token) };
447
413
  pairingCode = void 0;
448
414
  pairingExpiresAt = 0;
449
- await persistPairing(statePath, pairing);
415
+ await persistPairing(statePath, pairing2);
450
416
  log?.({ event: "browser.bridge", status: "paired" });
451
417
  return send(response, 200, { token, port: actualPort(server) }, origin);
452
418
  }
453
- const current = authorize(request2, origin, pairing);
419
+ const current = authorize(request2, origin, pairing2);
454
420
  if (url.pathname === "/browser/status" && request2.method === "POST") {
455
421
  const wasOffline = Date.now() - lastSeen >= 45e3;
456
422
  lastSeen = Date.now();
@@ -458,7 +424,7 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
458
424
  return send(response, 200, { paired: true, online: true, permissionsGranted }, current.origin);
459
425
  }
460
426
  if (url.pathname === "/browser/unpair" && request2.method === "POST") {
461
- pairing = void 0;
427
+ pairing2 = void 0;
462
428
  pairingCode = createPairingCode();
463
429
  pairingExpiresAt = Date.now() + 10 * 6e4;
464
430
  lastSeen = 0;
@@ -521,11 +487,11 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
521
487
  return pairingCode;
522
488
  },
523
489
  available() {
524
- return Boolean(pairing && permissionsGranted && Date.now() - lastSeen < 45e3);
490
+ return Boolean(pairing2 && permissionsGranted && Date.now() - lastSeen < 45e3);
525
491
  },
526
492
  execute(capability, parameters) {
527
493
  if (!BROWSER_CONTROL_CAPABILITIES.includes(capability)) throw new TypeError("browser capability is unavailable");
528
- if (!pairing || !permissionsGranted || Date.now() - lastSeen >= 45e3) return Promise.reject(new TypeError("browser control extension is unavailable or missing permissions"));
494
+ if (!pairing2 || !permissionsGranted || Date.now() - lastSeen >= 45e3) return Promise.reject(new TypeError("browser control extension is unavailable or missing permissions"));
529
495
  const requestId = randomUUID2();
530
496
  const command = { requestId, capability, parameters };
531
497
  const completion = new Promise((resolve, reject) => {
@@ -550,10 +516,10 @@ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
550
516
  }
551
517
  };
552
518
  }
553
- function authorize(request2, origin, pairing) {
554
- if (!pairing || origin !== "chrome-extension://" + pairing.extensionId) throw new TypeError("browser bridge is not paired");
519
+ function authorize(request2, origin, pairing2) {
520
+ if (!pairing2 || origin !== "chrome-extension://" + pairing2.extensionId) throw new TypeError("browser bridge is not paired");
555
521
  const auth = request2.headers.authorization;
556
- if (!auth?.startsWith("Bearer ") || digest(auth.slice(7)) !== pairing.tokenHash) throw new TypeError("browser bridge authorization failed");
522
+ if (!auth?.startsWith("Bearer ") || digest(auth.slice(7)) !== pairing2.tokenHash) throw new TypeError("browser bridge authorization failed");
557
523
  return { origin };
558
524
  }
559
525
  function cors(response, origin, status) {
@@ -599,8 +565,8 @@ async function loadPairing(file) {
599
565
  return void 0;
600
566
  }
601
567
  }
602
- async function persistPairing(file, pairing) {
603
- await writeFile2(file, JSON.stringify({ version: 1, ...pairing }) + "\n", { mode: 384 });
568
+ async function persistPairing(file, pairing2) {
569
+ await writeFile2(file, JSON.stringify({ version: 1, ...pairing2 }) + "\n", { mode: 384 });
604
570
  }
605
571
  function rejectAll(pending, message) {
606
572
  for (const value of pending.values()) {
@@ -649,7 +615,7 @@ import path4 from "node:path";
649
615
  // package.json
650
616
  var package_default = {
651
617
  name: "@codingfrees/uap-device-control",
652
- version: "0.1.16",
618
+ version: "0.1.18",
653
619
  description: "Cross-platform outbound UAP Device Control client",
654
620
  type: "module",
655
621
  bin: {
@@ -1385,10 +1351,10 @@ var defaultShell = () => process.platform === "win32" ? "powershell.exe" : "/bin
1385
1351
  var defaultExecutables = () => process.platform === "win32" ? ["powershell.exe", "cmd.exe"] : ["/bin/sh", "/bin/bash"];
1386
1352
 
1387
1353
  // ../device-agent/src/native-desktop.ts
1388
- import { execFile as execFile2 } from "node:child_process";
1389
- import { promisify as promisify2 } from "node:util";
1390
- var execute2 = promisify2(execFile2);
1391
- async function createNativeDesktopAdapter(platform = process.platform, run = execute2) {
1354
+ import { execFile } from "node:child_process";
1355
+ import { promisify } from "node:util";
1356
+ var execute = promisify(execFile);
1357
+ async function createNativeDesktopAdapter(platform = process.platform, run = execute) {
1392
1358
  if (platform === "win32") return windowsAdapter(run);
1393
1359
  if (platform === "linux") {
1394
1360
  const interop = await windowsInteropScreenAdapter(run);
@@ -1643,15 +1609,15 @@ var WINDOWS_CLIPBOARD_READ = "Add-Type -AssemblyName System.Windows.Forms;[Conso
1643
1609
  var WINDOWS_CLIPBOARD_WRITE = "param($text) Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Clipboard]::SetText($text)";
1644
1610
 
1645
1611
  // ../device-agent/src/native-services.ts
1646
- import { execFile as execFile3 } from "node:child_process";
1612
+ import { execFile as execFile2 } from "node:child_process";
1647
1613
  import { realpath as realpath2, stat as stat2 } from "node:fs/promises";
1648
1614
  import { win32 } from "node:path";
1649
- import { promisify as promisify3 } from "node:util";
1650
- var execute3 = promisify3(execFile3);
1615
+ import { promisify as promisify2 } from "node:util";
1616
+ var execute2 = promisify2(execFile2);
1651
1617
  async function createNativeServiceAdapter(options = {}) {
1652
1618
  const platform = options.platform ?? process.platform;
1653
1619
  const environment2 = options.environment ?? process.env;
1654
- const run = options.run ?? execute3;
1620
+ const run = options.run ?? execute2;
1655
1621
  const resolveExecutable = options.resolveExecutable ?? firstExecutable;
1656
1622
  let readCommand;
1657
1623
  let controlCommands;
@@ -1863,7 +1829,7 @@ async function request(fetcher, origin, pathname, token, body, signal, timeoutMs
1863
1829
  signal: controller.signal
1864
1830
  });
1865
1831
  } catch {
1866
- throw new RemoteUnavailableError(void 0, pathname);
1832
+ throw new RemoteUnavailableError(void 0, pathname, controller.signal.aborted ? "timeout" : "transport");
1867
1833
  }
1868
1834
  if (response.status === 401 || response.status === 403) throw new RemoteAuthorizationError(response.status, pathname);
1869
1835
  if (response.status === 409 && pathname === "/device-control/remote/poll") {
@@ -1880,8 +1846,7 @@ async function request(fetcher, origin, pathname, token, body, signal, timeoutMs
1880
1846
  }
1881
1847
  }
1882
1848
  async function remoteStatus(origin, stateDirectory, deviceId, fetcher = fetch) {
1883
- const { token } = await accessToken(stateDirectory, fetcher);
1884
- const value = await request(fetcher, origin, "/device-control/remote/status", token, { deviceId }, void 0, 5e3);
1849
+ const value = await authorizedRequest(fetcher, origin, stateDirectory, "/device-control/remote/status", { deviceId }, void 0, 5e3);
1885
1850
  if (typeof value.online !== "boolean") throw new TypeError("remote status response is invalid");
1886
1851
  const lastSeen = value.lastSeen;
1887
1852
  if (lastSeen !== void 0 && (!Number.isSafeInteger(lastSeen) || Number(lastSeen) < 0)) throw new TypeError("remote status response is invalid");
@@ -1898,13 +1863,15 @@ var RemoteSessionExpiredError = class extends Error {
1898
1863
  pathname;
1899
1864
  };
1900
1865
  var RemoteUnavailableError = class extends Error {
1901
- constructor(httpStatus, pathname) {
1866
+ constructor(httpStatus, pathname, reason) {
1902
1867
  super("remote endpoint is unavailable");
1903
1868
  this.httpStatus = httpStatus;
1904
1869
  this.pathname = pathname;
1870
+ this.reason = reason;
1905
1871
  }
1906
1872
  httpStatus;
1907
1873
  pathname;
1874
+ reason;
1908
1875
  };
1909
1876
  var RemoteAuthorizationError = class extends Error {
1910
1877
  constructor(httpStatus, pathname) {
@@ -1972,9 +1939,9 @@ import os4 from "node:os";
1972
1939
  import path5 from "node:path";
1973
1940
  import { chmod, copyFile, mkdir as mkdir4, rename as rename3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
1974
1941
  import { existsSync } from "node:fs";
1975
- import { execFile as execFile4 } from "node:child_process";
1976
- import { promisify as promisify4 } from "node:util";
1977
- var execute4 = promisify4(execFile4);
1942
+ import { execFile as execFile3 } from "node:child_process";
1943
+ import { promisify as promisify3 } from "node:util";
1944
+ var execute3 = promisify3(execFile3);
1978
1945
  async function installRemoteService(origin, stateDirectory) {
1979
1946
  if (await runnerV2Installed()) throw new TypeError("Runner V2 is installed; use its Device Control provider instead of installing a duplicate Remote service");
1980
1947
  const command = process.execPath;
@@ -2003,7 +1970,7 @@ async function installRemoteService(origin, stateDirectory) {
2003
1970
  await rm3(staged, { force: true }).catch(() => void 0);
2004
1971
  }
2005
1972
  }
2006
- async function runnerV2Installed(platform = process.platform, run = execute4, exists2 = existsSync) {
1973
+ async function runnerV2Installed(platform = process.platform, run = execute3, exists2 = existsSync) {
2007
1974
  if (platform === "linux") {
2008
1975
  if (exists2("/opt/uap-local-node-runner-v2/current")) return true;
2009
1976
  for (const args of [
@@ -2055,8 +2022,8 @@ async function installSystemd(command, args) {
2055
2022
  ].join("\n"),
2056
2023
  { mode: 384 }
2057
2024
  );
2058
- await execute4("systemctl", ["--user", "daemon-reload"]);
2059
- await execute4("systemctl", ["--user", "enable", "--now", "uap-device-control.service"]);
2025
+ await execute3("systemctl", ["--user", "daemon-reload"]);
2026
+ await execute3("systemctl", ["--user", "enable", "--now", "uap-device-control.service"]);
2060
2027
  return { platform: "linux", location };
2061
2028
  }
2062
2029
  async function installLaunchd(command, args) {
@@ -2067,15 +2034,15 @@ async function installLaunchd(command, args) {
2067
2034
  const plist = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>ro.codingfrees.uap-device-control</string><key>ProgramArguments</key><array>' + escaped + "</array><key>RunAtLoad</key><true/><key>KeepAlive</key><true/></dict></plist>";
2068
2035
  await writeFile4(location, plist, { mode: 384 });
2069
2036
  const domain = "gui/" + process.getuid?.();
2070
- await execute4("launchctl", ["bootout", domain, location]).catch(() => void 0);
2071
- await execute4("launchctl", ["bootstrap", domain, location]);
2037
+ await execute3("launchctl", ["bootout", domain, location]).catch(() => void 0);
2038
+ await execute3("launchctl", ["bootstrap", domain, location]);
2072
2039
  return { platform: "darwin", location };
2073
2040
  }
2074
2041
  async function installWindowsTask(command, args) {
2075
2042
  const location = "UAP Device Control";
2076
2043
  const taskCommand = quoteWindows(command) + " " + args.map(quoteWindows).join(" ");
2077
- await execute4("schtasks.exe", ["/Create", "/F", "/SC", "ONLOGON", "/TN", location, "/TR", taskCommand]);
2078
- await execute4("schtasks.exe", ["/Run", "/TN", location]);
2044
+ await execute3("schtasks.exe", ["/Create", "/F", "/SC", "ONLOGON", "/TN", location, "/TR", taskCommand]);
2045
+ await execute3("schtasks.exe", ["/Run", "/TN", location]);
2079
2046
  return { platform: "win32", location };
2080
2047
  }
2081
2048
  function systemdEscape(command, args) {
@@ -2094,6 +2061,7 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
2094
2061
  const command = !args.length || args.includes("--help") || args.includes("-h") || args[0] === "help" ? "help" : args[0];
2095
2062
  if (!["help", "remote", "status", "login", "logout", "browser-reset", "install-service"].includes(command ?? "")) throw new TypeError("unknown command; run uap-device-control help");
2096
2063
  let origin = process.env.UAP_DEVICE_CONTROL_ORIGIN;
2064
+ let pairingCode;
2097
2065
  let stateDirectory = defaultDeviceControlStateDirectory();
2098
2066
  const roots = [];
2099
2067
  const allowedExecutables = [];
@@ -2106,6 +2074,7 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
2106
2074
  const option = args[index];
2107
2075
  const value = args[index + 1];
2108
2076
  if (option === "--origin") origin = required(value, option), index++;
2077
+ else if (option === "--pairing-code") pairingCode = pairing(value), index++;
2109
2078
  else if (option === "--state-dir") stateDirectory = absolute(value, option), index++;
2110
2079
  else if (option === "--root" || option === "--read-only-root") {
2111
2080
  roots.push(root(required(value, option), option === "--read-only-root"));
@@ -2123,6 +2092,7 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
2123
2092
  return {
2124
2093
  command,
2125
2094
  ...normalizedOrigin ? { origin: normalizedOrigin } : {},
2095
+ ...pairingCode ? { pairingCode } : {},
2126
2096
  stateDirectory,
2127
2097
  roots,
2128
2098
  allowedExecutables,
@@ -2143,7 +2113,7 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
2143
2113
  const resolvedOrigin = resolveConfiguredOrigin(config.origin, existingAuth?.origin);
2144
2114
  const output = (event) => process.stdout.write(formatCliEvent(event, config.json) + "\n");
2145
2115
  if (config.command === "login") {
2146
- const auth = await loginDeviceControl(resolvedOrigin, config.stateDirectory);
2116
+ const auth = await loginDeviceControl(resolvedOrigin, config.stateDirectory, { pairingCode: config.pairingCode });
2147
2117
  output({ status: "authenticated", origin: auth.origin });
2148
2118
  return;
2149
2119
  }
@@ -2164,9 +2134,8 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
2164
2134
  if (config.command === "status") {
2165
2135
  const [auth, deviceId] = await Promise.all([existingAuth, loadRemoteDeviceId(config.stateDirectory)]);
2166
2136
  const deviceAuthorized = !!auth?.scope.split(" ").includes("device-control:device");
2167
- let remote;
2168
- if (auth && deviceAuthorized) remote = await remoteStatus(auth.origin, config.stateDirectory, deviceId).catch(() => ({ online: false }));
2169
- output({ deviceId, origin: auth?.origin ?? resolvedOrigin, authenticated: !!auth, deviceAuthorized, remote: remote ?? null, serviceMode: config.service, platform: process.platform });
2137
+ const remote = auth && deviceAuthorized ? await checkRemoteStatus(auth.origin, config.stateDirectory, deviceId) : null;
2138
+ output({ deviceId, origin: auth?.origin ?? resolvedOrigin, authenticated: !!auth, deviceAuthorized, remote, serviceMode: config.service, platform: process.platform });
2170
2139
  return;
2171
2140
  }
2172
2141
  if (config.command === "install-service") {
@@ -2178,7 +2147,7 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
2178
2147
  try {
2179
2148
  if (!existingAuth) {
2180
2149
  if (config.service) throw new TypeError("service mode requires login");
2181
- await loginDeviceControl(resolvedOrigin, config.stateDirectory);
2150
+ await loginDeviceControl(resolvedOrigin, config.stateDirectory, { pairingCode: config.pairingCode });
2182
2151
  }
2183
2152
  const controller = new AbortController();
2184
2153
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => controller.abort());
@@ -2235,6 +2204,21 @@ function formatCliEvent(event, json2 = false) {
2235
2204
  if ("authenticated" in event) return (event.authenticated ? "\u2705" : "\u26A0\uFE0F") + " Device " + String(event.deviceId) + " \xB7 " + String(event.origin) + " \xB7 remote=" + JSON.stringify(event.remote);
2236
2205
  return "\u2139\uFE0F " + JSON.stringify(event);
2237
2206
  }
2207
+ async function checkRemoteStatus(origin, stateDirectory, deviceId, probe = remoteStatus) {
2208
+ for (let attempt = 0; attempt < 2; attempt++) {
2209
+ try {
2210
+ return await probe(origin, stateDirectory, deviceId);
2211
+ } catch (error) {
2212
+ if (error instanceof RemoteAuthorizationError) return { online: null, error: "status_unauthorized", httpStatus: error.httpStatus };
2213
+ if (error instanceof RemoteUnavailableError) {
2214
+ if (attempt === 0) continue;
2215
+ return { online: null, error: error.reason === "timeout" ? "status_timeout" : "status_unavailable", ...error.httpStatus === void 0 ? {} : { httpStatus: error.httpStatus } };
2216
+ }
2217
+ return { online: null, error: "status_failed" };
2218
+ }
2219
+ }
2220
+ return { online: null, error: "status_unavailable" };
2221
+ }
2238
2222
  function deviceControlHelp() {
2239
2223
  return `UAP Device Control
2240
2224
 
@@ -2244,13 +2228,14 @@ Usage:
2244
2228
  Commands:
2245
2229
  remote Connect this computer to Device Control
2246
2230
  status Show authentication, device and connection status
2247
- login Authorize this computer in your browser
2231
+ login Pair this computer using a temporary admin-issued code
2248
2232
  logout Remove the saved authorization
2249
2233
  browser-reset Reset only the saved browser-extension pairing
2250
2234
  install-service Install the authenticated Remote as a system service
2251
2235
  help Show this help
2252
2236
 
2253
2237
  Remote options:
2238
+ --pairing-code <code> One-time code generated in the admin console
2254
2239
  --root <id=path> Add a writable filesystem root
2255
2240
  --read-only-root <id=path> Add a read-only filesystem root
2256
2241
  --allow-executable <path> Allow an executable for terminal commands
@@ -2264,7 +2249,7 @@ Remote options:
2264
2249
 
2265
2250
  Examples:
2266
2251
  npx @codingfrees/uap-device-control@latest
2267
- npx @codingfrees/uap-device-control@latest login
2252
+ npx @codingfrees/uap-device-control@latest login --pairing-code <code>
2268
2253
  npx @codingfrees/uap-device-control@latest browser-reset
2269
2254
  npx @codingfrees/uap-device-control@latest remote
2270
2255
  npx @codingfrees/uap-device-control@latest remote --no-browser-control
@@ -2298,6 +2283,10 @@ function port(value, label) {
2298
2283
  if (!Number.isInteger(result) || result < 1024 || result > 65535) throw new TypeError(label + " is invalid");
2299
2284
  return result;
2300
2285
  }
2286
+ function pairing(value) {
2287
+ if (!value || !/^[A-Za-z0-9_-]{32}$/.test(value)) throw new TypeError("pairing code must be a valid 32-character code from the admin console");
2288
+ return value;
2289
+ }
2301
2290
  function identifier2(value, label) {
2302
2291
  const result = required(value, label);
2303
2292
  if (!/^[A-Za-z0-9_.@:-]{1,256}$/.test(result)) throw new TypeError(label + " is invalid");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codingfrees/uap-device-control",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "description": "Cross-platform outbound UAP Device Control client",
5
5
  "type": "module",
6
6
  "bin": {