@codingfrees/uap-device-control 0.2.1 → 0.2.3

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.
@@ -57,6 +57,8 @@ async function createOAuthPkce() {
57
57
 
58
58
  // src/state.ts
59
59
  import os from "node:os";
60
+ import { execFile } from "node:child_process";
61
+ import { promisify } from "node:util";
60
62
  import path from "node:path";
61
63
  import { link, mkdir, readFile, rm, rename, writeFile } from "node:fs/promises";
62
64
  import { randomUUID } from "node:crypto";
@@ -107,8 +109,51 @@ async function saveRemoteAuth(stateDirectory, value) {
107
109
  async function clearRemoteAuth(stateDirectory) {
108
110
  await rm(path.join(stateDirectory, "auth.json"), { force: true });
109
111
  }
110
- function acquireRemoteProcessLock(stateDirectory) {
111
- return acquireStateLock(stateDirectory, "remote.lock", 0, "another UAP Device Control remote process is already running for this state directory");
112
+ var remoteBusy = "another UAP Device Control remote process is already running for this state directory";
113
+ async function acquireRemoteProcessLock(stateDirectory, replaceExisting = false) {
114
+ if (!replaceExisting) return acquireStateLock(stateDirectory, "remote.lock", 0, remoteBusy);
115
+ const handover = await acquireStateLock(stateDirectory, "remote-handover.lock", 8e3, "another UAP Remote startup is in progress");
116
+ try {
117
+ try {
118
+ return await acquireStateLock(stateDirectory, "remote.lock", 0, remoteBusy);
119
+ } catch (error) {
120
+ if (!(error instanceof TypeError) || error.message !== remoteBusy) throw error;
121
+ }
122
+ const lockFile = path.join(stateDirectory, "remote.lock");
123
+ const prior = await readLock(lockFile);
124
+ if (!prior || !processAlive(prior.pid)) return acquireStateLock(stateDirectory, "remote.lock", 1e3, remoteBusy);
125
+ if (prior.pid === process.pid || !await verifiedRemoteOwner(prior.pid)) throw new TypeError("existing Remote lock owner could not be verified; refusing to stop an unrelated process");
126
+ const current = await readLock(lockFile);
127
+ if (!current || current.pid !== prior.pid || current.token !== prior.token) return acquireStateLock(stateDirectory, "remote.lock", 1e3, remoteBusy);
128
+ try {
129
+ process.kill(prior.pid, "SIGTERM");
130
+ } catch (error) {
131
+ if (processAlive(prior.pid)) throw error;
132
+ }
133
+ const deadline = Date.now() + 6e3;
134
+ while (processAlive(prior.pid) && Date.now() < deadline) await sleep(100);
135
+ if (processAlive(prior.pid)) throw new TypeError("previous UAP Remote instance did not stop; refusing to start another");
136
+ return { ...await acquireStateLock(stateDirectory, "remote.lock", 1e3, remoteBusy), replaced: true };
137
+ } finally {
138
+ await handover.release();
139
+ }
140
+ }
141
+ async function verifiedRemoteOwner(pid) {
142
+ if (process.platform !== "win32") {
143
+ try {
144
+ const args = (await readFile(`/proc/${pid}/cmdline`)).toString("utf8").split("\0").filter(Boolean);
145
+ return args.some((arg) => /(?:^|[\\/])uap-device-control\.mjs$/.test(arg)) && args.includes("remote") && !args.includes("--service");
146
+ } catch {
147
+ return false;
148
+ }
149
+ }
150
+ try {
151
+ const script = String.raw`$p=Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}'; if($p -and $p.Name -eq 'node.exe' -and $p.CommandLine -match '[\\/]uap-device-control\.mjs(?=[\"\s]|$)' -and $p.CommandLine -match '(?:^|\s)remote(?:\s|$)' -and $p.CommandLine -notmatch '(?:^|\s)--service(?:\s|$)') { 'verified' }`;
152
+ const { stdout } = await promisify(execFile)("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], { timeout: 5e3, windowsHide: true, maxBuffer: 1024 });
153
+ return stdout.trim() === "verified";
154
+ } catch {
155
+ return false;
156
+ }
112
157
  }
113
158
  async function withRemoteAuthRefreshLock(stateDirectory, task) {
114
159
  const lease = await acquireStateLock(stateDirectory, "auth-refresh.lock", 2e4, "Device Control authorization refresh is busy");
@@ -625,7 +670,7 @@ import WebSocket from "ws";
625
670
  // package.json
626
671
  var package_default = {
627
672
  name: "@codingfrees/uap-device-control",
628
- version: "0.2.1",
673
+ version: "0.2.3",
629
674
  description: "Cross-platform outbound UAP Device Control client",
630
675
  type: "module",
631
676
  bin: {
@@ -651,8 +696,8 @@ var package_default = {
651
696
  };
652
697
 
653
698
  // ../device-agent/src/engine.ts
654
- import { execFile, spawn } from "node:child_process";
655
- import { promisify } from "node:util";
699
+ import { execFile as execFile2, spawn } from "node:child_process";
700
+ import { promisify as promisify2 } from "node:util";
656
701
  import { cp, mkdir as mkdir3, open, readdir, realpath, rename as rename2, rm as rm2, stat, writeFile as writeFile3 } from "node:fs/promises";
657
702
  import { realpathSync } from "node:fs";
658
703
  import os2 from "node:os";
@@ -1387,7 +1432,7 @@ function environment(value) {
1387
1432
  }
1388
1433
  return result;
1389
1434
  }
1390
- var runInventory = promisify(execFile);
1435
+ var runInventory = promisify2(execFile2);
1391
1436
  async function systemProcessInventory() {
1392
1437
  const windows = process.platform === "win32";
1393
1438
  const { stdout } = await runInventory(windows ? "tasklist.exe" : "ps", windows ? ["/FO", "CSV", "/NH"] : ["-eo", "pid=,comm=,rss=,pcpu="], { timeout: 5e3, maxBuffer: 512 * 1024, windowsHide: true });
@@ -1411,9 +1456,9 @@ var defaultShell = () => process.platform === "win32" ? "powershell.exe" : "/bin
1411
1456
  var defaultExecutables = () => process.platform === "win32" ? ["powershell.exe", "cmd.exe"] : ["/bin/sh", "/bin/bash"];
1412
1457
 
1413
1458
  // ../device-agent/src/native-desktop.ts
1414
- import { execFile as execFile2 } from "node:child_process";
1415
- import { promisify as promisify2 } from "node:util";
1416
- var execute = promisify2(execFile2);
1459
+ import { execFile as execFile3 } from "node:child_process";
1460
+ import { promisify as promisify3 } from "node:util";
1461
+ var execute = promisify3(execFile3);
1417
1462
  async function createNativeDesktopAdapter(platform = process.platform, run = execute) {
1418
1463
  if (platform === "win32") return windowsAdapter(run);
1419
1464
  if (platform === "linux") {
@@ -1669,11 +1714,11 @@ var WINDOWS_CLIPBOARD_READ = "Add-Type -AssemblyName System.Windows.Forms;[Conso
1669
1714
  var WINDOWS_CLIPBOARD_WRITE = "param($text) Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Clipboard]::SetText($text)";
1670
1715
 
1671
1716
  // ../device-agent/src/native-services.ts
1672
- import { execFile as execFile3 } from "node:child_process";
1717
+ import { execFile as execFile4 } from "node:child_process";
1673
1718
  import { realpath as realpath2, stat as stat2 } from "node:fs/promises";
1674
1719
  import { win32 } from "node:path";
1675
- import { promisify as promisify3 } from "node:util";
1676
- var execute2 = promisify3(execFile3);
1720
+ import { promisify as promisify4 } from "node:util";
1721
+ var execute2 = promisify4(execFile4);
1677
1722
  async function createNativeServiceAdapter(options = {}) {
1678
1723
  const platform = options.platform ?? process.platform;
1679
1724
  const environment2 = options.environment ?? process.env;
@@ -1837,7 +1882,7 @@ function optionalBrowserBridgeFailure(error) {
1837
1882
  if (!error || typeof error !== "object" || !("code" in error)) return false;
1838
1883
  return ["EADDRINUSE", "EACCES", "EAFNOSUPPORT", "EPROTONOSUPPORT"].includes(String(error.code));
1839
1884
  }
1840
- async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal, log, socketFactory = defaultSocketFactory, healthIntervalMs = 45e3) {
1885
+ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal, log, socketFactory = defaultSocketFactory) {
1841
1886
  const deviceId = engine.options.deviceId;
1842
1887
  const socket = await authorizedSocket(origin, stateDirectory, fetcher, socketFactory, signal, log, deviceId);
1843
1888
  const inFlight = /* @__PURE__ */ new Set();
@@ -1865,9 +1910,6 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
1865
1910
  try {
1866
1911
  await new Promise((resolve, reject) => {
1867
1912
  let connected = false;
1868
- let probeInProgress = false;
1869
- let probeFailures = 0;
1870
- let healthTimer;
1871
1913
  const fail = (error) => {
1872
1914
  for (const pending of acknowledgements.values()) pending.reject(error);
1873
1915
  acknowledgements.clear();
@@ -1879,26 +1921,6 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
1879
1921
  if (value.type === "connected") {
1880
1922
  connected = true;
1881
1923
  log?.({ event: "remote.session", status: "connected", deviceId, agentVersion: UAP_DEVICE_CONTROL_AGENT_VERSION });
1882
- if (!healthTimer) {
1883
- healthTimer = setInterval(() => {
1884
- if (probeInProgress || signal?.aborted) return;
1885
- probeInProgress = true;
1886
- void remoteStatus(origin, stateDirectory, deviceId, fetcher).then((state) => {
1887
- if (state.online) return void (probeFailures = 0);
1888
- log?.({ event: "remote.session", status: "broker-session-lost", deviceId });
1889
- fail(new RemoteUnavailableError(void 0, "/device-control/remote/status", "transport"));
1890
- socket.close(1012, "remote session expired");
1891
- }).catch(() => {
1892
- if (++probeFailures < 2) return;
1893
- log?.({ event: "remote.session", status: "health-unavailable", deviceId });
1894
- fail(new RemoteUnavailableError(void 0, "/device-control/remote/status", "transport"));
1895
- socket.close(1012, "remote health unavailable");
1896
- }).finally(() => {
1897
- probeInProgress = false;
1898
- });
1899
- }, healthIntervalMs);
1900
- healthTimer.unref();
1901
- }
1902
1924
  return;
1903
1925
  }
1904
1926
  if (!connected) throw new TypeError("remote socket sent data before connection acknowledgement");
@@ -1933,12 +1955,10 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
1933
1955
  }
1934
1956
  };
1935
1957
  const onClose = () => {
1936
- if (healthTimer) clearInterval(healthTimer);
1937
1958
  signal?.aborted ? resolve() : fail(resultFailure instanceof Error ? resultFailure : new RemoteUnavailableError(void 0, "/device-control/remote/socket", "transport"));
1938
1959
  };
1939
1960
  const onError = () => fail(new RemoteUnavailableError(void 0, "/device-control/remote/socket", "transport"));
1940
1961
  const onAbort = () => {
1941
- if (healthTimer) clearInterval(healthTimer);
1942
1962
  socket.close(1e3, "client stopped");
1943
1963
  resolve();
1944
1964
  };
@@ -2143,9 +2163,9 @@ import os4 from "node:os";
2143
2163
  import path5 from "node:path";
2144
2164
  import { chmod, copyFile, mkdir as mkdir4, rename as rename3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
2145
2165
  import { existsSync } from "node:fs";
2146
- import { execFile as execFile4 } from "node:child_process";
2147
- import { promisify as promisify4 } from "node:util";
2148
- var execute3 = promisify4(execFile4);
2166
+ import { execFile as execFile5 } from "node:child_process";
2167
+ import { promisify as promisify5 } from "node:util";
2168
+ var execute3 = promisify5(execFile5);
2149
2169
  async function installRemoteService(origin, stateDirectory) {
2150
2170
  if (await runnerV2Installed()) throw new TypeError("Runner V2 is installed; use its Device Control provider instead of installing a duplicate Remote service");
2151
2171
  const command = process.execPath;
@@ -2352,8 +2372,9 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
2352
2372
  output({ status: "installed", ...await installRemoteService(resolvedOrigin, config.stateDirectory) });
2353
2373
  return;
2354
2374
  }
2355
- const lease = await acquireRemoteProcessLock(config.stateDirectory);
2375
+ const lease = await acquireRemoteProcessLock(config.stateDirectory, true);
2356
2376
  try {
2377
+ if (lease.replaced) output({ event: "remote.session", status: "replaced" });
2357
2378
  if (!existingAuth) {
2358
2379
  if (config.service) throw new TypeError("service mode requires login");
2359
2380
  await loginDeviceControl(resolvedOrigin, config.stateDirectory, {
@@ -2410,6 +2431,7 @@ function formatCliEvent(event, json2 = false) {
2410
2431
  if (status === "unpaired") return "\u{1F50C} UAP Browser Extension unpaired";
2411
2432
  }
2412
2433
  if (event.event === "remote.session") {
2434
+ if (status === "replaced") return "\u267B\uFE0F Previous UAP Remote instance stopped; starting the new session";
2413
2435
  if (status === "connected") return "\u2705 Device connected \xB7 " + String(event.deviceId) + (event.agentVersion ? " \xB7 v" + String(event.agentVersion) : "");
2414
2436
  if (status === "disconnected") return "\u{1F50C} Device disconnected \xB7 " + String(event.deviceId);
2415
2437
  if (status === "reconnecting") return "\u26A0\uFE0F Connection interrupted" + httpDetail(event) + " \xB7 retrying in " + String(event.retryMs) + " ms";
@@ -2448,7 +2470,7 @@ Usage:
2448
2470
  uap-device-control <command> [options]
2449
2471
 
2450
2472
  Commands:
2451
- remote Connect this computer to Device Control
2473
+ remote Connect this computer to Device Control (replace a verified existing Remote instance)
2452
2474
  status Show authentication, device and connection status
2453
2475
  login Sign in through browser OAuth/PKCE or an admin-issued pairing code
2454
2476
  logout Remove the saved authorization
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codingfrees/uap-device-control",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Cross-platform outbound UAP Device Control client",
5
5
  "type": "module",
6
6
  "bin": {