@codingfrees/uap-device-control 0.1.3 → 0.1.5

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
@@ -28,6 +28,10 @@ You can also provide the origin through `UAP_DEVICE_CONTROL_ORIGIN`.
28
28
  npx @codingfrees/uap-device-control@latest remote
29
29
  ```
30
30
 
31
+ The interactive CLI uses concise human-readable status lines by default (`✅`, `❌`, `⚠️`, `🔐`, `🌐`, `🔌`, `🔧`). Use `--json` for stable JSONL output in scripts and log collectors.
32
+
33
+ By default the Remote process also starts the loopback-only semantic browser bridge on port `8800`. Until the UAP Browser Extension is paired, the CLI prints a short-lived pairing code. Browser control can be disabled with `--no-browser-control` or moved to another loopback port with `--browser-port <port>`.
34
+
31
35
  By default only the current directory is exposed as a Device Control filesystem root. Additional authority must be explicit:
32
36
 
33
37
  ```bash
@@ -38,6 +42,18 @@ npx @codingfrees/uap-device-control@latest remote \
38
42
  --allow-service example.service
39
43
  ```
40
44
 
45
+ ## Semantic browser control
46
+
47
+ Semantic browser control is optional and is executed by the `device-control-browser` companion assembly inside the generic UAP Browser Extension. It does not require Chrome/Edge remote-debugging flags or CDP.
48
+
49
+ 1. Install or enable the optional `device-control-browser` companion in the workspace; it depends on `device-control` and `browser-extension-host`.
50
+ 2. Start `remote` and note the local `🔐 Browser pairing code`.
51
+ 3. Open the UAP Browser Extension popup and the **Device Control · Browser** feature.
52
+ 4. Enter the pairing code and bridge port shown by the CLI, then enable browser control.
53
+ 5. The Remote session reconnects automatically and advertises the browser capabilities.
54
+
55
+ The browser surface supports bounded tab listing, open/navigate/activate/reload/back/forward/close, visible-page snapshot, selector-based click, bounded literal text entry and bounded vertical scrolling. Only HTTPS or loopback HTTP pages are eligible. Page content is untrusted data, no page-supplied JavaScript is evaluated, and every MCP browser tool is approval-gated.
56
+
41
57
  ## Status
42
58
 
43
59
  ```bash
@@ -64,4 +80,16 @@ The `/mcp` endpoint is required by ChatGPT/Codex and the public OpenAI plugin li
64
80
 
65
81
  ## Security boundary
66
82
 
67
- The client opens only outbound HTTPS connections. Filesystem roots, executable allowlists and service allowlists remain local explicit authority. Device credentials are origin-bound and cannot be silently reused against another environment.
83
+ The client opens only outbound HTTPS connections plus the optional browser bridge bound strictly to `127.0.0.1`. Filesystem roots, executable allowlists and service allowlists remain local explicit authority. Device credentials are origin-bound and cannot be silently reused against another environment. Browser pairing uses a short-lived local code, pins the exact extension ID and persists only a token hash on the Remote side; the bearer itself stays in extension storage.
84
+
85
+ ## Publishing
86
+
87
+ Publish a verified public release from this package with:
88
+
89
+ ```bash
90
+ pnpm publish:public
91
+ ```
92
+
93
+ Validate the exact release without publishing with `pnpm publish:public -- --dry-run`.
94
+
95
+ 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.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import path5 from "node:path";
4
+ import path6 from "node:path";
5
5
 
6
6
  // src/auth.ts
7
7
  import { createServer } from "node:http";
@@ -156,17 +156,17 @@ async function loginDeviceControl(origin, stateDirectory, options = {}) {
156
156
  );
157
157
  const clientId = text(registration.client_id, "OAuth client id");
158
158
  const pkce = await createOAuthPkce();
159
- const authorize = new URL(authorizationEndpoint);
160
- authorize.searchParams.set("response_type", "code");
161
- authorize.searchParams.set("client_id", clientId);
162
- authorize.searchParams.set("redirect_uri", callback.redirectUri);
163
- authorize.searchParams.set("resource", issuer + "/mcp");
164
- authorize.searchParams.set("scope", scopes);
165
- authorize.searchParams.set("state", pkce.state);
166
- authorize.searchParams.set("code_challenge", pkce.challenge);
167
- authorize.searchParams.set("code_challenge_method", "S256");
159
+ const authorize2 = new URL(authorizationEndpoint);
160
+ authorize2.searchParams.set("response_type", "code");
161
+ authorize2.searchParams.set("client_id", clientId);
162
+ authorize2.searchParams.set("redirect_uri", callback.redirectUri);
163
+ authorize2.searchParams.set("resource", issuer + "/mcp");
164
+ authorize2.searchParams.set("scope", scopes);
165
+ authorize2.searchParams.set("state", pkce.state);
166
+ authorize2.searchParams.set("code_challenge", pkce.challenge);
167
+ authorize2.searchParams.set("code_challenge_method", "S256");
168
168
  const configuredBootstrap = options.ownerBootstrapSecret === void 0 ? await loadOwnerBootstrapCredential(issuer).then((value) => value?.secret) : options.ownerBootstrapSecret ?? void 0;
169
- const result = configuredBootstrap ? await automaticPairing(fetcher, issuer, authorize, configuredBootstrap, pkce.state) : await browserAuthorization(options.open ?? openBrowser, authorize.href, callback.result);
169
+ const result = configuredBootstrap ? await automaticPairing(fetcher, issuer, authorize2, configuredBootstrap, pkce.state) : await browserAuthorization(options.open ?? openBrowser, authorize2.href, callback.result);
170
170
  if (result.state !== pkce.state || !result.code) throw new TypeError("OAuth callback is invalid");
