@codingfrees/uap-device-control 0.2.4 → 0.2.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/dist/uap-device-control.mjs +326 -176
- package/package.json +1 -1
|
@@ -341,8 +341,8 @@ async function callbackServer(timeoutMs) {
|
|
|
341
341
|
let settle;
|
|
342
342
|
let reject;
|
|
343
343
|
const result = new Promise((resolve, rejectResult) => (settle = resolve, reject = rejectResult));
|
|
344
|
-
const server = createServer((
|
|
345
|
-
const url = new URL(
|
|
344
|
+
const server = createServer((request, response) => {
|
|
345
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
346
346
|
if (url.pathname !== "/callback") {
|
|
347
347
|
response.writeHead(404).end();
|
|
348
348
|
return;
|
|
@@ -426,34 +426,60 @@ import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from
|
|
|
426
426
|
import { createServer as createServer2 } from "node:http";
|
|
427
427
|
import path2 from "node:path";
|
|
428
428
|
var BROWSER_CONTROL_CAPABILITIES = ["browser.tabs", "browser.navigate", "browser.snapshot", "browser.click", "browser.type", "browser.scroll"];
|
|
429
|
-
var
|
|
429
|
+
var EXTENSION_ORIGIN = /^(?:chrome-extension:\/\/[a-p]{32}|moz-extension:\/\/[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|safari-web-extension:\/\/[A-Za-z0-9._-]{8,128})$/;
|
|
430
|
+
var MAX_BROWSERS = 8;
|
|
431
|
+
var MAX_TAB_MAPPINGS = 1024;
|
|
430
432
|
async function resetBrowserBridgePairing(stateDirectory) {
|
|
431
433
|
await mkdir2(stateDirectory, { recursive: true, mode: 448 });
|
|
432
|
-
await writeFile2(path2.join(stateDirectory, "browser-bridge.json"), JSON.stringify({ version:
|
|
434
|
+
await writeFile2(path2.join(stateDirectory, "browser-bridge.json"), JSON.stringify({ version: 2, pairings: [] }) + "\n", { mode: 384 });
|
|
433
435
|
}
|
|
434
436
|
async function createBrowserBridge(stateDirectory, requestedPort = 18700, log) {
|
|
435
437
|
if (!Number.isInteger(requestedPort) || requestedPort !== 0 && (requestedPort < 1024 || requestedPort > 65535)) throw new TypeError("browser bridge port is invalid");
|
|
436
438
|
await mkdir2(stateDirectory, { recursive: true, mode: 448 });
|
|
437
439
|
const statePath = path2.join(stateDirectory, "browser-bridge.json");
|
|
438
|
-
let
|
|
439
|
-
let pairingCode =
|
|
440
|
-
let pairingExpiresAt =
|
|
441
|
-
let
|
|
442
|
-
|
|
443
|
-
let waiter;
|
|
444
|
-
const queue = [];
|
|
440
|
+
let pairings = await loadPairings(statePath);
|
|
441
|
+
let pairingCode = createPairingCode();
|
|
442
|
+
let pairingExpiresAt = Date.now() + 10 * 6e4;
|
|
443
|
+
let browserSequence = Math.max(0, ...pairings.map((p) => Number(p.browserId.slice(1)) || 0));
|
|
444
|
+
const clients = /* @__PURE__ */ new Map();
|
|
445
445
|
const pending = /* @__PURE__ */ new Map();
|
|
446
|
-
const
|
|
446
|
+
const tabs = /* @__PURE__ */ new Map();
|
|
447
|
+
const tabIds = /* @__PURE__ */ new Map();
|
|
448
|
+
let nextTabId = 1;
|
|
449
|
+
const clientFor = (browserId) => {
|
|
450
|
+
let client = clients.get(browserId);
|
|
451
|
+
if (!client) clients.set(browserId, client = { lastSeen: 0, permissionsGranted: false, queue: [] });
|
|
452
|
+
return client;
|
|
453
|
+
};
|
|
454
|
+
const online = (pairing2) => {
|
|
455
|
+
const client = clients.get(pairing2.browserId);
|
|
456
|
+
return Boolean(client?.permissionsGranted && Date.now() - client.lastSeen < 45e3);
|
|
457
|
+
};
|
|
458
|
+
const revokeClient = (browserId) => {
|
|
459
|
+
const client = clients.get(browserId);
|
|
460
|
+
if (client?.waiter) client.waiter(null);
|
|
461
|
+
clients.delete(browserId);
|
|
462
|
+
for (const [id, record] of pending) {
|
|
463
|
+
if (record.browserId !== browserId) continue;
|
|
464
|
+
clearTimeout(record.timer);
|
|
465
|
+
pending.delete(id);
|
|
466
|
+
record.reject(new TypeError("browser bridge was unpaired"));
|
|
467
|
+
}
|
|
468
|
+
for (const [id, tab] of tabs) if (tab.browserId === browserId) {
|
|
469
|
+
tabs.delete(id);
|
|
470
|
+
tabIds.delete(browserId + ":" + tab.nativeId);
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
const server = createServer2(async (request, response) => {
|
|
447
474
|
try {
|
|
448
|
-
const origin =
|
|
449
|
-
if (
|
|
450
|
-
const url = new URL(
|
|
475
|
+
const origin = request.headers.origin ?? "";
|
|
476
|
+
if (request.method === "OPTIONS") return cors(response, origin, 204);
|
|
477
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
451
478
|
if (!url.pathname.startsWith("/browser/")) return send(response, 404, { error: "not_found" }, origin);
|
|
452
|
-
if (url.pathname === "/browser/pair" &&
|
|
453
|
-
const body = await jsonBody(
|
|
454
|
-
|
|
455
|
-
if (
|
|
456
|
-
if (pairing2) throw new TypeError("browser bridge is already paired");
|
|
479
|
+
if (url.pathname === "/browser/pair" && request.method === "POST") {
|
|
480
|
+
const body = await jsonBody(request);
|
|
481
|
+
extensionIdValue(body.extensionId, origin);
|
|
482
|
+
if (pairings.length >= MAX_BROWSERS) throw new TypeError("maximum paired browsers reached");
|
|
457
483
|
const candidate = pairingCodeValue(body.pairingCode);
|
|
458
484
|
if (!pairingCode || Date.now() > pairingExpiresAt) {
|
|
459
485
|
pairingCode = createPairingCode();
|
|
@@ -463,43 +489,50 @@ async function createBrowserBridge(stateDirectory, requestedPort = 18700, log) {
|
|
|
463
489
|
}
|
|
464
490
|
if (!secureEqual(candidate, pairingCode)) throw new TypeError("browser pairing code is invalid");
|
|
465
491
|
const token = randomBytes2(32).toString("base64url");
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
await
|
|
470
|
-
log?.({ event: "browser.bridge", status: "paired" });
|
|
471
|
-
return send(response, 200, { token, port: actualPort(server) }, origin);
|
|
472
|
-
}
|
|
473
|
-
const current = authorize(request2, origin, pairing2);
|
|
474
|
-
if (url.pathname === "/browser/status" && request2.method === "POST") {
|
|
475
|
-
const wasOffline = Date.now() - lastSeen >= 45e3;
|
|
476
|
-
lastSeen = Date.now();
|
|
477
|
-
if (wasOffline) log?.({ event: "browser.bridge", status: "connected" });
|
|
478
|
-
return send(response, 200, { paired: true, online: true, permissionsGranted }, current.origin);
|
|
479
|
-
}
|
|
480
|
-
if (url.pathname === "/browser/unpair" && request2.method === "POST") {
|
|
481
|
-
pairing2 = void 0;
|
|
492
|
+
const browser = browserName(body.browser, origin);
|
|
493
|
+
const pairing2 = { browserId: "b" + ++browserSequence, origin, tokenHash: digest(token), browser };
|
|
494
|
+
pairings = [...pairings, pairing2];
|
|
495
|
+
await persistPairings(statePath, pairings);
|
|
482
496
|
pairingCode = createPairingCode();
|
|
483
497
|
pairingExpiresAt = Date.now() + 10 * 6e4;
|
|
484
|
-
|
|
485
|
-
permissionsGranted = false;
|
|
486
|
-
await writeFile2(statePath, JSON.stringify({ version: 1 }) + "\n", { mode: 384 });
|
|
487
|
-
rejectAll(pending, "browser bridge was unpaired");
|
|
488
|
-
log?.({ event: "browser.bridge", status: "unpaired" });
|
|
498
|
+
log?.({ event: "browser.bridge", status: "paired", browserId: pairing2.browserId, browser });
|
|
489
499
|
log?.({ event: "browser.bridge", status: "pairing-required", port: actualPort(server), pairingCode });
|
|
490
|
-
return send(response, 200, {
|
|
500
|
+
return send(response, 200, { token, port: actualPort(server), browserId: pairing2.browserId }, origin);
|
|
501
|
+
}
|
|
502
|
+
const current = authorize(request, origin, pairings);
|
|
503
|
+
const client = clientFor(current.browserId);
|
|
504
|
+
if (url.pathname === "/browser/status" && request.method === "POST") {
|
|
505
|
+
const wasOffline = Date.now() - client.lastSeen >= 45e3;
|
|
506
|
+
client.lastSeen = Date.now();
|
|
507
|
+
if (wasOffline) log?.({ event: "browser.bridge", status: "connected", browserId: current.browserId });
|
|
508
|
+
return send(response, 200, { paired: true, online: true, permissionsGranted: client.permissionsGranted, browserId: current.browserId }, origin);
|
|
491
509
|
}
|
|
492
|
-
if (url.pathname === "/browser/
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
const
|
|
510
|
+
if (url.pathname === "/browser/unpair" && request.method === "POST") {
|
|
511
|
+
pairings = pairings.filter((p) => p.browserId !== current.browserId);
|
|
512
|
+
await persistPairings(statePath, pairings);
|
|
513
|
+
revokeClient(current.browserId);
|
|
514
|
+
log?.({ event: "browser.bridge", status: "unpaired", browserId: current.browserId });
|
|
515
|
+
return send(response, 200, { unpaired: true }, origin);
|
|
516
|
+
}
|
|
517
|
+
if (url.pathname === "/browser/poll" && request.method === "POST") {
|
|
518
|
+
const body = await jsonBody(request);
|
|
519
|
+
const wasOffline = Date.now() - client.lastSeen >= 45e3;
|
|
520
|
+
const previousPermissions = client.permissionsGranted;
|
|
521
|
+
client.permissionsGranted = body.permissionsGranted === true;
|
|
522
|
+
client.lastSeen = Date.now();
|
|
523
|
+
if (wasOffline) log?.({ event: "browser.bridge", status: "connected", browserId: current.browserId });
|
|
524
|
+
if (previousPermissions !== client.permissionsGranted)
|
|
525
|
+
log?.({ event: "browser.bridge", status: client.permissionsGranted ? "permissions-granted" : "permissions-required", browserId: current.browserId });
|
|
526
|
+
if (!client.permissionsGranted) {
|
|
527
|
+
for (const [id, value] of pending) if (value.browserId === current.browserId) {
|
|
528
|
+
clearTimeout(value.timer);
|
|
529
|
+
pending.delete(id);
|
|
530
|
+
value.reject(new TypeError("browser permission was revoked"));
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
const command = client.permissionsGranted ? client.queue.shift() ?? await new Promise((resolve) => {
|
|
501
534
|
const timer = setTimeout(() => {
|
|
502
|
-
if (waiter === done) waiter = void 0;
|
|
535
|
+
if (client.waiter === done) client.waiter = void 0;
|
|
503
536
|
resolve(null);
|
|
504
537
|
}, 2e4);
|
|
505
538
|
timer.unref();
|
|
@@ -507,31 +540,62 @@ async function createBrowserBridge(stateDirectory, requestedPort = 18700, log) {
|
|
|
507
540
|
clearTimeout(timer);
|
|
508
541
|
resolve(value);
|
|
509
542
|
};
|
|
510
|
-
waiter = done;
|
|
511
|
-
});
|
|
512
|
-
return send(response, 200, { command },
|
|
543
|
+
client.waiter = done;
|
|
544
|
+
}) : null;
|
|
545
|
+
return send(response, 200, { command }, origin);
|
|
513
546
|
}
|
|
514
|
-
if (url.pathname === "/browser/result" &&
|
|
515
|
-
lastSeen = Date.now();
|
|
516
|
-
const body = await jsonBody(
|
|
547
|
+
if (url.pathname === "/browser/result" && request.method === "POST") {
|
|
548
|
+
client.lastSeen = Date.now();
|
|
549
|
+
const body = await jsonBody(request);
|
|
517
550
|
const requestId = identifier(body.requestId, "requestId");
|
|
518
551
|
const completion = pending.get(requestId);
|
|
519
|
-
if (!completion) return send(response, 409, { error: "request_not_pending" },
|
|
552
|
+
if (!completion || completion.browserId !== current.browserId) return send(response, 409, { error: "request_not_pending" }, origin);
|
|
520
553
|
pending.delete(requestId);
|
|
521
554
|
clearTimeout(completion.timer);
|
|
522
555
|
if (body.ok === true) completion.resolve(jsonValue(body.output));
|
|
523
556
|
else completion.reject(new TypeError(typeof body.error === "string" ? body.error.slice(0, 256) : "browser operation failed"));
|
|
524
|
-
return send(response, 200, { accepted: true },
|
|
557
|
+
return send(response, 200, { accepted: true }, origin);
|
|
525
558
|
}
|
|
526
|
-
return send(response, 404, { error: "not_found" },
|
|
559
|
+
return send(response, 404, { error: "not_found" }, origin);
|
|
527
560
|
} catch (error) {
|
|
528
|
-
return send(response, 400, { error: error instanceof Error ? error.message.slice(0, 256) : "browser bridge failed" },
|
|
561
|
+
return send(response, 400, { error: error instanceof Error ? error.message.slice(0, 256) : "browser bridge failed" }, request.headers.origin ?? "");
|
|
529
562
|
}
|
|
530
563
|
});
|
|
531
564
|
await new Promise((resolve, reject) => {
|
|
532
565
|
server.once("error", reject);
|
|
533
566
|
server.listen(requestedPort, "127.0.0.1", () => resolve());
|
|
534
567
|
});
|
|
568
|
+
const dispatch = (pairing2, capability, parameters) => {
|
|
569
|
+
if (!online(pairing2)) return Promise.reject(new TypeError("selected browser is offline or missing permissions"));
|
|
570
|
+
const client = clientFor(pairing2.browserId);
|
|
571
|
+
const requestId = randomUUID2();
|
|
572
|
+
const command = { requestId, capability, parameters };
|
|
573
|
+
const completion = new Promise((resolve, reject) => {
|
|
574
|
+
const timer = setTimeout(() => {
|
|
575
|
+
pending.delete(requestId);
|
|
576
|
+
reject(new TypeError("browser operation timed out"));
|
|
577
|
+
}, 45e3);
|
|
578
|
+
timer.unref();
|
|
579
|
+
pending.set(requestId, { browserId: pairing2.browserId, resolve, reject, timer });
|
|
580
|
+
});
|
|
581
|
+
if (client.waiter) {
|
|
582
|
+
const deliver = client.waiter;
|
|
583
|
+
client.waiter = void 0;
|
|
584
|
+
deliver(command);
|
|
585
|
+
} else client.queue.push(command);
|
|
586
|
+
return completion;
|
|
587
|
+
};
|
|
588
|
+
const virtualTabId = (pairing2, nativeId) => {
|
|
589
|
+
const key = pairing2.browserId + ":" + nativeId;
|
|
590
|
+
let id = tabIds.get(key);
|
|
591
|
+
if (!id) {
|
|
592
|
+
id = nextTabId++;
|
|
593
|
+
if (id > 2147483647) throw new TypeError("browser tab identifiers exhausted");
|
|
594
|
+
tabIds.set(key, id);
|
|
595
|
+
tabs.set(id, { browserId: pairing2.browserId, nativeId });
|
|
596
|
+
}
|
|
597
|
+
return id;
|
|
598
|
+
};
|
|
535
599
|
return {
|
|
536
600
|
get port() {
|
|
537
601
|
return actualPort(server);
|
|
@@ -540,44 +604,82 @@ async function createBrowserBridge(stateDirectory, requestedPort = 18700, log) {
|
|
|
540
604
|
get pairingCode() {
|
|
541
605
|
return pairingCode;
|
|
542
606
|
},
|
|
607
|
+
get pairingCount() {
|
|
608
|
+
return pairings.length;
|
|
609
|
+
},
|
|
543
610
|
available() {
|
|
544
|
-
return
|
|
611
|
+
return pairings.some(online);
|
|
545
612
|
},
|
|
546
|
-
execute(capability, parameters) {
|
|
613
|
+
async execute(capability, parameters) {
|
|
547
614
|
if (!BROWSER_CONTROL_CAPABILITIES.includes(capability)) throw new TypeError("browser capability is unavailable");
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
const
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
615
|
+
const connected = pairings.filter(online);
|
|
616
|
+
if (!connected.length) throw new TypeError("browser control extensions are offline or missing permissions");
|
|
617
|
+
if (capability === "browser.tabs") {
|
|
618
|
+
const all = [];
|
|
619
|
+
const inventories = await Promise.all(connected.map((pairing3) => dispatch(pairing3, capability, {})));
|
|
620
|
+
for (const [index, value] of inventories.entries()) {
|
|
621
|
+
const pairing3 = connected[index];
|
|
622
|
+
for (const item of value.tabs ?? []) {
|
|
623
|
+
const nativeId2 = item.tabId;
|
|
624
|
+
if (!Number.isSafeInteger(nativeId2) || Number(nativeId2) < 0) continue;
|
|
625
|
+
all.push({ ...item, tabId: virtualTabId(pairing3, Number(nativeId2)), browserId: pairing3.browserId, browser: pairing3.browser });
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
if (tabs.size > MAX_TAB_MAPPINGS) {
|
|
629
|
+
for (const id of [...tabs.keys()].slice(0, tabs.size - MAX_TAB_MAPPINGS)) {
|
|
630
|
+
const old = tabs.get(id);
|
|
631
|
+
tabIds.delete(old.browserId + ":" + old.nativeId);
|
|
632
|
+
tabs.delete(id);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
return { tabs: all.slice(0, 100) };
|
|
636
|
+
}
|
|
637
|
+
let pairing2;
|
|
638
|
+
let input = parameters;
|
|
639
|
+
if (parameters.tabId !== void 0) {
|
|
640
|
+
const tab = tabs.get(Number(parameters.tabId));
|
|
641
|
+
if (tab) {
|
|
642
|
+
pairing2 = connected.find((p) => p.browserId === tab.browserId);
|
|
643
|
+
if (!pairing2) throw new TypeError("selected browser is offline");
|
|
644
|
+
input = { ...parameters, tabId: tab.nativeId };
|
|
645
|
+
} else if (connected.length === 1 && Number.isSafeInteger(parameters.tabId)) {
|
|
646
|
+
pairing2 = connected[0];
|
|
647
|
+
} else throw new TypeError("browser tab identifier is unavailable; list browser tabs first");
|
|
648
|
+
} else {
|
|
649
|
+
pairing2 = typeof parameters.browserId === "string" ? connected.find((p) => p.browserId === parameters.browserId) : connected.length === 1 ? connected[0] : void 0;
|
|
650
|
+
if (!pairing2) throw new TypeError("select a browserId returned by list_browser_tabs");
|
|
651
|
+
}
|
|
652
|
+
const { browserId: _browserId, ...scoped } = input;
|
|
653
|
+
const result = await dispatch(pairing2, capability, scoped);
|
|
654
|
+
if (capability !== "browser.navigate" || !result || typeof result !== "object" || Array.isArray(result)) return result;
|
|
655
|
+
const output = result;
|
|
656
|
+
if (!Number.isSafeInteger(output.tabId) || Number(output.tabId) < 0) return result;
|
|
657
|
+
const nativeId = Number(output.tabId);
|
|
658
|
+
const tabId = virtualTabId(pairing2, nativeId);
|
|
659
|
+
if (parameters.operation === "close") {
|
|
660
|
+
tabs.delete(tabId);
|
|
661
|
+
tabIds.delete(pairing2.browserId + ":" + nativeId);
|
|
662
|
+
}
|
|
663
|
+
return { ...output, tabId, browserId: pairing2.browserId, browser: pairing2.browser };
|
|
565
664
|
},
|
|
566
665
|
async close() {
|
|
567
666
|
rejectAll(pending, "browser bridge closed");
|
|
568
|
-
|
|
667
|
+
for (const client of clients.values()) client.waiter?.(null);
|
|
569
668
|
await new Promise((resolve) => server.close(() => resolve()));
|
|
570
669
|
}
|
|
571
670
|
};
|
|
572
671
|
}
|
|
573
|
-
function authorize(
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
if (!auth?.startsWith("Bearer ")
|
|
577
|
-
|
|
672
|
+
function authorize(request, origin, pairings) {
|
|
673
|
+
const auth = request.headers.authorization;
|
|
674
|
+
if (!EXTENSION_ORIGIN.test(origin)) throw new TypeError("browser bridge is not paired");
|
|
675
|
+
if (!auth?.startsWith("Bearer ")) throw new TypeError("browser bridge authorization failed");
|
|
676
|
+
const tokenHash = digest(auth.slice(7));
|
|
677
|
+
const pairing2 = pairings.find((p) => p.origin === origin && secureHashEqual(tokenHash, p.tokenHash));
|
|
678
|
+
if (!pairing2) throw new TypeError("browser bridge authorization failed");
|
|
679
|
+
return pairing2;
|
|
578
680
|
}
|
|
579
681
|
function cors(response, origin, status) {
|
|
580
|
-
if (
|
|
682
|
+
if (EXTENSION_ORIGIN.test(origin)) {
|
|
581
683
|
response.setHeader("access-control-allow-origin", origin);
|
|
582
684
|
response.setHeader("access-control-allow-headers", "authorization,content-type");
|
|
583
685
|
response.setHeader("access-control-allow-methods", "POST,OPTIONS");
|
|
@@ -587,7 +689,7 @@ function cors(response, origin, status) {
|
|
|
587
689
|
response.end();
|
|
588
690
|
}
|
|
589
691
|
function send(response, status, body, origin) {
|
|
590
|
-
if (
|
|
692
|
+
if (EXTENSION_ORIGIN.test(origin)) {
|
|
591
693
|
response.setHeader("access-control-allow-origin", origin);
|
|
592
694
|
response.setHeader("vary", "Origin");
|
|
593
695
|
}
|
|
@@ -596,10 +698,10 @@ function send(response, status, body, origin) {
|
|
|
596
698
|
response.setHeader("cache-control", "no-store");
|
|
597
699
|
response.end(JSON.stringify(body));
|
|
598
700
|
}
|
|
599
|
-
async function jsonBody(
|
|
701
|
+
async function jsonBody(request) {
|
|
600
702
|
const chunks = [];
|
|
601
703
|
let size = 0;
|
|
602
|
-
for await (const chunk of
|
|
704
|
+
for await (const chunk of request) {
|
|
603
705
|
size += Buffer.byteLength(chunk);
|
|
604
706
|
if (size > 1024 * 1024) throw new TypeError("browser bridge request is too large");
|
|
605
707
|
chunks.push(Buffer.from(chunk));
|
|
@@ -608,19 +710,24 @@ async function jsonBody(request2) {
|
|
|
608
710
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("browser bridge request is invalid");
|
|
609
711
|
return parsed;
|
|
610
712
|
}
|
|
611
|
-
async function
|
|
713
|
+
async function loadPairings(file) {
|
|
612
714
|
try {
|
|
613
715
|
const parsed = JSON.parse(await readFile2(file, "utf8"));
|
|
614
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return
|
|
716
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [];
|
|
615
717
|
const record = parsed;
|
|
616
|
-
if (record.version
|
|
617
|
-
|
|
718
|
+
if (record.version === 1 && typeof record.extensionId === "string" && /^[a-f0-9]{64}$/.test(String(record.tokenHash))) {
|
|
719
|
+
const origin = "chrome-extension://" + record.extensionId;
|
|
720
|
+
return EXTENSION_ORIGIN.test(origin) ? [{ browserId: "b1", origin, tokenHash: String(record.tokenHash), browser: "Chrome/Chromium" }] : [];
|
|
721
|
+
}
|
|
722
|
+
if (record.version !== 2 || !Array.isArray(record.pairings) || record.pairings.length > MAX_BROWSERS) return [];
|
|
723
|
+
const pairings = record.pairings;
|
|
724
|
+
return pairings.every((p) => typeof p.browserId === "string" && /^b[1-9][0-9]*$/.test(p.browserId) && EXTENSION_ORIGIN.test(p.origin) && /^[a-f0-9]{64}$/.test(p.tokenHash) && typeof p.browser === "string" && p.browser.length <= 32) && new Set(pairings.map((p) => p.tokenHash)).size === pairings.length && new Set(pairings.map((p) => p.browserId)).size === pairings.length ? pairings : [];
|
|
618
725
|
} catch {
|
|
619
|
-
return
|
|
726
|
+
return [];
|
|
620
727
|
}
|
|
621
728
|
}
|
|
622
|
-
async function
|
|
623
|
-
await writeFile2(file, JSON.stringify({ version:
|
|
729
|
+
async function persistPairings(file, pairings) {
|
|
730
|
+
await writeFile2(file, JSON.stringify({ version: 2, pairings }) + "\n", { mode: 384 });
|
|
624
731
|
}
|
|
625
732
|
function rejectAll(pending, message) {
|
|
626
733
|
for (const value of pending.values()) {
|
|
@@ -632,9 +739,17 @@ function rejectAll(pending, message) {
|
|
|
632
739
|
function digest(value) {
|
|
633
740
|
return createHash("sha256").update(value).digest("hex");
|
|
634
741
|
}
|
|
635
|
-
function
|
|
636
|
-
|
|
637
|
-
return
|
|
742
|
+
function secureHashEqual(left, right) {
|
|
743
|
+
const a = Buffer.from(left, "hex"), b = Buffer.from(right, "hex");
|
|
744
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
745
|
+
}
|
|
746
|
+
function browserName(value, origin) {
|
|
747
|
+
if (origin.startsWith("moz-extension:")) return "Firefox";
|
|
748
|
+
if (origin.startsWith("safari-web-extension:")) return "Safari";
|
|
749
|
+
return ["Chrome", "Edge", "Opera"].includes(String(value)) ? String(value) : "Chrome/Chromium";
|
|
750
|
+
}
|
|
751
|
+
function extensionIdValue(value, origin) {
|
|
752
|
+
if (!EXTENSION_ORIGIN.test(origin) || value !== new URL(origin).host) throw new TypeError("browser extension origin is invalid");
|
|
638
753
|
}
|
|
639
754
|
function identifier(value, label) {
|
|
640
755
|
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(value)) throw new TypeError(label + " is invalid");
|
|
@@ -657,9 +772,7 @@ function pairingCodeValue(value) {
|
|
|
657
772
|
return value;
|
|
658
773
|
}
|
|
659
774
|
function secureEqual(left, right) {
|
|
660
|
-
|
|
661
|
-
const b = Buffer.from(digest(right), "hex");
|
|
662
|
-
return a.length === b.length && timingSafeEqual(a, b);
|
|
775
|
+
return secureHashEqual(digest(left), digest(right));
|
|
663
776
|
}
|
|
664
777
|
|
|
665
778
|
// src/remote.ts
|
|
@@ -670,7 +783,7 @@ import WebSocket from "ws";
|
|
|
670
783
|
// package.json
|
|
671
784
|
var package_default = {
|
|
672
785
|
name: "@codingfrees/uap-device-control",
|
|
673
|
-
version: "0.2.
|
|
786
|
+
version: "0.2.5",
|
|
674
787
|
description: "Cross-platform outbound UAP Device Control client",
|
|
675
788
|
type: "module",
|
|
676
789
|
bin: {
|
|
@@ -778,12 +891,16 @@ var DeviceAgentEngine = class {
|
|
|
778
891
|
get capabilities() {
|
|
779
892
|
return [...this.#baseCapabilities, ...[...this.#capabilityAdapters].filter(([, adapter]) => adapter.available?.() !== false).map(([capability]) => capability)];
|
|
780
893
|
}
|
|
894
|
+
localActivity() {
|
|
895
|
+
return { screenSessions: this.#screenSessions.size, terminalSessions: this.#sessions.size };
|
|
896
|
+
}
|
|
781
897
|
info() {
|
|
898
|
+
const p = os2.platform();
|
|
782
899
|
return {
|
|
783
900
|
deviceId: this.options.deviceId,
|
|
784
901
|
name: this.options.name ?? os2.hostname(),
|
|
785
902
|
status: "online",
|
|
786
|
-
os:
|
|
903
|
+
os: p === "win32" ? "Windows" : p === "darwin" ? "macOS" : p === "linux" ? "Linux" : p,
|
|
787
904
|
architecture: os2.arch(),
|
|
788
905
|
agentVersion: this.options.agentVersion ?? "0.1.0",
|
|
789
906
|
lastSeen: Date.now(),
|
|
@@ -798,18 +915,16 @@ var DeviceAgentEngine = class {
|
|
|
798
915
|
}
|
|
799
916
|
panicStop() {
|
|
800
917
|
const activity = { processes: this.#processes.size, oneShotCommands: this.#oneShots.size, terminalSessions: this.#sessions.size, screenSessions: this.#screenSessions.size };
|
|
801
|
-
|
|
802
|
-
if (
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
}
|
|
918
|
+
const kill = (v) => {
|
|
919
|
+
if (v.exitCode === null) v.child.kill("SIGKILL");
|
|
920
|
+
v.child.stdin.destroy();
|
|
921
|
+
v.child.stdout.destroy();
|
|
922
|
+
v.child.stderr.destroy();
|
|
923
|
+
};
|
|
924
|
+
for (const value of [...this.#processes.values(), ...this.#oneShots.values()]) kill(value);
|
|
807
925
|
for (const value of this.#sessions.values()) {
|
|
808
926
|
if (value.idleTimer) clearTimeout(value.idleTimer);
|
|
809
|
-
|
|
810
|
-
value.child.stdin.destroy();
|
|
811
|
-
value.child.stdout.destroy();
|
|
812
|
-
value.child.stderr.destroy();
|
|
927
|
+
kill(value);
|
|
813
928
|
}
|
|
814
929
|
this.#processes.clear();
|
|
815
930
|
this.#oneShots.clear();
|
|
@@ -1047,8 +1162,8 @@ var DeviceAgentEngine = class {
|
|
|
1047
1162
|
return { closed: true };
|
|
1048
1163
|
}
|
|
1049
1164
|
if (operation === "input") {
|
|
1050
|
-
this.#touchTerminalSession(value);
|
|
1051
1165
|
const data = text2(input.data, 65536, "terminal input");
|
|
1166
|
+
this.#touchTerminalSession(value);
|
|
1052
1167
|
value.child.stdin.write(data);
|
|
1053
1168
|
return { accepted: true, expiresAt: value.expiresAt };
|
|
1054
1169
|
}
|
|
@@ -1061,8 +1176,9 @@ var DeviceAgentEngine = class {
|
|
|
1061
1176
|
return sessionSummary(value);
|
|
1062
1177
|
}
|
|
1063
1178
|
if (operation === "resume") {
|
|
1179
|
+
const resume = terminalResumeSummary(value, input);
|
|
1064
1180
|
this.#touchTerminalSession(value);
|
|
1065
|
-
return
|
|
1181
|
+
return { ...resume, lastActivityAt: value.lastActivityAt, expiresAt: value.expiresAt };
|
|
1066
1182
|
}
|
|
1067
1183
|
throw new TypeError("terminal operation is invalid");
|
|
1068
1184
|
}
|
|
@@ -1110,13 +1226,15 @@ var DeviceAgentEngine = class {
|
|
|
1110
1226
|
return { closed: true };
|
|
1111
1227
|
}
|
|
1112
1228
|
if (operation === "frame") {
|
|
1229
|
+
const frame = await this.options.captureScreen(session.monitorId, { format: session.format, quality: session.quality });
|
|
1230
|
+
if (this.#screenSessions.get(sessionId) !== session) throw new TypeError("screen session is unavailable");
|
|
1113
1231
|
this.#touchScreenSession(sessionId, session);
|
|
1114
|
-
return { sessionId, frame
|
|
1232
|
+
return { sessionId, frame, capturedAt: Date.now(), expiresAt: session.expiresAt };
|
|
1115
1233
|
}
|
|
1116
1234
|
if (operation === "feedback") {
|
|
1117
|
-
this.#touchScreenSession(sessionId, session);
|
|
1118
1235
|
const observedLatencyMs = bounded(Number(input.observedLatencyMs), 0, 6e4, "observed screen latency");
|
|
1119
1236
|
const droppedFrames = bounded(Number(input.droppedFrames ?? 0), 0, 1e4, "dropped screen frames");
|
|
1237
|
+
this.#touchScreenSession(sessionId, session);
|
|
1120
1238
|
const degraded = droppedFrames > 0 || observedLatencyMs > session.intervalMs * 1.5;
|
|
1121
1239
|
session.intervalMs = degraded ? Math.min(5e3, session.intervalMs + 100) : Math.max(session.requestedIntervalMs, session.intervalMs - 50);
|
|
1122
1240
|
if (session.requestedFormat === "auto") {
|
|
@@ -1826,7 +1944,7 @@ async function runRemote(options) {
|
|
|
1826
1944
|
return void 0;
|
|
1827
1945
|
});
|
|
1828
1946
|
if (browser) {
|
|
1829
|
-
options.log?.({ event: "browser.bridge", status: "ready", port: browser.port, pairingStored:
|
|
1947
|
+
options.log?.({ event: "browser.bridge", status: "ready", port: browser.port, pairingStored: browser.pairingCount > 0 });
|
|
1830
1948
|
if (browser.pairingCode) options.log?.({ event: "browser.bridge", status: "pairing-required", port: browser.port, pairingCode: browser.pairingCode });
|
|
1831
1949
|
}
|
|
1832
1950
|
const engine = new DeviceAgentEngine({
|
|
@@ -1864,7 +1982,8 @@ async function runRemote(options) {
|
|
|
1864
1982
|
deviceId,
|
|
1865
1983
|
retryMs: delay,
|
|
1866
1984
|
...httpStatus === void 0 ? {} : { httpStatus },
|
|
1867
|
-
...error.pathname === void 0 ? {} : { pathname: error.pathname }
|
|
1985
|
+
...error.pathname === void 0 ? {} : { pathname: error.pathname },
|
|
1986
|
+
...error.reason === void 0 ? {} : { reason: error.reason }
|
|
1868
1987
|
});
|
|
1869
1988
|
await sleep2(delay, options.signal);
|
|
1870
1989
|
delay = Math.min(delay * 2, 15e3);
|
|
@@ -1886,10 +2005,15 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
|
|
|
1886
2005
|
const deviceId = engine.options.deviceId;
|
|
1887
2006
|
const socket = await authorizedSocket(origin, stateDirectory, fetcher, socketFactory, signal, log, deviceId);
|
|
1888
2007
|
const inFlight = /* @__PURE__ */ new Set();
|
|
2008
|
+
const queued = [];
|
|
2009
|
+
const drainWaiters = /* @__PURE__ */ new Set();
|
|
1889
2010
|
const dispatched = /* @__PURE__ */ new Set();
|
|
1890
2011
|
const acknowledgements = /* @__PURE__ */ new Map();
|
|
1891
2012
|
let browserExecution = Promise.resolve(void 0);
|
|
1892
2013
|
let resultFailure;
|
|
2014
|
+
const sessionStartedAt = Date.now();
|
|
2015
|
+
let closeCode;
|
|
2016
|
+
let closeCause;
|
|
1893
2017
|
const execute4 = (command, workspaceId) => {
|
|
1894
2018
|
if (!command.capability.startsWith("browser.")) return engine.execute(command.capability, command.parameters, { workspaceId });
|
|
1895
2019
|
const current = browserExecution.then(() => engine.execute(command.capability, command.parameters, { workspaceId }));
|
|
@@ -1907,6 +2031,29 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
|
|
|
1907
2031
|
}
|
|
1908
2032
|
await sendResult(socket, acknowledgements, { type: "result", requestId: command.requestId, ...outcome, executionMs: elapsed(startedAt) });
|
|
1909
2033
|
};
|
|
2034
|
+
const resolveDrain = () => {
|
|
2035
|
+
if (queued.length || inFlight.size) return;
|
|
2036
|
+
for (const resolve of drainWaiters) resolve();
|
|
2037
|
+
drainWaiters.clear();
|
|
2038
|
+
};
|
|
2039
|
+
const dispatch = () => {
|
|
2040
|
+
while (inFlight.size < 4 && queued.length) {
|
|
2041
|
+
const { command, workspaceId } = queued.shift();
|
|
2042
|
+
const job = complete(command, workspaceId).catch((error) => {
|
|
2043
|
+
if (signal?.aborted) return;
|
|
2044
|
+
resultFailure ??= error;
|
|
2045
|
+
closeCause = "result-delivery";
|
|
2046
|
+
socket.close(1011, "command result failed");
|
|
2047
|
+
});
|
|
2048
|
+
inFlight.add(job);
|
|
2049
|
+
void job.finally(() => {
|
|
2050
|
+
inFlight.delete(job);
|
|
2051
|
+
dispatch();
|
|
2052
|
+
resolveDrain();
|
|
2053
|
+
});
|
|
2054
|
+
}
|
|
2055
|
+
};
|
|
2056
|
+
const drain = () => queued.length || inFlight.size ? new Promise((resolve) => drainWaiters.add(resolve)) : Promise.resolve();
|
|
1910
2057
|
try {
|
|
1911
2058
|
await new Promise((resolve, reject) => {
|
|
1912
2059
|
let connected = false;
|
|
@@ -1938,27 +2085,30 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
|
|
|
1938
2085
|
return;
|
|
1939
2086
|
}
|
|
1940
2087
|
if (value.type !== "command") throw new TypeError("remote socket message type is invalid");
|
|
1941
|
-
if (inFlight.size >= 4) throw new TypeError("remote socket exceeded command concurrency");
|
|
1942
2088
|
const command = commandValue(value.command);
|
|
1943
2089
|
if (dispatched.has(command.requestId)) return;
|
|
1944
2090
|
dispatched.add(command.requestId);
|
|
1945
2091
|
if (dispatched.size > 2048) dispatched.delete(dispatched.values().next().value);
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
});
|
|
1950
|
-
inFlight.add(job);
|
|
1951
|
-
void job.then(() => inFlight.delete(job));
|
|
2092
|
+
if (queued.length + inFlight.size >= 256) throw new TypeError("remote socket command queue is full");
|
|
2093
|
+
queued.push({ command, workspaceId: bounded2(value.workspaceId, "workspace id") });
|
|
2094
|
+
dispatch();
|
|
1952
2095
|
} catch (error) {
|
|
2096
|
+
closeCause = "protocol-error";
|
|
1953
2097
|
fail(error instanceof Error ? error : new TypeError("remote socket message is invalid"));
|
|
1954
2098
|
socket.close(1002, "invalid message");
|
|
1955
2099
|
}
|
|
1956
2100
|
};
|
|
1957
|
-
const onClose = () => {
|
|
2101
|
+
const onClose = (code) => {
|
|
2102
|
+
if (Number.isInteger(code) && code >= 1e3 && code <= 4999) closeCode = code;
|
|
2103
|
+
closeCause ??= signal?.aborted ? "client-abort" : "socket-closed";
|
|
1958
2104
|
signal?.aborted ? resolve() : fail(resultFailure instanceof Error ? resultFailure : new RemoteUnavailableError(void 0, "/device-control/remote/socket", "transport"));
|
|
1959
2105
|
};
|
|
1960
|
-
const onError = () =>
|
|
2106
|
+
const onError = () => {
|
|
2107
|
+
closeCause = "socket-error";
|
|
2108
|
+
fail(new RemoteUnavailableError(void 0, "/device-control/remote/socket", "transport"));
|
|
2109
|
+
};
|
|
1961
2110
|
const onAbort = () => {
|
|
2111
|
+
closeCause = "client-abort";
|
|
1962
2112
|
socket.close(1e3, "client stopped");
|
|
1963
2113
|
resolve();
|
|
1964
2114
|
};
|
|
@@ -1967,9 +2117,11 @@ async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, si
|
|
|
1967
2117
|
socket.send(JSON.stringify({ type: "hello", device: engine.info() }));
|
|
1968
2118
|
});
|
|
1969
2119
|
} finally {
|
|
1970
|
-
|
|
2120
|
+
for (const pending of acknowledgements.values()) pending.reject(new RemoteUnavailableError(void 0, "/device-control/remote/socket", "transport"));
|
|
2121
|
+
acknowledgements.clear();
|
|
2122
|
+
await drain();
|
|
1971
2123
|
socket.close(1e3, "session ended");
|
|
1972
|
-
log?.({ event: "remote.session", status: "disconnected", deviceId });
|
|
2124
|
+
log?.({ event: "remote.session", status: "disconnected", deviceId, ...closeCode === void 0 ? {} : { closeCode }, ...closeCause ? { closeCause } : {}, uptimeMs: elapsed(sessionStartedAt) });
|
|
1973
2125
|
}
|
|
1974
2126
|
}
|
|
1975
2127
|
function defaultSocketFactory(url, token) {
|
|
@@ -1978,7 +2130,7 @@ function defaultSocketFactory(url, token) {
|
|
|
1978
2130
|
async function authorizedSocket(origin, stateDirectory, fetcher, factory, signal, log, deviceId) {
|
|
1979
2131
|
const open2 = async (refresh = false) => {
|
|
1980
2132
|
const current = await accessToken(stateDirectory, fetcher, refresh);
|
|
1981
|
-
const url = new URL("/device-control/remote/socket",
|
|
2133
|
+
const url = new URL("/device-control/remote/socket", canonicalOrigin(origin));
|
|
1982
2134
|
url.searchParams.set("deviceId", deviceId);
|
|
1983
2135
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
1984
2136
|
return await socketHandshake(factory(url.href, current.token), signal);
|
|
@@ -1994,25 +2146,31 @@ async function authorizedSocket(origin, stateDirectory, fetcher, factory, signal
|
|
|
1994
2146
|
function socketHandshake(socket, signal) {
|
|
1995
2147
|
return new Promise((resolve, reject) => {
|
|
1996
2148
|
const done = (error) => {
|
|
1997
|
-
|
|
2149
|
+
clearTimeout(timer);
|
|
2150
|
+
socket.off("open", opened).off("error", failed).off("close", closed).off("unexpected-response", rejected);
|
|
1998
2151
|
signal?.removeEventListener("abort", aborted);
|
|
1999
2152
|
error ? reject(error) : resolve(socket);
|
|
2000
2153
|
};
|
|
2001
2154
|
const opened = () => done();
|
|
2002
2155
|
const failed = () => done(new RemoteUnavailableError(void 0, "/device-control/remote/socket", "transport"));
|
|
2156
|
+
const closed = failed;
|
|
2003
2157
|
const rejected = (_request, response) => done(
|
|
2004
2158
|
response.statusCode === 401 || response.statusCode === 403 ? new RemoteAuthorizationError(response.statusCode, "/device-control/remote/socket") : new RemoteUnavailableError(response.statusCode, "/device-control/remote/socket")
|
|
2005
2159
|
);
|
|
2006
|
-
const
|
|
2007
|
-
done(new RemoteUnavailableError(void 0, "/device-control/remote/socket",
|
|
2160
|
+
const cancel = (reason) => {
|
|
2161
|
+
done(new RemoteUnavailableError(void 0, "/device-control/remote/socket", reason));
|
|
2008
2162
|
const absorbCloseError = () => {
|
|
2009
2163
|
};
|
|
2010
2164
|
const releaseCloseError = () => socket.off("error", absorbCloseError).off("close", releaseCloseError);
|
|
2011
2165
|
socket.on("error", absorbCloseError).on("close", releaseCloseError);
|
|
2012
2166
|
socket.close(1e3, "client stopped");
|
|
2013
2167
|
};
|
|
2014
|
-
|
|
2168
|
+
const aborted = () => cancel("transport");
|
|
2169
|
+
const timer = setTimeout(() => cancel("timeout"), 1e4);
|
|
2170
|
+
timer.unref();
|
|
2171
|
+
socket.on("open", opened).on("error", failed).on("close", closed).on("unexpected-response", rejected);
|
|
2015
2172
|
signal?.addEventListener("abort", aborted, { once: true });
|
|
2173
|
+
if (signal?.aborted) aborted();
|
|
2016
2174
|
});
|
|
2017
2175
|
}
|
|
2018
2176
|
function sendResult(socket, acknowledgements, value) {
|
|
@@ -2033,48 +2191,38 @@ function socketMessage(value) {
|
|
|
2033
2191
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("remote socket message is invalid");
|
|
2034
2192
|
return parsed;
|
|
2035
2193
|
}
|
|
2036
|
-
async function authorizedRequest(fetcher, origin, stateDirectory, pathname, body
|
|
2037
|
-
const
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
} catch (error) {
|
|
2041
|
-
if (!(error instanceof RemoteAuthorizationError)) throw error;
|
|
2042
|
-
log?.({ event: "remote.session", status: "reauthorizing", ...deviceId ? { deviceId } : {}, httpStatus: error.httpStatus, pathname: error.pathname });
|
|
2043
|
-
const refreshed = await accessToken(stateDirectory, fetcher, true);
|
|
2044
|
-
return request(fetcher, origin, pathname, refreshed.token, body, signal, timeoutMs);
|
|
2045
|
-
}
|
|
2046
|
-
}
|
|
2047
|
-
async function request(fetcher, origin, pathname, token, body, signal, timeoutMs = 15e3) {
|
|
2048
|
-
const controller = new AbortController();
|
|
2049
|
-
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
2050
|
-
const onAbort = () => controller.abort();
|
|
2051
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2052
|
-
try {
|
|
2194
|
+
async function authorizedRequest(fetcher, origin, stateDirectory, pathname, body) {
|
|
2195
|
+
const send2 = async (refresh = false) => {
|
|
2196
|
+
const { token } = await accessToken(stateDirectory, fetcher, refresh);
|
|
2197
|
+
const signal = AbortSignal.timeout(5e3);
|
|
2053
2198
|
let response;
|
|
2054
2199
|
try {
|
|
2055
|
-
response = await fetcher(new URL(pathname,
|
|
2200
|
+
response = await fetcher(new URL(pathname, canonicalOrigin(origin)), {
|
|
2056
2201
|
method: "POST",
|
|
2057
2202
|
headers: { "content-type": "application/json", authorization: "Bearer " + token },
|
|
2058
2203
|
body: JSON.stringify(body),
|
|
2059
2204
|
redirect: "error",
|
|
2060
2205
|
cache: "no-store",
|
|
2061
|
-
signal
|
|
2206
|
+
signal
|
|
2062
2207
|
});
|
|
2063
2208
|
} catch {
|
|
2064
|
-
throw new RemoteUnavailableError(void 0, pathname,
|
|
2209
|
+
throw new RemoteUnavailableError(void 0, pathname, signal.aborted ? "timeout" : "transport");
|
|
2065
2210
|
}
|
|
2066
2211
|
if (response.status === 401 || response.status === 403) throw new RemoteAuthorizationError(response.status, pathname);
|
|
2067
2212
|
if (!response.ok) throw new RemoteUnavailableError(response.status, pathname);
|
|
2068
2213
|
const raw = await response.json();
|
|
2069
2214
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("remote response is invalid");
|
|
2070
2215
|
return raw;
|
|
2071
|
-
}
|
|
2072
|
-
|
|
2073
|
-
|
|
2216
|
+
};
|
|
2217
|
+
try {
|
|
2218
|
+
return await send2();
|
|
2219
|
+
} catch (error) {
|
|
2220
|
+
if (!(error instanceof RemoteAuthorizationError)) throw error;
|
|
2221
|
+
return send2(true);
|
|
2074
2222
|
}
|
|
2075
2223
|
}
|
|
2076
2224
|
async function remoteStatus(origin, stateDirectory, deviceId, fetcher = fetch) {
|
|
2077
|
-
const value = await authorizedRequest(fetcher, origin, stateDirectory, "/device-control/remote/status", { deviceId }
|
|
2225
|
+
const value = await authorizedRequest(fetcher, origin, stateDirectory, "/device-control/remote/status", { deviceId });
|
|
2078
2226
|
if (typeof value.online !== "boolean") throw new TypeError("remote status response is invalid");
|
|
2079
2227
|
const lastSeen = value.lastSeen;
|
|
2080
2228
|
if (lastSeen !== void 0 && (!Number.isSafeInteger(lastSeen) || Number(lastSeen) < 0)) throw new TypeError("remote status response is invalid");
|
|
@@ -2110,11 +2258,6 @@ var RemoteAuthorizationError = class extends Error {
|
|
|
2110
2258
|
httpStatus;
|
|
2111
2259
|
pathname;
|
|
2112
2260
|
};
|
|
2113
|
-
function canonicalOrigin2(value) {
|
|
2114
|
-
const url = new URL(value);
|
|
2115
|
-
if (url.protocol !== "https:" || url.origin !== value || url.username || url.password) throw new TypeError("origin must be canonical HTTPS");
|
|
2116
|
-
return url.origin;
|
|
2117
|
-
}
|
|
2118
2261
|
function bounded2(value, label) {
|
|
2119
2262
|
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(value)) throw new TypeError(label + " is invalid");
|
|
2120
2263
|
return value;
|
|
@@ -2315,7 +2458,7 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
|
|
|
2315
2458
|
else if (option === "--json") json2 = true;
|
|
2316
2459
|
else throw new TypeError("unsupported UAP Device Control option: " + option);
|
|
2317
2460
|
}
|
|
2318
|
-
const normalizedOrigin = origin === void 0 ? void 0 :
|
|
2461
|
+
const normalizedOrigin = origin === void 0 ? void 0 : canonicalOrigin(origin);
|
|
2319
2462
|
if (!roots.length && command === "remote") roots.push(...defaultRemoteRoots(cwd));
|
|
2320
2463
|
return {
|
|
2321
2464
|
command,
|
|
@@ -2339,7 +2482,7 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
|
|
|
2339
2482
|
}
|
|
2340
2483
|
const existingAuth = await loadRemoteAuth(config.stateDirectory);
|
|
2341
2484
|
const resolvedOrigin = resolveConfiguredOrigin(config.origin, existingAuth?.origin);
|
|
2342
|
-
const output = (event) => process.stdout.write(
|
|
2485
|
+
const output = (event) => process.stdout.write(formatCliLogEntry(event, config.json) + "\n");
|
|
2343
2486
|
if (config.command === "login") {
|
|
2344
2487
|
const auth = await loginDeviceControl(resolvedOrigin, config.stateDirectory, {
|
|
2345
2488
|
pairingCode: config.pairingCode,
|
|
@@ -2406,6 +2549,12 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
|
|
|
2406
2549
|
await lease.release();
|
|
2407
2550
|
}
|
|
2408
2551
|
}
|
|
2552
|
+
function formatCliLogEntry(event, json2 = false, now = /* @__PURE__ */ new Date()) {
|
|
2553
|
+
const timestamp = now.toISOString();
|
|
2554
|
+
if (json2) return JSON.stringify({ ...event, timestamp });
|
|
2555
|
+
const prefix = "[" + now.toTimeString().slice(0, 8) + "." + String(now.getMilliseconds()).padStart(3, "0") + "] ";
|
|
2556
|
+
return formatCliEvent(event).split("\n").map((line) => prefix + line).join("\n");
|
|
2557
|
+
}
|
|
2409
2558
|
function formatCliEvent(event, json2 = false) {
|
|
2410
2559
|
if (json2) return JSON.stringify(event);
|
|
2411
2560
|
const status = event.status;
|
|
@@ -2437,8 +2586,14 @@ function formatCliEvent(event, json2 = false) {
|
|
|
2437
2586
|
if (event.event === "remote.session") {
|
|
2438
2587
|
if (status === "replaced") return "\u267B\uFE0F Previous UAP Remote instance stopped; starting the new session";
|
|
2439
2588
|
if (status === "connected") return "\u2705 Device connected \xB7 " + String(event.deviceId) + (event.agentVersion ? " \xB7 v" + String(event.agentVersion) : "");
|
|
2440
|
-
if (status === "disconnected")
|
|
2441
|
-
|
|
2589
|
+
if (status === "disconnected") {
|
|
2590
|
+
const code = Number(event.closeCode);
|
|
2591
|
+
const cause = ["socket-closed", "socket-error", "client-abort", "protocol-error", "result-delivery"].includes(String(event.closeCause)) ? String(event.closeCause) : "";
|
|
2592
|
+
const uptime = Number(event.uptimeMs);
|
|
2593
|
+
return "\u{1F50C} Device disconnected \xB7 " + String(event.deviceId) + (Number.isInteger(code) && code >= 1e3 && code <= 4999 ? " \xB7 WS " + code : "") + (cause ? " \xB7 " + cause : "") + (Number.isInteger(uptime) && uptime >= 0 && uptime <= 864e5 ? " \xB7 uptime " + uptime + " ms" : "");
|
|
2594
|
+
}
|
|
2595
|
+
if (status === "reconnecting")
|
|
2596
|
+
return "\u26A0\uFE0F Connection interrupted" + httpDetail(event) + (["transport", "timeout"].includes(String(event.reason)) ? " \xB7 " + String(event.reason) : "") + " \xB7 retrying in " + String(event.retryMs) + " ms";
|
|
2442
2597
|
if (status === "reauthorizing") return "\u{1F510} Refreshing Device Control authorization" + httpDetail(event);
|
|
2443
2598
|
}
|
|
2444
2599
|
if (event.event === "oauth.browser" && status === "authorization-required")
|
|
@@ -2513,11 +2668,6 @@ function resolveConfiguredOrigin(explicit, stored) {
|
|
|
2513
2668
|
if (explicit && stored && explicit !== stored) throw new TypeError("configured origin does not match the authenticated origin; logout before changing environments");
|
|
2514
2669
|
return explicit ?? stored ?? DEFAULT_DEVICE_CONTROL_ORIGIN;
|
|
2515
2670
|
}
|
|
2516
|
-
function canonicalOrigin3(value) {
|
|
2517
|
-
const url = new URL(value);
|
|
2518
|
-
if (url.protocol !== "https:" || url.origin !== value || url.username || url.password) throw new TypeError("origin must be canonical HTTPS");
|
|
2519
|
-
return url.origin;
|
|
2520
|
-
}
|
|
2521
2671
|
function required(value, label) {
|
|
2522
2672
|
if (!value || value.includes("\0") || value.length > 4096) throw new TypeError(label + " is invalid");
|
|
2523
2673
|
return value;
|