@codingfrees/uap-device-control 0.1.7 → 0.1.9

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.
@@ -60,7 +60,7 @@ async function createOAuthPkce() {
60
60
  // src/state.ts
61
61
  import os from "node:os";
62
62
  import path from "node:path";
63
- import { mkdir, readFile, rm, rename, writeFile } from "node:fs/promises";
63
+ import { link, mkdir, readFile, rm, rename, writeFile } from "node:fs/promises";
64
64
  import { randomUUID } from "node:crypto";
65
65
  function defaultOwnerBootstrapPath(home = os.homedir(), platform = process.platform) {
66
66
  if (platform === "win32") return path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "UAP", "DeviceControl", "owner-bootstrap.json");
@@ -142,17 +142,21 @@ async function withRemoteAuthRefreshLock(stateDirectory, task) {
142
142
  async function acquireStateLock(stateDirectory, name, waitMs, busyMessage) {
143
143
  await mkdir(stateDirectory, { recursive: true, mode: 448 });
144
144
  const file = path.join(stateDirectory, name);
145
- const owner = { pid: process.pid, token: randomUUID(), createdAt: Date.now() };
145
+ const owner = { pid: process.pid, token: randomUUID() };
146
+ const temporary = file + ".tmp-" + owner.token;
146
147
  const deadline = Date.now() + waitMs;
147
148
  for (; ; ) {
148
149
  try {
149
- await writeFile(file, JSON.stringify(owner), { encoding: "utf8", flag: "wx", mode: 384 });
150
+ await writeFile(temporary, JSON.stringify(owner), { encoding: "utf8", flag: "wx", mode: 384 });
151
+ await link(temporary, file);
150
152
  return { release: () => removeOwnedLock(file, owner.token) };
151
153
  } catch (error) {
152
154
  if (!exists(error)) throw error;
155
+ } finally {
156
+ await rm(temporary, { force: true });
153
157
  }
154
158
  const current = await readLock(file);
155
- if (!current) throw new TypeError("Device Control state lock is invalid: " + file);
159
+ if (!current) continue;
156
160
  if (!processAlive(current.pid)) {
157
161
  await removeOwnedLock(file, current.token);
158
162
  continue;
@@ -164,13 +168,13 @@ async function acquireStateLock(stateDirectory, name, waitMs, busyMessage) {
164
168
  async function readLock(file) {
165
169
  try {
166
170
  const raw = JSON.parse(await readFile(file, "utf8"));
167
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
171
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("Device Control state lock is invalid: " + file);
168
172
  const value = raw;
169
- if (!Number.isSafeInteger(value.pid) || Number(value.pid) < 1 || typeof value.token !== "string" || !/^[0-9a-f-]{36}$/.test(value.token) || !Number.isSafeInteger(value.createdAt)) return void 0;
170
- return { pid: Number(value.pid), token: value.token, createdAt: Number(value.createdAt) };
173
+ if (!Number.isSafeInteger(value.pid) || Number(value.pid) < 1 || typeof value.token !== "string" || !/^[0-9a-f-]{36}$/.test(value.token)) throw new TypeError("Device Control state lock is invalid: " + file);
174
+ return { pid: Number(value.pid), token: value.token };
171
175
  } catch (error) {
172
176
  if (missing(error)) return void 0;
173
- return void 0;
177
+ throw error;
174
178
  }
175
179
  }
176
180
  async function removeOwnedLock(file, token) {
@@ -403,7 +407,7 @@ import path4 from "node:path";
403
407
  // package.json
404
408
  var package_default = {
405
409
  name: "@codingfrees/uap-device-control",
406
- version: "0.1.7",
410
+ version: "0.1.9",
407
411
  description: "Cross-platform outbound UAP Device Control client",
408
412
  type: "module",
409
413
  bin: {
@@ -1163,7 +1167,18 @@ async function windowsAdapter(run) {
1163
1167
  const monitors = monitorId ? JSON.parse(asText((await invoke2(WINDOWS_MONITORS)).stdout)) : [];
1164
1168
  const monitor = monitorId ? monitors.find((item) => item.id === monitorId) : void 0;
1165
1169
  if (monitorId && !monitor) throw new TypeError("screen monitor is unavailable");
1166
- await invoke2(WINDOWS_POINTER, pointerArguments(monitor ? { ...input, x: integer2(input.x, 0, 1e5, "x") + monitor.x, y: integer2(input.y, 0, 1e5, "y") + monitor.y, toX: integer2(input.toX ?? input.x, 0, 1e5, "toX") + monitor.x, toY: integer2(input.toY ?? input.y, 0, 1e5, "toY") + monitor.y } : input));
1170
+ await invoke2(
1171
+ WINDOWS_POINTER,
1172
+ pointerArguments(
1173
+ monitor ? {
1174
+ ...input,
1175
+ x: integer2(input.x, 0, 1e5, "x") + monitor.x,
1176
+ y: integer2(input.y, 0, 1e5, "y") + monitor.y,
1177
+ toX: integer2(input.toX ?? input.x, 0, 1e5, "toX") + monitor.x,
1178
+ toY: integer2(input.toY ?? input.y, 0, 1e5, "toY") + monitor.y
1179
+ } : input
1180
+ )
1181
+ );
1167
1182
  },
1168
1183
  keyboard: async (input) => {
1169
1184
  await invoke2(WINDOWS_KEYBOARD, [windowsKeyboardSequence(input)]);
@@ -1180,7 +1195,10 @@ async function windowsInteropScreenAdapter(run) {
1180
1195
  const version = await run(executable, ["-NoProfile", "-NonInteractive", "-Command", "$PSVersionTable.PSVersion.ToString()"], { ...commandOptions(), timeout: 2e3 });
1181
1196
  if (!/^\d+(?:\.\d+)+/.test(asText(version.stdout).trim())) continue;
1182
1197
  const invoke2 = (script, args = []) => powershellInvoke(run, executable, script, args);
1183
- return { monitors: async () => JSON.parse(asText((await invoke2(WINDOWS_MONITORS)).stdout)), captureScreen: async (monitorId, options) => JSON.parse(asText((await invoke2(WINDOWS_CAPTURE, [monitorId ?? "0", options?.format ?? "png", String(options?.quality ?? 100)])).stdout)) };
1198
+ return {
1199
+ monitors: async () => JSON.parse(asText((await invoke2(WINDOWS_MONITORS)).stdout)),
1200
+ captureScreen: async (monitorId, options) => JSON.parse(asText((await invoke2(WINDOWS_CAPTURE, [monitorId ?? "0", options?.format ?? "png", String(options?.quality ?? 100)])).stdout))
1201
+ };
1184
1202
  } catch {
1185
1203
  }
1186
1204
  }
@@ -1199,7 +1217,11 @@ async function linuxAdapter(run) {
1199
1217
  const monitors = parseXrandrGeometry(asText((await run("xrandr", ["--query"], commandOptions())).stdout));
1200
1218
  const monitor2 = monitorId ? monitors.find((item) => item.id === monitorId) : monitors.find((item) => item.primary) ?? monitors[0];
1201
1219
  if (!monitor2) throw new TypeError("screen monitor is unavailable");
1202
- const output2 = await run("import", ["-window", "root", "-crop", `${monitor2.width}x${monitor2.height}+${monitor2.x}+${monitor2.y}`, ...options.format === "jpeg" ? ["-quality", String(options.quality)] : [], `${options.format}:-`], binaryOptions());
1220
+ const output2 = await run(
1221
+ "import",
1222
+ ["-window", "root", "-crop", `${monitor2.width}x${monitor2.height}+${monitor2.x}+${monitor2.y}`, ...options.format === "jpeg" ? ["-quality", String(options.quality)] : [], `${options.format}:-`],
1223
+ binaryOptions()
1224
+ );
1203
1225
  const bytes2 = screenImage(asBuffer(output2.stdout), options.format);
1204
1226
  return { contentType: `image/${options.format}`, contentBase64: bytes2.toString("base64"), width: monitor2.width, height: monitor2.height, monitorId: monitor2.id };
1205
1227
  }
@@ -1269,10 +1291,11 @@ function windowsKeyboardSequence(input) {
1269
1291
  }
1270
1292
  const key = text3(input.key, 64, "keyboard key");
1271
1293
  if (/^F(?:[1-9]|1[0-2])$/.test(key)) return "{" + key + "}";
1272
- const token = WINDOWS_KEY_TOKENS[key];
1273
- if (!token) throw new TypeError("keyboard key is invalid");
1274
1294
  const modifiers = modifierList(input.modifiers);
1275
- return (modifiers.includes("Control") ? "^" : "") + (modifiers.includes("Alt") ? "%" : "") + (modifiers.includes("Shift") ? "+" : "") + token;
1295
+ if (modifiers.includes("Meta")) throw new TypeError("Meta keyboard modifier is unavailable on Windows");
1296
+ const token = WINDOWS_KEY_TOKENS[key] ?? (/^[a-zA-Z0-9]$/.test(key) ? key.toLowerCase() : null);
1297
+ if (!token) throw new TypeError("keyboard key is invalid; use a named key, F1-F12, or a single letter/digit");
1298
+ return (modifiers.includes("Control") ? "^" : "") + (modifiers.includes("Alt") ? "%" : "") + (modifiers.includes("Shift") || /^[A-Z]$/.test(key) && modifiers.length === 0 ? "+" : "") + token;
1276
1299
  }
1277
1300
  function linuxKeySequence(key, rawModifiers) {
1278
1301
  const aliases = { Control: "ctrl", Alt: "alt", Shift: "shift", Meta: "super" };
@@ -1713,7 +1736,11 @@ async function runRemote(options) {
1713
1736
  options.log?.(event);
1714
1737
  if (event.event === "browser.bridge" && (event.status === "paired" || event.status === "unpaired")) refreshSession();
1715
1738
  };
1716
- const browser = options.browserControl === false ? void 0 : await createBrowserBridge(options.stateDirectory, options.browserPort ?? 8800, browserLog);
1739
+ const browser = options.browserControl === false ? void 0 : await createBrowserBridge(options.stateDirectory, options.browserPort ?? 8800, browserLog).catch((error) => {
1740
+ if (!optionalBrowserBridgeFailure(error)) throw error;
1741
+ options.log?.({ event: "browser.bridge", status: "unavailable" });
1742
+ return void 0;
1743
+ });
1717
1744
  if (browser) {
1718
1745
  options.log?.({ event: "browser.bridge", status: "ready", port: browser.port, paired: browser.paired });
1719
1746
  if (browser.pairingCode) options.log?.({ event: "browser.bridge", status: "pairing-required", port: browser.port, pairingCode: browser.pairingCode });
@@ -1766,6 +1793,10 @@ async function runRemote(options) {
1766
1793
  engine.close();
1767
1794
  }
1768
1795
  }
1796
+ function optionalBrowserBridgeFailure(error) {
1797
+ if (!error || typeof error !== "object" || !("code" in error)) return false;
1798
+ return ["EADDRINUSE", "EACCES", "EAFNOSUPPORT", "EPROTONOSUPPORT"].includes(String(error.code));
1799
+ }
1769
1800
  async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal, log) {
1770
1801
  const deviceId = engine.options.deviceId;
1771
1802
  const invoke2 = (pathname, body, requestSignal = signal, timeoutMs = 15e3, requestLog = log) => authorizedRequest(fetcher, origin, stateDirectory, pathname, body, requestSignal, timeoutMs, requestLog, deviceId);
@@ -1991,8 +2022,8 @@ function xml(value) {
1991
2022
  // src/cli.ts
1992
2023
  var DEFAULT_DEVICE_CONTROL_ORIGIN = "https://device-control.aemdpc.ro";
1993
2024
  function parseDeviceControlArguments(args, cwd = process.cwd()) {
1994
- const command = args[0];
1995
- if (!["remote", "status", "login", "logout", "install-service"].includes(command ?? "")) throw new TypeError("command must be remote, status, login, logout, or install-service");
2025
+ const command = !args.length || args.includes("--help") || args.includes("-h") || args[0] === "help" ? "help" : args[0];
2026
+ if (!["help", "remote", "status", "login", "logout", "install-service"].includes(command ?? "")) throw new TypeError("unknown command; run uap-device-control help");
1996
2027
  let origin = process.env.UAP_DEVICE_CONTROL_ORIGIN;
1997
2028
  let stateDirectory = defaultDeviceControlStateDirectory();
1998
2029
  const roots = [];
@@ -2002,7 +2033,7 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
2002
2033
  let browserControl = true;
2003
2034
  let browserPort = 8800;
2004
2035
  let json2 = false;
2005
- for (let index = 1; index < args.length; index++) {
2036
+ for (let index = command === "help" ? args.length : 1; index < args.length; index++) {
2006
2037
  const option = args[index];
2007
2038
  const value = args[index + 1];
2008
2039
  if (option === "--origin") origin = required(value, option), index++;
@@ -2035,6 +2066,10 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
2035
2066
  }
2036
2067
  async function runDeviceControlCli(args = process.argv.slice(2)) {
2037
2068
  const config = parseDeviceControlArguments(args);
2069
+ if (config.command === "help") {
2070
+ process.stdout.write(deviceControlHelp());
2071
+ return;
2072
+ }
2038
2073
  const existingAuth = await loadRemoteAuth(config.stateDirectory);
2039
2074
  const resolvedOrigin = resolveConfiguredOrigin(config.origin, existingAuth?.origin);
2040
2075
  const output = (event) => process.stdout.write(formatCliEvent(event, config.json) + "\n");
@@ -2048,11 +2083,11 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
2048
2083
  return;
2049
2084
  }
2050
2085
  if (config.command === "status") {
2051
- const [auth, deviceId] = await Promise.all([Promise.resolve(existingAuth), loadRemoteDeviceId(config.stateDirectory)]);
2052
- const deviceAuthorized = Boolean(auth?.scope.split(" ").includes("device-control:device"));
2086
+ const [auth, deviceId] = await Promise.all([existingAuth, loadRemoteDeviceId(config.stateDirectory)]);
2087
+ const deviceAuthorized = !!auth?.scope.split(" ").includes("device-control:device");
2053
2088
  let remote;
2054
2089
  if (auth && deviceAuthorized) remote = await remoteStatus(auth.origin, config.stateDirectory, deviceId).catch(() => ({ online: false }));
2055
- output({ deviceId, origin: auth?.origin ?? resolvedOrigin, authenticated: Boolean(auth), deviceAuthorized, remote: remote ?? null, serviceMode: config.service, platform: process.platform });
2090
+ output({ deviceId, origin: auth?.origin ?? resolvedOrigin, authenticated: !!auth, deviceAuthorized, remote: remote ?? null, serviceMode: config.service, platform: process.platform });
2056
2091
  return;
2057
2092
  }
2058
2093
  if (config.command === "install-service") {
@@ -2068,10 +2103,9 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
2068
2103
  }
2069
2104
  const controller = new AbortController();
2070
2105
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => controller.abort());
2071
- const remoteOrigin = resolvedOrigin;
2072
- output({ status: "connecting", origin: remoteOrigin, platform: process.platform });
2106
+ output({ status: "connecting", origin: resolvedOrigin, platform: process.platform });
2073
2107
  await runRemote({
2074
- origin: remoteOrigin,
2108
+ origin: resolvedOrigin,
2075
2109
  stateDirectory: config.stateDirectory,
2076
2110
  roots: config.roots,
2077
2111
  allowedExecutables: config.allowedExecutables,
@@ -2087,18 +2121,18 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
2087
2121
  }
2088
2122
  function formatCliEvent(event, json2 = false) {
2089
2123
  if (json2) return JSON.stringify(event);
2090
- const status = String(event.status ?? "");
2124
+ const status = event.status;
2091
2125
  if (event.event === "plugin.tool") {
2092
2126
  const tool = String(event.tool ?? "tool");
2093
- const phase = String(event.phase ?? "");
2094
- if (phase === "invoking") return "\u{1F527} " + tool + " \xB7 running";
2095
- if (phase === "failed") return "\u274C " + tool + " \xB7 failed";
2127
+ if (event.phase === "invoking") return "\u{1F527} " + tool + " \xB7 running" + (event.deviceId ? " \xB7 " + JSON.stringify(event, ["providerId", "deviceId"]) : "");
2128
+ if (event.phase === "failed") return "\u274C " + tool + " \xB7 failed";
2096
2129
  const summary2 = event.summary && typeof event.summary === "object" ? " \xB7 " + JSON.stringify(event.summary) : "";
2097
2130
  return "\u2705 " + tool + " \xB7 completed" + summary2;
2098
2131
  }
2099
2132
  if (event.event === "browser.bridge") {
2100
2133
  if (status === "ready") return "\u{1F310} Browser bridge ready \xB7 127.0.0.1:" + String(event.port) + (event.paired ? " \xB7 paired" : " \xB7 waiting for pairing");
2101
- if (status === "pairing-required") return "\u{1F510} Browser pairing code: " + String(event.pairingCode) + " \xB7 port " + String(event.port);
2134
+ if (status === "pairing-required") return "\u26A0\uFE0F Browser extension not connected; remote control continues without browser tools \xB7 pairing code " + String(event.pairingCode) + " \xB7 port " + String(event.port);
2135
+ if (status === "unavailable") return "\u26A0\uFE0F Browser control unavailable; remote control continues with files, terminal and processes";
2102
2136
  if (status === "paired") return "\u2705 UAP Browser Extension paired";
2103
2137
  if (status === "connected") return "\u{1F310} UAP Browser Extension connected";
2104
2138
  if (status === "unpaired") return "\u{1F50C} UAP Browser Extension unpaired";
@@ -2117,6 +2151,39 @@ function formatCliEvent(event, json2 = false) {
2117
2151
  if ("authenticated" in event) return (event.authenticated ? "\u2705" : "\u26A0\uFE0F") + " Device " + String(event.deviceId) + " \xB7 " + String(event.origin) + " \xB7 remote=" + JSON.stringify(event.remote);
2118
2152
  return "\u2139\uFE0F " + JSON.stringify(event);
2119
2153
  }
2154
+ function deviceControlHelp() {
2155
+ return `UAP Device Control
2156
+
2157
+ Usage:
2158
+ uap-device-control <command> [options]
2159
+
2160
+ Commands:
2161
+ remote Connect this computer to Device Control
2162
+ status Show authentication, device and connection status
2163
+ login Authorize this computer in your browser
2164
+ logout Remove the saved authorization
2165
+ install-service Install the authenticated Remote as a system service
2166
+ help Show this help
2167
+
2168
+ Remote options:
2169
+ --root <id=path> Add a writable filesystem root
2170
+ --read-only-root <id=path> Add a read-only filesystem root
2171
+ --allow-executable <path> Allow an executable for terminal commands
2172
+ --allow-service <name> Allow a native service
2173
+ --browser-port <port> Browser extension bridge port (default: 8800)
2174
+ --no-browser-control Run without browser integration
2175
+ --state-dir <path> Override the local state directory
2176
+ --origin <https-origin> Override the Device Control service origin
2177
+ --json Emit machine-readable JSON events
2178
+ -h, --help Show this help
2179
+
2180
+ Examples:
2181
+ npx @codingfrees/uap-device-control@latest
2182
+ npx @codingfrees/uap-device-control@latest login
2183
+ npx @codingfrees/uap-device-control@latest remote
2184
+ npx @codingfrees/uap-device-control@latest remote --no-browser-control
2185
+ `;
2186
+ }
2120
2187
  function httpDetail(event) {
2121
2188
  const status = Number(event.httpStatus);
2122
2189
  const pathname = typeof event.pathname === "string" && /^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]{1,255}$/.test(event.pathname) ? event.pathname : "";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codingfrees/uap-device-control",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Cross-platform outbound UAP Device Control client",
5
5
  "type": "module",
6
6
  "bin": {