@codingfrees/uap-device-control 0.2.12 → 0.2.14

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
@@ -4,7 +4,7 @@ Cross-platform outbound Device Control client for Universal Agent Platform.
4
4
 
5
5
  ## Requirements
6
6
 
7
- - Node.js 26.x (`>=26.8.1 <27`)
7
+ - Node.js 24.18.1 or later, 25.x, or 26.x (`>=24.18.1 <27`). Prefer supported LTS majors for ongoing installations.
8
8
  - a public UAP Device Control origin for first login
9
9
  - Windows, Linux or macOS
10
10
 
@@ -234,19 +234,19 @@ async function loginDeviceControl(origin, stateDirectory, options = {}) {
234
234
  if (options.pairingCode !== void 0 && !/^[A-Za-z0-9_-]{32}$/.test(options.pairingCode)) throw new TypeError("invalid single-use pairing code");
235
235
  const fetcher = options.fetcher ?? fetch;
236
236
  const issuer = canonicalOrigin(origin);
237
- const metadata = await json(fetcher(new URL("/.well-known/oauth-authorization-server", issuer), { redirect: "error", cache: "no-store" }));
237
+ const requestTimeoutMs = options.requestTimeoutMs ?? 15e3;
238
+ const requestJson = (url, init = {}) => timedJson(fetcher, url, init, requestTimeoutMs);
239
+ const metadata = await requestJson(new URL("/.well-known/oauth-authorization-server", issuer), { redirect: "error", cache: "no-store" });
238
240
  const authorizationEndpoint = exactHttps(metadata.authorization_endpoint, issuer);
239
241
  const tokenEndpoint = exactHttps(metadata.token_endpoint, issuer);
240
242
  const registrationEndpoint = exactHttps(metadata.registration_endpoint, issuer);
241
- const callback = await callbackServer(options.timeoutMs ?? 12e4);
243
+ const callback = await callbackServer();
242
244
  try {
243
- const registration = await json(
244
- fetcher(registrationEndpoint, {
245
- method: "POST",
246
- headers: { "content-type": "application/json" },
247
- body: JSON.stringify({ redirect_uris: [callback.redirectUri], token_endpoint_auth_method: "none", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"] })
248
- })
249
- );
245
+ const registration = await requestJson(registrationEndpoint, {
246
+ method: "POST",
247
+ headers: { "content-type": "application/json" },
248
+ body: JSON.stringify({ redirect_uris: [callback.redirectUri], token_endpoint_auth_method: "none", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"] })
249
+ });
250
250
  const clientId = text(registration.client_id, "OAuth client id");
251
251
  const pkce = await createOAuthPkce();
252
252
  const authorize2 = new URL(authorizationEndpoint);
@@ -258,15 +258,13 @@ async function loginDeviceControl(origin, stateDirectory, options = {}) {
258
258
  authorize2.searchParams.set("state", pkce.state);
259
259
  authorize2.searchParams.set("code_challenge", pkce.challenge);
260
260
  authorize2.searchParams.set("code_challenge_method", "S256");
261
- const result = options.pairingCode ? await automaticPairing(fetcher, issuer, authorize2, options.pairingCode, pkce.state) : await browserAuthorization(authorize2, callback.result, options.onAuthorizationUrl);
261
+ const result = options.pairingCode ? await automaticPairing(requestJson, issuer, authorize2, options.pairingCode, pkce.state) : await browserAuthorization(authorize2, callback.result, options.onAuthorizationUrl, options.timeoutMs ?? 8 * 6e4);
262
262
  if (result.state !== pkce.state || !result.code) throw new TypeError("OAuth callback is invalid");
263
- const token = await json(
264
- fetcher(tokenEndpoint, {
265
- method: "POST",
266
- headers: { "content-type": "application/x-www-form-urlencoded" },
267
- body: new URLSearchParams({ grant_type: "authorization_code", client_id: clientId, code: result.code, redirect_uri: callback.redirectUri, code_verifier: pkce.verifier, resource: issuer + "/mcp" })
268
- })
269
- );
263
+ const token = await requestJson(tokenEndpoint, {
264
+ method: "POST",
265
+ headers: { "content-type": "application/x-www-form-urlencoded" },
266
+ body: new URLSearchParams({ grant_type: "authorization_code", client_id: clientId, code: result.code, redirect_uri: callback.redirectUri, code_verifier: pkce.verifier, resource: issuer + "/mcp" })
267
+ });
270
268
  const refreshToken = text(token.refresh_token, "OAuth refresh token");
271
269
  const accessToken2 = text(token.access_token, "OAuth access token");
272
270
  const expiresIn = integer(token.expires_in, "OAuth expiry");
@@ -329,37 +327,65 @@ async function logoutDeviceControl(stateDirectory, fetcher = fetch) {
329
327
  await clearRemoteAuth(stateDirectory);
330
328
  return true;
331
329
  }
332
- async function browserAuthorization(authorize2, result, onAuthorizationUrl) {
330
+ async function browserAuthorization(authorize2, result, onAuthorizationUrl, timeoutMs) {
333
331
  await onAuthorizationUrl?.(authorize2.href);
334
- return result;
332
+ return withTimeout(result, timeoutMs, "OAuth browser authorization timed out; finish Google sign-in and select Authorize this computer in the same browser.");
335
333
  }
336
- async function automaticPairing(fetcher, issuer, authorize2, pairingCode, expectedState) {
337
- const started = await json(
338
- fetcher(new URL("/pairing/start", issuer), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ authorizeUrl: authorize2.href }), redirect: "error", cache: "no-store" })
339
- );
334
+ async function automaticPairing(requestJson, issuer, authorize2, pairingCode, expectedState) {
335
+ const started = await requestJson(new URL("/pairing/start", issuer), {
336
+ method: "POST",
337
+ headers: { "content-type": "application/json" },
338
+ body: JSON.stringify({ authorizeUrl: authorize2.href }),
339
+ redirect: "error",
340
+ cache: "no-store"
341
+ });
340
342
  const pairingId = text(started.pairingId, "pairing id");
341
343
  const pollToken = text(started.pollToken, "pairing poll token");
342
- await json(
343
- fetcher(new URL("/pairing/approve", issuer), {
344
- method: "POST",
345
- headers: { "content-type": "application/json", "x-uap-pairing-code": pairingCode },
346
- body: JSON.stringify({ pairingId }),
347
- redirect: "error",
348
- cache: "no-store"
349
- })
350
- );
351
- const status = await json(
352
- fetcher(new URL("/pairing/status", issuer), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ pairingId, pollToken }), redirect: "error", cache: "no-store" })
353
- );
344
+ await requestJson(new URL("/pairing/approve", issuer), {
345
+ method: "POST",
346
+ headers: { "content-type": "application/json", "x-uap-pairing-code": pairingCode },
347
+ body: JSON.stringify({ pairingId }),
348
+ redirect: "error",
349
+ cache: "no-store"
350
+ });
351
+ const status = await requestJson(new URL("/pairing/status", issuer), {
352
+ method: "POST",
353
+ headers: { "content-type": "application/json" },
354
+ body: JSON.stringify({ pairingId, pollToken }),
355
+ redirect: "error",
356
+ cache: "no-store"
357
+ });
354
358
  if (status.status !== "approved" || typeof status.redirect !== "string") throw new TypeError("pairing approval failed");
355
359
  const redirect = new URL(status.redirect);
356
360
  if (redirect.searchParams.get("state") !== expectedState) throw new TypeError("pairing callback state is invalid");
357
361
  return { code: redirect.searchParams.get("code") ?? void 0, state: redirect.searchParams.get("state") ?? void 0 };
358
362
  }
359
- async function callbackServer(timeoutMs) {
363
+ async function timedJson(fetcher, url, init, timeoutMs) {
364
+ const controller = new AbortController();
365
+ return withTimeout(json(fetcher(url, { ...init, signal: controller.signal })), timeoutMs, `OAuth request timed out at ${url.pathname}`, () => controller.abort());
366
+ }
367
+ async function withTimeout(pending, timeoutMs, message, onTimeout) {
368
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 10 * 6e4) throw new TypeError("OAuth timeout setting is invalid");
369
+ let timer;
370
+ try {
371
+ return await Promise.race([
372
+ pending,
373
+ new Promise((_, reject) => {
374
+ timer = setTimeout(() => {
375
+ reject(new TypeError(message));
376
+ onTimeout?.();
377
+ }, timeoutMs);
378
+ })
379
+ ]);
380
+ } finally {
381
+ clearTimeout(timer);
382
+ }
383
+ }
384
+ async function callbackServer() {
360
385
  let settle;
361
386
  let reject;
362
387
  const result = new Promise((resolve, rejectResult) => (settle = resolve, reject = rejectResult));
388
+ void result.catch(() => void 0);
363
389
  const server = createServer((request, response) => {
364
390
  const url = new URL(request.url ?? "/", "http://127.0.0.1");
365
391
  if (url.pathname !== "/callback") {
@@ -372,7 +398,7 @@ async function callbackServer(timeoutMs) {
372
398
  reject(new TypeError("OAuth browser authorization was declined"));
373
399
  return;
374
400
  }
375
- response.end("UAP Device Control login completed. You can close this window.");
401
+ response.end("UAP Device Control callback received. Return to the terminal to confirm login.");
376
402
  settle({ code: url.searchParams.get("code") ?? void 0, state: url.searchParams.get("state") ?? void 0 });
377
403
  });
378
404
  await new Promise((resolve, rejectListen) => {
@@ -381,13 +407,10 @@ async function callbackServer(timeoutMs) {
381
407
  });
382
408
  const address = server.address();
383
409
  if (!address || typeof address === "string") throw new TypeError("OAuth callback address is unavailable");
384
- const timer = setTimeout(() => reject(new TypeError("OAuth login timed out")), timeoutMs);
385
- timer.unref();
386
410
  return {
387
411
  redirectUri: "http://127.0.0.1:" + address.port + "/callback",
388
412
  result,
389
413
  close: async () => {
390
- clearTimeout(timer);
391
414
  await new Promise((resolve) => server.close(() => resolve()));
392
415
  }
393
416
  };
@@ -802,7 +825,7 @@ import WebSocket from "ws";
802
825
  // package.json
803
826
  var package_default = {
804
827
  name: "@codingfrees/uap-device-control",
805
- version: "0.2.12",
828
+ version: "0.2.14",
806
829
  description: "Cross-platform outbound UAP Device Control client",
807
830
  contentPolicy: {
808
831
  class: "dual-use"
@@ -821,7 +844,7 @@ var package_default = {
821
844
  "DISCLOSURE"
822
845
  ],
823
846
  engines: {
824
- node: ">=26.8.1 <27"
847
+ node: ">=24.18.1 <27"
825
848
  },
826
849
  dependencies: {
827
850
  ws: "8.22.0"
@@ -830,7 +853,7 @@ var package_default = {
830
853
  access: "public"
831
854
  },
832
855
  scripts: {
833
- build: 'pnpm exec esbuild src/bin.ts --bundle --packages=external --platform=node --format=esm --target=node26 --outfile=dist/uap-device-control.mjs --banner:js="#!/usr/bin/env node"',
856
+ build: 'pnpm exec esbuild src/bin.ts --bundle --packages=external --platform=node --format=esm --target=node24 --outfile=dist/uap-device-control.mjs --banner:js="#!/usr/bin/env node"',
834
857
  prepack: "pnpm run build",
835
858
  "publish:public": "node scripts/publish.mjs"
836
859
  }
@@ -838,8 +861,9 @@ var package_default = {
838
861
 
839
862
  // ../device-agent/src/engine.ts
840
863
  import { execFile as execFile2, spawn } from "node:child_process";
864
+ import { once } from "node:events";
841
865
  import { promisify as promisify2 } from "node:util";
842
- import { cp, mkdir as mkdir3, open, readdir, realpath as realpath2, rename as rename2, rm as rm2, stat, writeFile as writeFile3 } from "node:fs/promises";
866
+ import { cp, lstat, mkdir as mkdir3, open, readdir, realpath as realpath2, rename as rename2, rm as rm2, stat, writeFile as writeFile3 } from "node:fs/promises";
843
867
  import { realpathSync } from "node:fs";
844
868
  import os2 from "node:os";
845
869
  import path3 from "node:path";
@@ -1066,8 +1090,13 @@ var DeviceAgentEngine = class {
1066
1090
  return {
1067
1091
  entries: await Promise.all(
1068
1092
  entries.slice(0, 2e3).map(async (entry) => {
1069
- const value = await stat(path3.join(target, entry.name));
1070
- return { name: entry.name, path: path3.posix.join(relative.replaceAll("\\", "/"), entry.name), kind: entry.isDirectory() ? "directory" : "file", size: value.size, modifiedAt: value.mtimeMs };
1093
+ const value = await lstat(path3.join(target, entry.name)).catch(() => null);
1094
+ return {
1095
+ name: entry.name,
1096
+ path: path3.posix.join(relative.replaceAll("\\", "/"), entry.name),
1097
+ kind: entry.isDirectory() ? "directory" : "file",
1098
+ ...value ? { size: value.size, modifiedAt: value.mtimeMs } : { metadataUnavailable: true }
1099
+ };
1071
1100
  })
1072
1101
  )
1073
1102
  };
@@ -1128,7 +1157,7 @@ var DeviceAgentEngine = class {
1128
1157
  }
1129
1158
  async #oneShot(input, workspaceId) {
1130
1159
  const startedAt = Date.now();
1131
- const process2 = this.#spawn(input, false, workspaceId);
1160
+ const process2 = await this.#spawn(input, false, workspaceId);
1132
1161
  process2.capability = "terminal.exec";
1133
1162
  this.#oneShots.set(process2.id, process2);
1134
1163
  const timeoutMs = bounded(Number(input.timeoutMs ?? 3e4), 100, 3e5, "command timeout");
@@ -1159,7 +1188,7 @@ var DeviceAgentEngine = class {
1159
1188
  }
1160
1189
  if (capability === "process.start") {
1161
1190
  if (this.#running(this.#processes) >= this.#maxProcesses) throw new TypeError("process limit reached");
1162
- const value2 = this.#spawn(input, false, workspaceId);
1191
+ const value2 = await this.#spawn(input, false, workspaceId);
1163
1192
  this.#processes.set(value2.id, value2);
1164
1193
  return summary(value2);
1165
1194
  }
@@ -1174,7 +1203,7 @@ var DeviceAgentEngine = class {
1174
1203
  const operation = String(input.operation);
1175
1204
  if (operation === "start") {
1176
1205
  if (this.#running(this.#sessions) >= this.#maxSessions) throw new TypeError("terminal session limit reached");
1177
- const value2 = this.#spawn(input, true, workspaceId);
1206
+ const value2 = await this.#spawn(input, true, workspaceId);
1178
1207
  value2.lastActivityAt = Date.now();
1179
1208
  value2.expiresAt = value2.lastActivityAt + this.#sessionIdleTimeoutMs;
1180
1209
  value2.idleTimer = null;
@@ -1337,16 +1366,14 @@ var DeviceAgentEngine = class {
1337
1366
  this.#screenSessions.delete(sessionId);
1338
1367
  this.#emit("device-agent.screen.expired", "screen.stream", { sessionId, idleTimeoutMs: this.#sessionIdleTimeoutMs }, session.workspaceId);
1339
1368
  }
1340
- #spawn(input, terminal, workspaceId) {
1369
+ async #spawn(input, terminal, workspaceId) {
1341
1370
  const executable = text2(input.executable ?? defaultShell(), 260, "executable");
1342
- if (!this.#unrestricted && ![...this.#allowed].some((allowed) => executable === allowed || path3.basename(executable).toLowerCase() === path3.basename(allowed).toLowerCase())) {
1371
+ if (!this.#unrestricted && ![...this.#allowed].some((allowed) => path3.basename(executable).toLowerCase() === path3.basename(allowed).toLowerCase())) {
1343
1372
  throw new TypeError("executable is not allowed: " + executable);
1344
1373
  }
1345
1374
  const args = Array.isArray(input.args) ? input.args.map((value) => text2(value, 8192, "argument")) : terminal ? [] : [text2(input.command ?? "", 8192, "command")];
1346
1375
  if (args.length > 128 || JSON.stringify(args).length > 32768) throw new TypeError("command length limit exceeded");
1347
- const cwd = input.cwd === void 0 ? void 0 : this.#cwd(input.cwd);
1348
- const env = environment(input.environment);
1349
- const child = spawn(executable, args, { cwd, env: { ...process.env, ...env }, shell: false, windowsHide: true });
1376
+ const child = spawn(executable, args, { cwd: input.cwd === void 0 ? void 0 : this.#cwd(input.cwd), env: { ...process.env, ...environment(input.environment) }, shell: false, windowsHide: true });
1350
1377
  const record = {
1351
1378
  id: randomUUID3(),
1352
1379
  capability: terminal ? "terminal.session" : "process.output",
@@ -1362,16 +1389,14 @@ var DeviceAgentEngine = class {
1362
1389
  truncated: false,
1363
1390
  workspaceId
1364
1391
  };
1365
- child.stdout.on("data", (chunk) => this.#append(record, "stdout", chunk));
1366
- child.stderr.on("data", (chunk) => this.#append(record, "stderr", chunk));
1367
- child.once("close", (code) => {
1368
- record.exitCode = code;
1369
- });
1392
+ for (const stream of ["stdout", "stderr"]) child[stream].on("data", (chunk) => this.#append(record, stream, chunk));
1393
+ child.once("close", (code) => record.exitCode = code);
1394
+ await once(child, "spawn");
1370
1395
  return record;
1371
1396
  }
1372
1397
  #append(record, target, chunk) {
1373
- const totalKey = target === "stdout" ? "stdoutBytes" : "stderrBytes";
1374
- const baseKey = target === "stdout" ? "stdoutBaseBytes" : "stderrBaseBytes";
1398
+ const totalKey = `${target}Bytes`;
1399
+ const baseKey = `${target}BaseBytes`;
1375
1400
  record[totalKey] += chunk.byteLength;
1376
1401
  const next = record[target] + chunk.toString("utf8");
1377
1402
  if (record.capability === "terminal.session") {
@@ -1470,7 +1495,10 @@ var retainUtf8Tail = (value, maximumBytes) => {
1470
1495
  while (start < bytes.byteLength && (bytes[start] & 192) === 128) start++;
1471
1496
  return { text: bytes.subarray(start).toString("utf8"), droppedBytes: start };
1472
1497
  };
1473
- var inside = (root2, target) => target === root2 || target.startsWith(root2 + path3.sep);
1498
+ var inside = (root2, target) => {
1499
+ const relative = path3.relative(root2, target);
1500
+ return relative !== ".." && !relative.startsWith(".." + path3.sep) && !path3.isAbsolute(relative);
1501
+ };
1474
1502
  var executionWorkspaceId = (value) => {
1475
1503
  if (value === void 0) return null;
1476
1504
  if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) throw new TypeError("workspace id is invalid");
@@ -1526,7 +1554,7 @@ function isMissing(error) {
1526
1554
  }
1527
1555
  function safeRelative(value, empty) {
1528
1556
  const result = String(value ?? "");
1529
- if (!empty && !result || result.length > 1024 || path3.isAbsolute(result) || result.split(/[\\/]/).some((part) => part === "..") || result.includes("\0")) {
1557
+ if (!empty && !result || result.length > 1024 || path3.isAbsolute(result) || path3.win32.parse(result).root !== "" || result.split(/[\\/]/).some((part) => part === "..") || result.includes("\0")) {
1530
1558
  throw new TypeError("relative path is invalid");
1531
1559
  }
1532
1560
  return result;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codingfrees/uap-device-control",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "description": "Cross-platform outbound UAP Device Control client",
5
5
  "contentPolicy": {
6
6
  "class": "dual-use"
@@ -19,7 +19,7 @@
19
19
  "DISCLOSURE"
20
20
  ],
21
21
  "engines": {
22
- "node": ">=26.8.1 <27"
22
+ "node": ">=24.18.1 <27"
23
23
  },
24
24
  "dependencies": {
25
25
  "ws": "8.22.0"
@@ -28,7 +28,7 @@
28
28
  "access": "public"
29
29
  },
30
30
  "scripts": {
31
- "build": "pnpm exec esbuild src/bin.ts --bundle --packages=external --platform=node --format=esm --target=node26 --outfile=dist/uap-device-control.mjs --banner:js=\"#!/usr/bin/env node\"",
31
+ "build": "pnpm exec esbuild src/bin.ts --bundle --packages=external --platform=node --format=esm --target=node24 --outfile=dist/uap-device-control.mjs --banner:js=\"#!/usr/bin/env node\"",
32
32
  "prepack": "pnpm run build",
33
33
  "publish:public": "node scripts/publish.mjs"
34
34
  }