171
171
  const token = await json(
172
172
  fetcher(tokenEndpoint, {
@@ -219,9 +219,9 @@ async function logoutDeviceControl(stateDirectory, fetcher = fetch) {
219
219
  await clearRemoteAuth(stateDirectory);
220
220
  return true;
221
221
  }
222
- async function automaticPairing(fetcher, issuer, authorize, ownerSecret, expectedState) {
222
+ async function automaticPairing(fetcher, issuer, authorize2, ownerSecret, expectedState) {
223
223
  const started = await json(
224
- fetcher(new URL("/pairing/start", issuer), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ authorizeUrl: authorize.href }), redirect: "error", cache: "no-store" })
224
+ fetcher(new URL("/pairing/start", issuer), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ authorizeUrl: authorize2.href }), redirect: "error", cache: "no-store" })
225
225
  );
226
226
  const pairingId = text(started.pairingId, "pairing id");
227
227
  const pollToken = text(started.pollToken, "pairing poll token");
@@ -289,12 +289,12 @@ async function openBrowser(url) {
289
289
  async function json(response) {
290
290
  const value = await response;
291
291
  if (!value.ok) {
292
- let path6 = "request";
292
+ let path7 = "request";
293
293
  try {
294
- path6 = new URL(value.url).pathname || "request";
294
+ path7 = new URL(value.url).pathname || "request";
295
295
  } catch {
296
296
  }
297
- throw new TypeError(`OAuth request failed (${value.status}) at ${path6}`);
297
+ throw new TypeError(`OAuth request failed (${value.status}) at ${path7}`);
298
298
  }
299
299
  const raw = await value.json();
300
300
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("OAuth response is invalid");
@@ -323,7 +323,7 @@ function integer(value, label) {
323
323
 
324
324
  // src/remote.ts
325
325
  import os3 from "node:os";
326
- import path3 from "node:path";
326
+ import path4 from "node:path";
327
327
 
328
328
  // ../device-agent/src/engine.ts
329
329
  import { spawn } from "node:child_process";
@@ -351,7 +351,12 @@ var DeviceAgentEngine = class {
351
351
  if (this.#roots.has(root2.id) || !path2.isAbsolute(root2.path)) throw new TypeError("device root is invalid");
352
352
  this.#roots.set(root2.id, { ...root2, readOnly: root2.readOnly === true, path: realpathSync(path2.resolve(root2.path)) });
353
353
  }
354
- this.capabilities = [
354
+ for (const adapter of options.capabilityAdapters ?? [])
355
+ for (const capability of adapter.capabilities) {
356
+ if (!/^[a-z][a-z0-9.-]{2,95}$/.test(capability) || this.#capabilityAdapters.has(capability)) throw new TypeError("device capability adapter is invalid");
357
+ this.#capabilityAdapters.set(capability, adapter);
358
+ }
359
+ this.#baseCapabilities = [
355
360
  "device.info",
356
361
  "device.health",
357
362
  "filesystem.roots",
@@ -380,9 +385,10 @@ var DeviceAgentEngine = class {
380
385
  ...options.readClipboard ? ["clipboard.read"] : [],
381
386
  ...options.writeClipboard ? ["clipboard.write"] : []
382
387
  ];
388
+ if ([...this.#capabilityAdapters.keys()].some((capability) => this.#baseCapabilities.includes(capability))) throw new TypeError("device capability adapter collides with a built-in capability");
383
389
  }
384
390
  options;
385
- capabilities;
391
+ #baseCapabilities;
386
392
  #roots = /* @__PURE__ */ new Map();
387
393
  #processes = /* @__PURE__ */ new Map();
388
394
  #oneShots = /* @__PURE__ */ new Map();
@@ -395,7 +401,11 @@ var DeviceAgentEngine = class {
395
401
  #sessionIdleTimeoutMs;
396
402
  #allowed;
397
403
  #allowedServices = /* @__PURE__ */ new Set();
404
+ #capabilityAdapters = /* @__PURE__ */ new Map();
398
405
  #listeners = /* @__PURE__ */ new Set();
406
+ get capabilities() {
407
+ return [...this.#baseCapabilities, ...[...this.#capabilityAdapters].filter(([, adapter]) => adapter.available?.() !== false).map(([capability]) => capability)];
408
+ }
399
409
  info() {
400
410
  return {
401
411
  deviceId: this.options.deviceId,
@@ -411,6 +421,7 @@ var DeviceAgentEngine = class {
411
421
  }
412
422
  close() {
413
423
  this.panicStop();
424
+ for (const adapter of new Set(this.#capabilityAdapters.values())) void adapter.close?.();
414
425
  this.#listeners.clear();
415
426
  }
416
427
  panicStop() {
@@ -524,6 +535,8 @@ var DeviceAgentEngine = class {
524
535
  await this.options.writeClipboard(clipboardText(input.text));
525
536
  return { accepted: true };
526
537
  }
538
+ const adapter = this.#capabilityAdapters.get(capability);
539
+ if (adapter) return adapter.execute(capability, input);
527
540
  throw new TypeError("device capability is unavailable");
528
541
  }
529
542
  async #filesystem(capability, input) {
@@ -716,7 +729,13 @@ var DeviceAgentEngine = class {
716
729
  clearTimeout(session.timer);
717
730
  session.timer = setTimeout(() => void this.#pushScreenFrame(sessionId), session.intervalMs);
718
731
  session.timer.unref();
719
- return { sessionId, intervalMs: session.intervalMs, format: session.format, quality: session.quality, adapted: session.intervalMs !== session.requestedIntervalMs || session.quality !== session.requestedQuality || session.requestedFormat === "auto" && session.format === "jpeg" };
732
+ return {
733
+ sessionId,
734
+ intervalMs: session.intervalMs,
735
+ format: session.format,
736
+ quality: session.quality,
737
+ adapted: session.intervalMs !== session.requestedIntervalMs || session.quality !== session.requestedQuality || session.requestedFormat === "auto" && session.format === "jpeg"
738
+ };
720
739
  }
721
740
  throw new TypeError("screen stream operation is invalid");
722
741
  }
@@ -1349,6 +1368,236 @@ function isMissing2(error) {
1349
1368
  return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
1350
1369
  }
1351
1370
 
1371
+ // src/browser-bridge.ts
1372
+ import { createHash, randomBytes as randomBytes2, randomUUID as randomUUID3, timingSafeEqual } from "node:crypto";
1373
+ import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "node:fs/promises";
1374
+ import { createServer as createServer2 } from "node:http";
1375
+ import path3 from "node:path";
1376
+ var BROWSER_CONTROL_CAPABILITIES = ["browser.tabs", "browser.navigate", "browser.snapshot", "browser.click", "browser.type", "browser.scroll"];
1377
+ var EXTENSION_ID = /^[a-p]{32}$/;
1378
+ async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
1379
+ if (!Number.isInteger(requestedPort) || requestedPort !== 0 && (requestedPort < 1024 || requestedPort > 65535)) throw new TypeError("browser bridge port is invalid");
1380
+ await mkdir3(stateDirectory, { recursive: true, mode: 448 });
1381
+ const statePath = path3.join(stateDirectory, "browser-bridge.json");
1382
+ let pairing = await loadPairing(statePath);
1383
+ let pairingCode = pairing ? void 0 : createPairingCode();
1384
+ let pairingExpiresAt = pairingCode ? Date.now() + 10 * 6e4 : 0;
1385
+ let lastSeen = 0;
1386
+ let waiter;
1387
+ const queue = [];
1388
+ const pending = /* @__PURE__ */ new Map();
1389
+ const server = createServer2(async (request2, response) => {
1390
+ try {
1391
+ const origin = request2.headers.origin ?? "";
1392
+ if (request2.method === "OPTIONS") return cors(response, origin, 204);
1393
+ const url = new URL(request2.url ?? "/", "http://127.0.0.1");
1394
+ if (!url.pathname.startsWith("/browser/")) return send(response, 404, { error: "not_found" }, origin);
1395
+ if (url.pathname === "/browser/pair" && request2.method === "POST") {
1396
+ const body = await jsonBody(request2);
1397
+ const extensionId = extensionIdValue(body.extensionId);
1398
+ if (origin !== "chrome-extension://" + extensionId) throw new TypeError("browser extension origin is invalid");
1399
+ if (pairing) throw new TypeError("browser bridge is already paired");
1400
+ const candidate = pairingCodeValue(body.pairingCode);
1401
+ if (!pairingCode || Date.now() > pairingExpiresAt) {
1402
+ pairingCode = createPairingCode();
1403
+ pairingExpiresAt = Date.now() + 10 * 6e4;
1404
+ log?.({ event: "browser.bridge", status: "pairing-required", port: actualPort(server), pairingCode });
1405
+ throw new TypeError("browser pairing code expired; use the new code shown locally");
1406
+ }
1407
+ if (!secureEqual(candidate, pairingCode)) throw new TypeError("browser pairing code is invalid");
1408
+ const token = randomBytes2(32).toString("base64url");
1409
+ pairing = { extensionId, tokenHash: digest(token) };
1410
+ pairingCode = void 0;
1411
+ pairingExpiresAt = 0;
1412
+ await persistPairing(statePath, pairing);
1413
+ log?.({ event: "browser.bridge", status: "paired" });
1414
+ return send(response, 200, { token, port: actualPort(server) }, origin);
1415
+ }
1416
+ const current = authorize(request2, origin, pairing);
1417
+ if (url.pathname === "/browser/status" && request2.method === "POST") return send(response, 200, { paired: true, online: Date.now() - lastSeen < 45e3 }, current.origin);
1418
+ if (url.pathname === "/browser/unpair" && request2.method === "POST") {
1419
+ pairing = void 0;
1420
+ pairingCode = createPairingCode();
1421
+ pairingExpiresAt = Date.now() + 10 * 6e4;
1422
+ lastSeen = 0;
1423
+ await writeFile3(statePath, JSON.stringify({ version: 1 }) + "\n", { mode: 384 });
1424
+ rejectAll(pending, "browser bridge was unpaired");
1425
+ log?.({ event: "browser.bridge", status: "unpaired" });
1426
+ log?.({ event: "browser.bridge", status: "pairing-required", port: actualPort(server), pairingCode });
1427
+ return send(response, 200, { unpaired: true }, current.origin);
1428
+ }
1429
+ if (url.pathname === "/browser/poll" && request2.method === "POST") {
1430
+ const wasOffline = Date.now() - lastSeen >= 45e3;
1431
+ lastSeen = Date.now();
1432
+ if (wasOffline) log?.({ event: "browser.bridge", status: "connected" });
1433
+ const command = queue.shift() ?? await new Promise((resolve) => {
1434
+ const timer = setTimeout(() => {
1435
+ if (waiter === done) waiter = void 0;
1436
+ resolve(null);
1437
+ }, 2e4);
1438
+ timer.unref();
1439
+ const done = (value) => {
1440
+ clearTimeout(timer);
1441
+ resolve(value);
1442
+ };
1443
+ waiter = done;
1444
+ });
1445
+ return send(response, 200, { command }, current.origin);
1446
+ }
1447
+ if (url.pathname === "/browser/result" && request2.method === "POST") {
1448
+ lastSeen = Date.now();
1449
+ const body = await jsonBody(request2);
1450
+ const requestId = identifier(body.requestId, "requestId");
1451
+ const completion = pending.get(requestId);
1452
+ if (!completion) return send(response, 409, { error: "request_not_pending" }, current.origin);
1453
+ pending.delete(requestId);
1454
+ clearTimeout(completion.timer);
1455
+ if (body.ok === true) completion.resolve(jsonValue(body.output));
1456
+ else completion.reject(new TypeError(typeof body.error === "string" ? body.error.slice(0, 256) : "browser operation failed"));
1457
+ return send(response, 200, { accepted: true }, current.origin);
1458
+ }
1459
+ return send(response, 404, { error: "not_found" }, current.origin);
1460
+ } catch (error) {
1461
+ return send(response, 400, { error: error instanceof Error ? error.message.slice(0, 256) : "browser bridge failed" }, request2.headers.origin ?? "");
1462
+ }
1463
+ });
1464
+ await new Promise((resolve, reject) => {
1465
+ server.once("error", reject);
1466
+ server.listen(requestedPort, "127.0.0.1", () => resolve());
1467
+ });
1468
+ return {
1469
+ get port() {
1470
+ return actualPort(server);
1471
+ },
1472
+ get paired() {
1473
+ return Boolean(pairing);
1474
+ },
1475
+ capabilities: BROWSER_CONTROL_CAPABILITIES,
1476
+ get pairingCode() {
1477
+ return pairingCode;
1478
+ },
1479
+ available() {
1480
+ return Boolean(pairing);
1481
+ },
1482
+ execute(capability, parameters) {
1483
+ if (!BROWSER_CONTROL_CAPABILITIES.includes(capability)) throw new TypeError("browser capability is unavailable");
1484
+ if (!pairing || Date.now() - lastSeen >= 45e3) return Promise.reject(new TypeError("browser control extension is unavailable"));
1485
+ const requestId = randomUUID3();
1486
+ const command = { requestId, capability, parameters };
1487
+ const completion = new Promise((resolve, reject) => {
1488
+ const timer = setTimeout(() => {
1489
+ pending.delete(requestId);
1490
+ reject(new TypeError("browser operation timed out"));
1491
+ }, 45e3);
1492
+ timer.unref();
1493
+ pending.set(requestId, { resolve, reject, timer });
1494
+ });
1495
+ if (waiter) {
1496
+ const deliver = waiter;
1497
+ waiter = void 0;
1498
+ deliver(command);
1499
+ } else queue.push(command);
1500
+ return completion;
1501
+ },
1502
+ async close() {
1503
+ rejectAll(pending, "browser bridge closed");
1504
+ if (waiter) waiter(null);
1505
+ await new Promise((resolve) => server.close(() => resolve()));
1506
+ }
1507
+ };
1508
+ }
1509
+ function authorize(request2, origin, pairing) {
1510
+ if (!pairing || origin !== "chrome-extension://" + pairing.extensionId) throw new TypeError("browser bridge is not paired");
1511
+ const auth = request2.headers.authorization;
1512
+ if (!auth?.startsWith("Bearer ") || digest(auth.slice(7)) !== pairing.tokenHash) throw new TypeError("browser bridge authorization failed");
1513
+ return { origin };
1514
+ }
1515
+ function cors(response, origin, status) {
1516
+ if (/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) {
1517
+ response.setHeader("access-control-allow-origin", origin);
1518
+ response.setHeader("access-control-allow-headers", "authorization,content-type");
1519
+ response.setHeader("access-control-allow-methods", "POST,OPTIONS");
1520
+ response.setHeader("vary", "Origin");
1521
+ }
1522
+ response.statusCode = status;
1523
+ response.end();
1524
+ }
1525
+ function send(response, status, body, origin) {
1526
+ if (/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) {
1527
+ response.setHeader("access-control-allow-origin", origin);
1528
+ response.setHeader("vary", "Origin");
1529
+ }
1530
+ response.statusCode = status;
1531
+ response.setHeader("content-type", "application/json; charset=utf-8");
1532
+ response.setHeader("cache-control", "no-store");
1533
+ response.end(JSON.stringify(body));
1534
+ }
1535
+ async function jsonBody(request2) {
1536
+ const chunks = [];
1537
+ let size = 0;
1538
+ for await (const chunk of request2) {
1539
+ size += Buffer.byteLength(chunk);
1540
+ if (size > 1024 * 1024) throw new TypeError("browser bridge request is too large");
1541
+ chunks.push(Buffer.from(chunk));
1542
+ }
1543
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
1544
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("browser bridge request is invalid");
1545
+ return parsed;
1546
+ }
1547
+ async function loadPairing(file) {
1548
+ try {
1549
+ const parsed = JSON.parse(await readFile3(file, "utf8"));
1550
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
1551
+ const record = parsed;
1552
+ if (record.version !== 1 || typeof record.extensionId !== "string" || typeof record.tokenHash !== "string" || !EXTENSION_ID.test(record.extensionId) || !/^[a-f0-9]{64}$/.test(record.tokenHash)) return void 0;
1553
+ return { extensionId: record.extensionId, tokenHash: record.tokenHash };
1554
+ } catch {
1555
+ return void 0;
1556
+ }
1557
+ }
1558
+ async function persistPairing(file, pairing) {
1559
+ await writeFile3(file, JSON.stringify({ version: 1, ...pairing }) + "\n", { mode: 384 });
1560
+ }
1561
+ function rejectAll(pending, message) {
1562
+ for (const value of pending.values()) {
1563
+ clearTimeout(value.timer);
1564
+ value.reject(new TypeError(message));
1565
+ }
1566
+ pending.clear();
1567
+ }
1568
+ function digest(value) {
1569
+ return createHash("sha256").update(value).digest("hex");
1570
+ }
1571
+ function extensionIdValue(value) {
1572
+ if (typeof value !== "string" || !EXTENSION_ID.test(value)) throw new TypeError("browser extension id is invalid");
1573
+ return value;
1574
+ }
1575
+ function identifier(value, label) {
1576
+ if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(value)) throw new TypeError(label + " is invalid");
1577
+ return value;
1578
+ }
1579
+ function jsonValue(value) {
1580
+ JSON.stringify(value);
1581
+ return value;
1582
+ }
1583
+ function actualPort(server) {
1584
+ const address = server.address();
1585
+ if (!address || typeof address === "string") throw new TypeError("browser bridge is unavailable");
1586
+ return address.port;
1587
+ }
1588
+ function createPairingCode() {
1589
+ return randomBytes2(9).toString("base64url");
1590
+ }
1591
+ function pairingCodeValue(value) {
1592
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]{12,32}$/.test(value)) throw new TypeError("browser pairing code is invalid");
1593
+ return value;
1594
+ }
1595
+ function secureEqual(left, right) {
1596
+ const a = Buffer.from(digest(left), "hex");
1597
+ const b = Buffer.from(digest(right), "hex");
1598
+ return a.length === b.length && timingSafeEqual(a, b);
1599
+ }
1600
+
1352
1601
  // src/remote.ts
1353
1602
  async function runRemote(options) {
1354
1603
  const fetcher = options.fetcher ?? fetch;
@@ -1356,43 +1605,71 @@ async function runRemote(options) {
1356
1605
  const desktop = await createNativeDesktopAdapter();
1357
1606
  const services = options.allowedServices.length ? await createNativeServiceAdapter() : void 0;
1358
1607
  if (options.allowedServices.length && !services) throw new TypeError("native service control is unavailable");
1608
+ let refreshSession = () => {
1609
+ };
1610
+ const browserLog = (event) => {
1611
+ options.log?.(event);
1612
+ if (event.event === "browser.bridge" && (event.status === "paired" || event.status === "unpaired")) refreshSession();
1613
+ };
1614
+ const browser = options.browserControl === false ? void 0 : await createBrowserBridge(options.stateDirectory, options.browserPort ?? 8800, browserLog);
1615
+ if (browser) {
1616
+ options.log?.({ event: "browser.bridge", status: "ready", port: browser.port, paired: browser.paired });
1617
+ if (browser.pairingCode) options.log?.({ event: "browser.bridge", status: "pairing-required", port: browser.port, pairingCode: browser.pairingCode });
1618
+ }
1359
1619
  const engine = new DeviceAgentEngine({
1360
1620
  deviceId,
1361
1621
  name: os3.hostname(),
1362
1622
  roots: options.roots,
1363
1623
  ...options.allowedExecutables.length ? { allowedExecutables: options.allowedExecutables } : {},
1364
1624
  ...services ? { services, allowedServices: options.allowedServices } : {},
1625
+ ...browser ? { capabilityAdapters: [browser] } : {},
1365
1626
  ...desktop
1366
1627
  });
1367
1628
  try {
1368
1629
  let delay = 500;
1369
1630
  while (!options.signal?.aborted) {
1631
+ const sessionController = new AbortController();
1632
+ const abort = () => sessionController.abort();
1633
+ options.signal?.addEventListener("abort", abort, { once: true });
1634
+ refreshSession = abort;
1370
1635
  try {
1371
- await remoteSession(options.origin, options.stateDirectory, engine, fetcher, options.signal);
1636
+ await remoteSession(options.origin, options.stateDirectory, engine, fetcher, sessionController.signal, options.log);
1372
1637
  delay = 500;
1373
1638
  } catch (error) {
1374
1639
  if (options.signal?.aborted) break;
1640
+ if (sessionController.signal.aborted) {
1641
+ delay = 500;
1642
+ continue;
1643
+ }
1375
1644
  if (error instanceof RemoteAuthorizationError) {
1645
+ options.log?.({ event: "remote.session", status: "reauthorizing", deviceId });
1376
1646
  await accessToken(options.stateDirectory, fetcher, true);
1377
1647
  delay = 500;
1378
1648
  continue;
1379
1649
  }
1380
1650
  if (!(error instanceof RemoteUnavailableError)) throw error;
1651
+ options.log?.({ event: "remote.session", status: "reconnecting", deviceId, retryMs: delay });
1381
1652
  await sleep(delay, options.signal);
1382
1653
  delay = Math.min(delay * 2, 15e3);
1654
+ } finally {
1655
+ refreshSession = () => {
1656
+ };
1657
+ options.signal?.removeEventListener("abort", abort);
1383
1658
  }
1384
1659
  }
1385
1660
  } finally {
1386
1661
  engine.close();
1387
1662
  }
1388
1663
  }
1389
- async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal) {
1664
+ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal, log) {
1390
1665
  const { token } = await accessToken(stateDirectory, fetcher);
1391
1666
  const connected = await request(fetcher, origin, "/device-control/remote/connect", token, { device: engine.info() }, signal);
1392
1667
  const sessionId = bounded2(connected.sessionId, "remote session id");
1668
+ log?.({ event: "remote.session", status: "connected", deviceId: engine.options.deviceId });
1393
1669
  try {
1394
1670
  while (!signal?.aborted) {
1395
1671
  const next = await request(fetcher, origin, "/device-control/remote/poll", token, { sessionId, deviceId: engine.options.deviceId }, signal, 35e3);
1672
+ if (next.notice !== void 0) log?.({ event: "plugin.tool", ...noticeValue(next.notice) });
1396
1673
  if (next.command === null || next.command === void 0) continue;
1397
1674
  const command = commandValue(next.command);
1398
1675
  const startedAt = Date.now();
@@ -1412,6 +1689,7 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
1412
1689
  }
1413
1690
  } finally {
1414
1691
  await request(fetcher, origin, "/device-control/remote/disconnect", token, { sessionId, deviceId: engine.options.deviceId }, void 0, 5e3).catch(() => void 0);
1692
+ log?.({ event: "remote.session", status: "disconnected", deviceId: engine.options.deviceId });
1415
1693
  }
1416
1694
  }
1417
1695
  async function request(fetcher, origin, pathname, token, body, signal, timeoutMs = 15e3) {
@@ -1452,7 +1730,7 @@ async function remoteStatus(origin, stateDirectory, deviceId, fetcher = fetch) {
1452
1730
  return { online: value.online, ...lastSeen === void 0 ? {} : { lastSeen: Number(lastSeen) } };
1453
1731
  }
1454
1732
  function defaultRemoteRoots(cwd = process.cwd()) {
1455
- return [{ id: "cwd", label: "Current directory", path: path3.resolve(cwd), readOnly: false }];
1733
+ return [{ id: "cwd", label: "Current directory", path: path4.resolve(cwd), readOnly: false }];
1456
1734
  }
1457
1735
  var RemoteUnavailableError = class extends Error {
1458
1736
  };
@@ -1467,6 +1745,21 @@ function bounded2(value, label) {
1467
1745
  if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(value)) throw new TypeError(label + " is invalid");
1468
1746
  return value;
1469
1747
  }
1748
+ function noticeValue(value) {
1749
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("remote notice is invalid");
1750
+ const record = value;
1751
+ const phase = record.phase;
1752
+ if (phase !== "invoking" && phase !== "invoked" && phase !== "failed") throw new TypeError("remote notice phase is invalid");
1753
+ const summary2 = record.summary;
1754
+ if (summary2 !== void 0 && (!summary2 || typeof summary2 !== "object" || Array.isArray(summary2))) throw new TypeError("remote notice summary is invalid");
1755
+ return {
1756
+ tool: bounded2(record.tool, "remote notice tool"),
1757
+ phase,
1758
+ ...record.providerId === void 0 ? {} : { providerId: bounded2(record.providerId, "remote notice provider") },
1759
+ ...record.deviceId === void 0 ? {} : { deviceId: bounded2(record.deviceId, "remote notice device") },
1760
+ ...summary2 === void 0 ? {} : { summary: summary2 }
1761
+ };
1762
+ }
1470
1763
  function commandValue(value) {
1471
1764
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("remote command is invalid");
1472
1765
  const record = value;
@@ -1495,8 +1788,8 @@ function sleep(ms, signal) {
1495
1788
 
1496
1789
  // src/service.ts
1497
1790
  import os4 from "node:os";
1498
- import path4 from "node:path";
1499
- import { chmod, copyFile, mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
1791
+ import path5 from "node:path";
1792
+ import { chmod, copyFile, mkdir as mkdir4, writeFile as writeFile4 } from "node:fs/promises";
1500
1793
  import { execFile as execFile4 } from "node:child_process";
1501
1794
  import { promisify as promisify4 } from "node:util";
1502
1795
  var execute4 = promisify4(execFile4);
@@ -1504,8 +1797,8 @@ async function installRemoteService(origin, stateDirectory) {
1504
1797
  const command = process.execPath;
1505
1798
  const source = process.argv[1];
1506
1799
  if (!source) throw new TypeError("CLI executable path is unavailable");
1507
- await mkdir3(stateDirectory, { recursive: true, mode: 448 });
1508
- const script = path4.join(stateDirectory, "uap-device-control.mjs");
1800
+ await mkdir4(stateDirectory, { recursive: true, mode: 448 });
1801
+ const script = path5.join(stateDirectory, "uap-device-control.mjs");
1509
1802
  await copyFile(source, script);
1510
1803
  if (process.platform !== "win32") await chmod(script, 448);
1511
1804
  const args = [script, "remote", "--origin", origin, "--state-dir", stateDirectory, "--service"];
@@ -1515,10 +1808,10 @@ async function installRemoteService(origin, stateDirectory) {
1515
1808
  throw new TypeError("service installation is unsupported on this platform");
1516
1809
  }
1517
1810
  async function installSystemd(command, args) {
1518
- const directory = path4.join(os4.homedir(), ".config", "systemd", "user");
1519
- const location = path4.join(directory, "uap-device-control.service");
1520
- await mkdir3(directory, { recursive: true });
1521
- await writeFile3(
1811
+ const directory = path5.join(os4.homedir(), ".config", "systemd", "user");
1812
+ const location = path5.join(directory, "uap-device-control.service");
1813
+ await mkdir4(directory, { recursive: true });
1814
+ await writeFile4(
1522
1815
  location,
1523
1816
  [
1524
1817
  "[Unit]",
@@ -1543,12 +1836,12 @@ async function installSystemd(command, args) {
1543
1836
  return { platform: "linux", location };
1544
1837
  }
1545
1838
  async function installLaunchd(command, args) {
1546
- const directory = path4.join(os4.homedir(), "Library", "LaunchAgents");
1547
- const location = path4.join(directory, "ro.codingfrees.uap-device-control.plist");
1548
- await mkdir3(directory, { recursive: true });
1839
+ const directory = path5.join(os4.homedir(), "Library", "LaunchAgents");
1840
+ const location = path5.join(directory, "ro.codingfrees.uap-device-control.plist");
1841
+ await mkdir4(directory, { recursive: true });
1549
1842
  const escaped = [command, ...args].map((value) => "<string>" + xml(value) + "</string>").join("");
1550
1843
  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>";
1551
- await writeFile3(location, plist, { mode: 384 });
1844
+ await writeFile4(location, plist, { mode: 384 });
1552
1845
  const domain = "gui/" + process.getuid?.();
1553
1846
  await execute4("launchctl", ["bootout", domain, location]).catch(() => void 0);
1554
1847
  await execute4("launchctl", ["bootstrap", domain, location]);
@@ -1582,6 +1875,9 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
1582
1875
  const allowedExecutables = [];
1583
1876
  const allowedServices = [];
1584
1877
  let service = false;
1878
+ let browserControl = true;
1879
+ let browserPort = 8800;
1880
+ let json2 = false;
1585
1881
  for (let index = 1; index < args.length; index++) {
1586
1882
  const option = args[index];
1587
1883
  const value = args[index + 1];
@@ -1591,25 +1887,40 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
1591
1887
  roots.push(root(required(value, option), option === "--read-only-root"));
1592
1888
  index++;
1593
1889
  } else if (option === "--allow-executable") allowedExecutables.push(absolute(value, option)), index++;
1594
- else if (option === "--allow-service") allowedServices.push(identifier(value, option)), index++;
1890
+ else if (option === "--allow-service") allowedServices.push(identifier2(value, option)), index++;
1595
1891
  else if (option === "--service") service = true;
1892
+ else if (option === "--no-browser-control") browserControl = false;
1893
+ else if (option === "--browser-port") browserPort = port(value, option), index++;
1894
+ else if (option === "--json") json2 = true;
1596
1895
  else throw new TypeError("unsupported UAP Device Control option: " + option);
1597
1896
  }
1598
1897
  const normalizedOrigin = origin === void 0 ? void 0 : canonicalOrigin3(origin);
1599
1898
  if (!roots.length && command === "remote") roots.push(...defaultRemoteRoots(cwd));
1600
- return { command, ...normalizedOrigin ? { origin: normalizedOrigin } : {}, stateDirectory, roots, allowedExecutables, allowedServices, service };
1899
+ return {
1900
+ command,
1901
+ ...normalizedOrigin ? { origin: normalizedOrigin } : {},
1902
+ stateDirectory,
1903
+ roots,
1904
+ allowedExecutables,
1905
+ allowedServices,
1906
+ service,
1907
+ browserControl,
1908
+ browserPort,
1909
+ json: json2
1910
+ };
1601
1911
  }
1602
1912
  async function runDeviceControlCli(args = process.argv.slice(2)) {
1603
1913
  const config = parseDeviceControlArguments(args);
1604
1914
  const existingAuth = await loadRemoteAuth(config.stateDirectory);
1605
1915
  const resolvedOrigin = resolveConfiguredOrigin(config.origin, existingAuth?.origin);
1916
+ const output = (event) => process.stdout.write(formatCliEvent(event, config.json) + "\n");
1606
1917
  if (config.command === "login") {
1607
1918
  const auth = await loginDeviceControl(resolvedOrigin, config.stateDirectory);
1608
- process.stdout.write(JSON.stringify({ status: "authenticated", origin: auth.origin }) + "\n");
1919
+ output({ status: "authenticated", origin: auth.origin });
1609
1920
  return;
1610
1921
  }
1611
1922
  if (config.command === "logout") {
1612
- process.stdout.write(JSON.stringify({ status: await logoutDeviceControl(config.stateDirectory) ? "logged-out" : "not-logged-in" }) + "\n");
1923
+ output({ status: await logoutDeviceControl(config.stateDirectory) ? "logged-out" : "not-logged-in" });
1613
1924
  return;
1614
1925
  }
1615
1926
  if (config.command === "status") {
@@ -1617,14 +1928,12 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
1617
1928
  const deviceAuthorized = Boolean(auth?.scope.split(" ").includes("device-control:device"));
1618
1929
  let remote;
1619
1930
  if (auth && deviceAuthorized) remote = await remoteStatus(auth.origin, config.stateDirectory, deviceId).catch(() => ({ online: false }));
1620
- process.stdout.write(
1621
- JSON.stringify({ deviceId, origin: auth?.origin ?? resolvedOrigin, authenticated: Boolean(auth), deviceAuthorized, remote: remote ?? null, serviceMode: config.service, platform: process.platform }) + "\n"
1622
- );
1931
+ output({ deviceId, origin: auth?.origin ?? resolvedOrigin, authenticated: Boolean(auth), deviceAuthorized, remote: remote ?? null, serviceMode: config.service, platform: process.platform });
1623
1932
  return;
1624
1933
  }
1625
1934
  if (config.command === "install-service") {
1626
1935
  if (!existingAuth) throw new TypeError("login is required before install-service");
1627
- process.stdout.write(JSON.stringify({ status: "installed", ...await installRemoteService(resolvedOrigin, config.stateDirectory) }) + "\n");
1936
+ output({ status: "installed", ...await installRemoteService(resolvedOrigin, config.stateDirectory) });
1628
1937
  return;
1629
1938
  }
1630
1939
  if (!existingAuth) {
@@ -1634,8 +1943,50 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
1634
1943
  const controller = new AbortController();
1635
1944
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => controller.abort());
1636
1945
  const remoteOrigin = resolvedOrigin;
1637
- process.stdout.write(JSON.stringify({ status: "connecting", origin: remoteOrigin, platform: process.platform }) + "\n");
1638
- await runRemote({ origin: remoteOrigin, stateDirectory: config.stateDirectory, roots: config.roots, allowedExecutables: config.allowedExecutables, allowedServices: config.allowedServices, signal: controller.signal });
1946
+ output({ status: "connecting", origin: remoteOrigin, platform: process.platform });
1947
+ await runRemote({
1948
+ origin: remoteOrigin,
1949
+ stateDirectory: config.stateDirectory,
1950
+ roots: config.roots,
1951
+ allowedExecutables: config.allowedExecutables,
1952
+ allowedServices: config.allowedServices,
1953
+ browserControl: config.browserControl,
1954
+ browserPort: config.browserPort,
1955
+ signal: controller.signal,
1956
+ log: output
1957
+ });
1958
+ }
1959
+ function formatCliEvent(event, json2 = false) {
1960
+ if (json2) return JSON.stringify(event);
1961
+ const status = String(event.status ?? "");
1962
+ if (event.event === "plugin.tool") {
1963
+ const tool = String(event.tool ?? "tool");
1964
+ const phase = String(event.phase ?? "");
1965
+ if (phase === "invoking") return "\u{1F527} " + tool + " \xB7 running";
1966
+ if (phase === "failed") return "\u274C " + tool + " \xB7 failed";
1967
+ const summary2 = event.summary && typeof event.summary === "object" ? " \xB7 " + JSON.stringify(event.summary) : "";
1968
+ return "\u2705 " + tool + " \xB7 completed" + summary2;
1969
+ }
1970
+ if (event.event === "browser.bridge") {
1971
+ 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");
1972
+ if (status === "pairing-required") return "\u{1F510} Browser pairing code: " + String(event.pairingCode) + " \xB7 port " + String(event.port);
1973
+ if (status === "paired") return "\u2705 UAP Browser Extension paired";
1974
+ if (status === "connected") return "\u{1F310} UAP Browser Extension connected";
1975
+ if (status === "unpaired") return "\u{1F50C} UAP Browser Extension unpaired";
1976
+ }
1977
+ if (event.event === "remote.session") {
1978
+ if (status === "connected") return "\u2705 Device connected \xB7 " + String(event.deviceId);
1979
+ if (status === "disconnected") return "\u{1F50C} Device disconnected \xB7 " + String(event.deviceId);
1980
+ if (status === "reconnecting") return "\u26A0\uFE0F Connection interrupted \xB7 retrying in " + String(event.retryMs) + " ms";
1981
+ if (status === "reauthorizing") return "\u{1F510} Refreshing Device Control authorization";
1982
+ }
1983
+ if (status === "connecting") return "\u{1F310} Connecting to " + String(event.origin) + " \xB7 " + String(event.platform);
1984
+ if (status === "authenticated") return "\u2705 Authenticated \xB7 " + String(event.origin);
1985
+ if (status === "logged-out") return "\u2705 Logged out";
1986
+ if (status === "not-logged-in") return "\u26A0\uFE0F Not logged in";
1987
+ if (status === "installed") return "\u2705 Remote service installed";
1988
+ if ("authenticated" in event) return (event.authenticated ? "\u2705" : "\u26A0\uFE0F") + " Device " + String(event.deviceId) + " \xB7 " + String(event.origin) + " \xB7 remote=" + JSON.stringify(event.remote);
1989
+ return "\u2139\uFE0F " + JSON.stringify(event);
1639
1990
  }
1640
1991
  function resolveConfiguredOrigin(explicit, stored) {
1641
1992
  if (explicit && stored && explicit !== stored) throw new TypeError("configured origin does not match the authenticated origin; logout before changing environments");
@@ -1652,10 +2003,15 @@ function required(value, label) {
1652
2003
  }
1653
2004
  function absolute(value, label) {
1654
2005
  const resolved = required(value, label);
1655
- if (!path5.isAbsolute(resolved)) throw new TypeError(label + " must be absolute");
1656
- return path5.resolve(resolved);
2006
+ if (!path6.isAbsolute(resolved)) throw new TypeError(label + " must be absolute");
2007
+ return path6.resolve(resolved);
1657
2008
  }
1658
- function identifier(value, label) {
2009
+ function port(value, label) {
2010
+ const result = Number(required(value, label));
2011
+ if (!Number.isInteger(result) || result < 1024 || result > 65535) throw new TypeError(label + " is invalid");
2012
+ return result;
2013
+ }
2014
+ function identifier2(value, label) {
1659
2015
  const result = required(value, label);
1660
2016
  if (!/^[A-Za-z0-9_.@:-]{1,256}$/.test(result)) throw new TypeError(label + " is invalid");
1661
2017
  return result;
@@ -1663,12 +2019,13 @@ function identifier(value, label) {
1663
2019
  function root(value, readOnly) {
1664
2020
  const split = value.indexOf("=");
1665
2021
  if (split < 1) throw new TypeError("root must use id=absolute-path");
1666
- const id = identifier(value.slice(0, split), "root id");
2022
+ const id = identifier2(value.slice(0, split), "root id");
1667
2023
  return { id, label: id, path: absolute(value.slice(split + 1), "root path"), readOnly };
1668
2024
  }
1669
2025
 
1670
2026
  // src/bin.ts
1671
2027
  runDeviceControlCli().catch((error) => {
1672
- process.stderr.write(JSON.stringify({ error: error instanceof Error ? error.message : "UAP Device Control failed" }) + "\n");
2028
+ const message = error instanceof Error ? error.message : "UAP Device Control failed";
2029
+ process.stderr.write(process.argv.includes("--json") ? JSON.stringify({ error: message }) + "\n" : "\u274C " + message + "\n");
1673
2030
  process.exitCode = 1;
1674
2031
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codingfrees/uap-device-control",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Cross-platform outbound UAP Device Control client",
5
5
  "type": "module",
6
6
  "bin": {
@@ -17,6 +17,7 @@
17
17
  },
18
18
  "scripts": {
19
19
  "build": "pnpm exec esbuild src/bin.ts --bundle --platform=node --format=esm --target=node26 --outfile=dist/uap-device-control.mjs --banner:js=\"#!/usr/bin/env node\"",
20
- "prepack": "pnpm run build"
20
+ "prepack": "pnpm run build",
21
+ "publish:public": "node scripts/publish.mjs"
21
22
  }
22
23
  }