@codingfrees/uap-device-control 0.2.0 → 0.2.2
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/dist/uap-device-control.mjs +146 -25
- package/package.json +1 -1
|
@@ -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
|
-
|
|
111
|
-
|
|
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.
|
|
673
|
+
version: "0.2.2",
|
|
629
674
|
description: "Cross-platform outbound UAP Device Control client",
|
|
630
675
|
type: "module",
|
|
631
676
|
bin: {
|
|
@@ -651,8 +696,9 @@ var package_default = {
|
|
|
651
696
|
};
|
|
652
697
|
|
|
653
698
|
// ../device-agent/src/engine.ts
|
|
654
|
-
import { spawn } from "node:child_process";
|
|
655
|
-
import {
|
|
699
|
+
import { execFile as execFile2, spawn } from "node:child_process";
|
|
700
|
+
import { promisify as promisify2 } from "node:util";
|
|
701
|
+
import { cp, mkdir as mkdir3, open, readdir, realpath, rename as rename2, rm as rm2, stat, writeFile as writeFile3 } from "node:fs/promises";
|
|
656
702
|
import { realpathSync } from "node:fs";
|
|
657
703
|
import os2 from "node:os";
|
|
658
704
|
import path3 from "node:path";
|
|
@@ -886,9 +932,29 @@ var DeviceAgentEngine = class {
|
|
|
886
932
|
return { path: relative, kind: value.isDirectory() ? "directory" : "file", size: value.size, modifiedAt: value.mtimeMs, createdAt: value.birthtimeMs };
|
|
887
933
|
}
|
|
888
934
|
if (capability === "filesystem.read" || capability === "filesystem.download" || capability === "filesystem.preview") {
|
|
889
|
-
const
|
|
890
|
-
|
|
891
|
-
|
|
935
|
+
const info = await stat(target);
|
|
936
|
+
const chunked = input.offsetBytes !== void 0 || input.lengthBytes !== void 0;
|
|
937
|
+
if (chunked && capability === "filesystem.preview") throw new TypeError("preview does not support byte ranges");
|
|
938
|
+
const limit = Math.min(this.#maxTransfer, 2 * 1024 * 1024);
|
|
939
|
+
if (!chunked && capability !== "filesystem.preview" && info.size > limit) throw new TypeError("file is too large for a single response; use offsetBytes and lengthBytes (up to 1 MiB per chunk)");
|
|
940
|
+
const offset = chunked ? bounded(Number(input.offsetBytes ?? 0), 0, Number.MAX_SAFE_INTEGER, "file offset") : 0;
|
|
941
|
+
const length = chunked ? bounded(Number(input.lengthBytes ?? 1024 * 1024), 1, Math.min(this.#maxTransfer, 1024 * 1024), "chunk size") : capability === "filesystem.preview" ? Math.min(info.size, this.#maxTransfer, 64 * 1024) : info.size;
|
|
942
|
+
if (offset > info.size) throw new TypeError("file offset exceeds size");
|
|
943
|
+
const handle = await open(target, "r");
|
|
944
|
+
let data;
|
|
945
|
+
try {
|
|
946
|
+
const buffer = Buffer.allocUnsafe(Math.min(length, info.size - offset));
|
|
947
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
|
|
948
|
+
data = buffer.subarray(0, bytesRead);
|
|
949
|
+
} finally {
|
|
950
|
+
await handle.close();
|
|
951
|
+
}
|
|
952
|
+
return {
|
|
953
|
+
contentBase64: data.toString("base64"),
|
|
954
|
+
size: data.byteLength,
|
|
955
|
+
...chunked ? { totalSize: info.size, offsetBytes: offset, nextOffsetBytes: offset + data.byteLength, eof: offset + data.byteLength >= info.size } : {},
|
|
956
|
+
...capability === "filesystem.preview" ? { totalSize: info.size, preview: data.toString("utf8") } : {}
|
|
957
|
+
};
|
|
892
958
|
}
|
|
893
959
|
if (root2.readOnly) throw new TypeError("device root is read only");
|
|
894
960
|
if (capability === "filesystem.write" || capability === "filesystem.upload") {
|
|
@@ -939,7 +1005,13 @@ var DeviceAgentEngine = class {
|
|
|
939
1005
|
}
|
|
940
1006
|
async #process(capability, input, workspaceId) {
|
|
941
1007
|
this.#prune();
|
|
942
|
-
if (capability === "process.list")
|
|
1008
|
+
if (capability === "process.list") {
|
|
1009
|
+
if (input.includeSystem === true) {
|
|
1010
|
+
if (this.options.systemProcessInventory === false) throw new TypeError("system process inventory is disabled");
|
|
1011
|
+
return { scope: "system", processes: await systemProcessInventory() };
|
|
1012
|
+
}
|
|
1013
|
+
return { scope: "workspace", processes: [...this.#processes.values()].filter((value2) => value2.workspaceId === workspaceId).map(summary) };
|
|
1014
|
+
}
|
|
943
1015
|
if (capability === "process.start") {
|
|
944
1016
|
if (this.#running(this.#processes) >= this.#maxProcesses) throw new TypeError("process limit reached");
|
|
945
1017
|
const value2 = this.#spawn(input, false, workspaceId);
|
|
@@ -1360,13 +1432,33 @@ function environment(value) {
|
|
|
1360
1432
|
}
|
|
1361
1433
|
return result;
|
|
1362
1434
|
}
|
|
1435
|
+
var runInventory = promisify2(execFile2);
|
|
1436
|
+
async function systemProcessInventory() {
|
|
1437
|
+
const windows = process.platform === "win32";
|
|
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 });
|
|
1439
|
+
const records = [];
|
|
1440
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
1441
|
+
if (windows) {
|
|
1442
|
+
const match = /^"((?:[^"]|"")*)","(\d+)"/.exec(line);
|
|
1443
|
+
if (match) {
|
|
1444
|
+
const rawMemory = /,"([\d,.\s]+)\s*K"\s*$/.exec(line)?.[1];
|
|
1445
|
+
const memoryKb = rawMemory ? Number(rawMemory.replace(/\D/g, "")) : void 0;
|
|
1446
|
+
records.push({ pid: Number(match[2]), name: match[1].replaceAll('""', '"').slice(0, 128), ...memoryKb !== void 0 ? { memoryKb } : {} });
|
|
1447
|
+
}
|
|
1448
|
+
} else {
|
|
1449
|
+
const match = /^\s*(\d+)\s+(\S+)\s+(\d+)\s+([\d.]+)/.exec(line);
|
|
1450
|
+
if (match) records.push({ pid: Number(match[1]), name: match[2].slice(0, 128), memoryKb: Number(match[3]), cpuPercent: Number(match[4]) });
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
return records.sort((left, right) => (right.memoryKb ?? 0) - (left.memoryKb ?? 0)).slice(0, 200);
|
|
1454
|
+
}
|
|
1363
1455
|
var defaultShell = () => process.platform === "win32" ? "powershell.exe" : "/bin/sh";
|
|
1364
1456
|
var defaultExecutables = () => process.platform === "win32" ? ["powershell.exe", "cmd.exe"] : ["/bin/sh", "/bin/bash"];
|
|
1365
1457
|
|
|
1366
1458
|
// ../device-agent/src/native-desktop.ts
|
|
1367
|
-
import { execFile } from "node:child_process";
|
|
1368
|
-
import { promisify } from "node:util";
|
|
1369
|
-
var execute =
|
|
1459
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
1460
|
+
import { promisify as promisify3 } from "node:util";
|
|
1461
|
+
var execute = promisify3(execFile3);
|
|
1370
1462
|
async function createNativeDesktopAdapter(platform = process.platform, run = execute) {
|
|
1371
1463
|
if (platform === "win32") return windowsAdapter(run);
|
|
1372
1464
|
if (platform === "linux") {
|
|
@@ -1622,11 +1714,11 @@ var WINDOWS_CLIPBOARD_READ = "Add-Type -AssemblyName System.Windows.Forms;[Conso
|
|
|
1622
1714
|
var WINDOWS_CLIPBOARD_WRITE = "param($text) Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Clipboard]::SetText($text)";
|
|
1623
1715
|
|
|
1624
1716
|
// ../device-agent/src/native-services.ts
|
|
1625
|
-
import { execFile as
|
|
1717
|
+
import { execFile as execFile4 } from "node:child_process";
|
|
1626
1718
|
import { realpath as realpath2, stat as stat2 } from "node:fs/promises";
|
|
1627
1719
|
import { win32 } from "node:path";
|
|
1628
|
-
import { promisify as
|
|
1629
|
-
var execute2 =
|
|
1720
|
+
import { promisify as promisify4 } from "node:util";
|
|
1721
|
+
var execute2 = promisify4(execFile4);
|
|
1630
1722
|
async function createNativeServiceAdapter(options = {}) {
|
|
1631
1723
|
const platform = options.platform ?? process.platform;
|
|
1632
1724
|
const environment2 = options.environment ?? process.env;
|
|
@@ -1790,7 +1882,7 @@ function optionalBrowserBridgeFailure(error) {
|
|
|
1790
1882
|
if (!error || typeof error !== "object" || !("code" in error)) return false;
|
|
1791
1883
|
return ["EADDRINUSE", "EACCES", "EAFNOSUPPORT", "EPROTONOSUPPORT"].includes(String(error.code));
|
|
1792
1884
|
}
|
|
1793
|
-
async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal, log, socketFactory = defaultSocketFactory) {
|
|
1885
|
+
async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal, log, socketFactory = defaultSocketFactory, healthIntervalMs = 45e3) {
|
|
1794
1886
|
const deviceId = engine.options.deviceId;
|
|
1795
1887
|
const socket = await authorizedSocket(origin, stateDirectory, fetcher, socketFactory, signal, log, deviceId);
|
|
1796
1888
|
const inFlight = /* @__PURE__ */ new Set();
|
|
@@ -1818,6 +1910,9 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
|
|
|
1818
1910
|
try {
|
|
1819
1911
|
await new Promise((resolve, reject) => {
|
|
1820
1912
|
let connected = false;
|
|
1913
|
+
let probeInProgress = false;
|
|
1914
|
+
let probeFailures = 0;
|
|
1915
|
+
let healthTimer;
|
|
1821
1916
|
const fail = (error) => {
|
|
1822
1917
|
for (const pending of acknowledgements.values()) pending.reject(error);
|
|
1823
1918
|
acknowledgements.clear();
|
|
@@ -1829,6 +1924,26 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
|
|
|
1829
1924
|
if (value.type === "connected") {
|
|
1830
1925
|
connected = true;
|
|
1831
1926
|
log?.({ event: "remote.session", status: "connected", deviceId, agentVersion: UAP_DEVICE_CONTROL_AGENT_VERSION });
|
|
1927
|
+
if (!healthTimer) {
|
|
1928
|
+
healthTimer = setInterval(() => {
|
|
1929
|
+
if (probeInProgress || signal?.aborted) return;
|
|
1930
|
+
probeInProgress = true;
|
|
1931
|
+
void remoteStatus(origin, stateDirectory, deviceId, fetcher).then((state) => {
|
|
1932
|
+
if (state.online) return void (probeFailures = 0);
|
|
1933
|
+
log?.({ event: "remote.session", status: "broker-session-lost", deviceId });
|
|
1934
|
+
fail(new RemoteUnavailableError(void 0, "/device-control/remote/status", "transport"));
|
|
1935
|
+
socket.close(1012, "remote session expired");
|
|
1936
|
+
}).catch(() => {
|
|
1937
|
+
if (++probeFailures < 2) return;
|
|
1938
|
+
log?.({ event: "remote.session", status: "health-unavailable", deviceId });
|
|
1939
|
+
fail(new RemoteUnavailableError(void 0, "/device-control/remote/status", "transport"));
|
|
1940
|
+
socket.close(1012, "remote health unavailable");
|
|
1941
|
+
}).finally(() => {
|
|
1942
|
+
probeInProgress = false;
|
|
1943
|
+
});
|
|
1944
|
+
}, healthIntervalMs);
|
|
1945
|
+
healthTimer.unref();
|
|
1946
|
+
}
|
|
1832
1947
|
return;
|
|
1833
1948
|
}
|
|
1834
1949
|
if (!connected) throw new TypeError("remote socket sent data before connection acknowledgement");
|
|
@@ -1862,9 +1977,13 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
|
|
|
1862
1977
|
socket.close(1002, "invalid message");
|
|
1863
1978
|
}
|
|
1864
1979
|
};
|
|
1865
|
-
const onClose = () =>
|
|
1980
|
+
const onClose = () => {
|
|
1981
|
+
if (healthTimer) clearInterval(healthTimer);
|
|
1982
|
+
signal?.aborted ? resolve() : fail(resultFailure instanceof Error ? resultFailure : new RemoteUnavailableError(void 0, "/device-control/remote/socket", "transport"));
|
|
1983
|
+
};
|
|
1866
1984
|
const onError = () => fail(new RemoteUnavailableError(void 0, "/device-control/remote/socket", "transport"));
|
|
1867
1985
|
const onAbort = () => {
|
|
1986
|
+
if (healthTimer) clearInterval(healthTimer);
|
|
1868
1987
|
socket.close(1e3, "client stopped");
|
|
1869
1988
|
resolve();
|
|
1870
1989
|
};
|
|
@@ -1882,7 +2001,7 @@ function defaultSocketFactory(url, token) {
|
|
|
1882
2001
|
return new WebSocket(url, { headers: { authorization: "Bearer " + token } });
|
|
1883
2002
|
}
|
|
1884
2003
|
async function authorizedSocket(origin, stateDirectory, fetcher, factory, signal, log, deviceId) {
|
|
1885
|
-
const
|
|
2004
|
+
const open2 = async (refresh = false) => {
|
|
1886
2005
|
const current = await accessToken(stateDirectory, fetcher, refresh);
|
|
1887
2006
|
const url = new URL("/device-control/remote/socket", canonicalOrigin2(origin));
|
|
1888
2007
|
url.searchParams.set("deviceId", deviceId);
|
|
@@ -1890,11 +2009,11 @@ async function authorizedSocket(origin, stateDirectory, fetcher, factory, signal
|
|
|
1890
2009
|
return await socketHandshake(factory(url.href, current.token), signal);
|
|
1891
2010
|
};
|
|
1892
2011
|
try {
|
|
1893
|
-
return await
|
|
2012
|
+
return await open2();
|
|
1894
2013
|
} catch (error) {
|
|
1895
2014
|
if (!(error instanceof RemoteAuthorizationError)) throw error;
|
|
1896
2015
|
log?.({ event: "remote.session", status: "reauthorizing", deviceId, httpStatus: error.httpStatus, pathname: error.pathname });
|
|
1897
|
-
return
|
|
2016
|
+
return open2(true);
|
|
1898
2017
|
}
|
|
1899
2018
|
}
|
|
1900
2019
|
function socketHandshake(socket, signal) {
|
|
@@ -2069,9 +2188,9 @@ import os4 from "node:os";
|
|
|
2069
2188
|
import path5 from "node:path";
|
|
2070
2189
|
import { chmod, copyFile, mkdir as mkdir4, rename as rename3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
|
|
2071
2190
|
import { existsSync } from "node:fs";
|
|
2072
|
-
import { execFile as
|
|
2073
|
-
import { promisify as
|
|
2074
|
-
var execute3 =
|
|
2191
|
+
import { execFile as execFile5 } from "node:child_process";
|
|
2192
|
+
import { promisify as promisify5 } from "node:util";
|
|
2193
|
+
var execute3 = promisify5(execFile5);
|
|
2075
2194
|
async function installRemoteService(origin, stateDirectory) {
|
|
2076
2195
|
if (await runnerV2Installed()) throw new TypeError("Runner V2 is installed; use its Device Control provider instead of installing a duplicate Remote service");
|
|
2077
2196
|
const command = process.execPath;
|
|
@@ -2278,8 +2397,9 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
|
|
|
2278
2397
|
output({ status: "installed", ...await installRemoteService(resolvedOrigin, config.stateDirectory) });
|
|
2279
2398
|
return;
|
|
2280
2399
|
}
|
|
2281
|
-
const lease = await acquireRemoteProcessLock(config.stateDirectory);
|
|
2400
|
+
const lease = await acquireRemoteProcessLock(config.stateDirectory, true);
|
|
2282
2401
|
try {
|
|
2402
|
+
if (lease.replaced) output({ event: "remote.session", status: "replaced" });
|
|
2283
2403
|
if (!existingAuth) {
|
|
2284
2404
|
if (config.service) throw new TypeError("service mode requires login");
|
|
2285
2405
|
await loginDeviceControl(resolvedOrigin, config.stateDirectory, {
|
|
@@ -2336,6 +2456,7 @@ function formatCliEvent(event, json2 = false) {
|
|
|
2336
2456
|
if (status === "unpaired") return "\u{1F50C} UAP Browser Extension unpaired";
|
|
2337
2457
|
}
|
|
2338
2458
|
if (event.event === "remote.session") {
|
|
2459
|
+
if (status === "replaced") return "\u267B\uFE0F Previous UAP Remote instance stopped; starting the new session";
|
|
2339
2460
|
if (status === "connected") return "\u2705 Device connected \xB7 " + String(event.deviceId) + (event.agentVersion ? " \xB7 v" + String(event.agentVersion) : "");
|
|
2340
2461
|
if (status === "disconnected") return "\u{1F50C} Device disconnected \xB7 " + String(event.deviceId);
|
|
2341
2462
|
if (status === "reconnecting") return "\u26A0\uFE0F Connection interrupted" + httpDetail(event) + " \xB7 retrying in " + String(event.retryMs) + " ms";
|
|
@@ -2374,7 +2495,7 @@ Usage:
|
|
|
2374
2495
|
uap-device-control <command> [options]
|
|
2375
2496
|
|
|
2376
2497
|
Commands:
|
|
2377
|
-
remote Connect this computer to Device Control
|
|
2498
|
+
remote Connect this computer to Device Control (replace a verified existing Remote instance)
|
|
2378
2499
|
status Show authentication, device and connection status
|
|
2379
2500
|
login Sign in through browser OAuth/PKCE or an admin-issued pairing code
|
|
2380
2501
|
logout Remove the saved authorization
|