@codingfrees/uap-device-control 0.1.4 → 0.1.6
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 +17 -1
- package/dist/uap-device-control.mjs +560 -97
- package/package.json +1 -1
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. Only one `remote` process may use a state directory at a time; starting a second process with the same device identity fails locally instead of replacing the live broker session. OAuth refresh is serialized across processes, and access-token renewal is retried in the existing broker session rather than forcing a device reconnect.
|
|
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,7 +80,7 @@ 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.
|
|
68
84
|
|
|
69
85
|
## Publishing
|
|
70
86
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
|
-
import
|
|
4
|
+
import path6 from "node:path";
|
|
5
5
|
|
|
6
6
|
// src/auth.ts
|
|
7
7
|
import { createServer } from "node:http";
|
|
@@ -128,6 +128,66 @@ async function saveRemoteAuth(stateDirectory, value) {
|
|
|
128
128
|
async function clearRemoteAuth(stateDirectory) {
|
|
129
129
|
await rm(path.join(stateDirectory, "auth.json"), { force: true });
|
|
130
130
|
}
|
|
131
|
+
function acquireRemoteProcessLock(stateDirectory) {
|
|
132
|
+
return acquireStateLock(stateDirectory, "remote.lock", 0, "another UAP Device Control remote process is already running for this state directory");
|
|
133
|
+
}
|
|
134
|
+
async function withRemoteAuthRefreshLock(stateDirectory, task) {
|
|
135
|
+
const lease = await acquireStateLock(stateDirectory, "auth-refresh.lock", 2e4, "Device Control authorization refresh is busy");
|
|
136
|
+
try {
|
|
137
|
+
return await task();
|
|
138
|
+
} finally {
|
|
139
|
+
await lease.release();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async function acquireStateLock(stateDirectory, name, waitMs, busyMessage) {
|
|
143
|
+
await mkdir(stateDirectory, { recursive: true, mode: 448 });
|
|
144
|
+
const file = path.join(stateDirectory, name);
|
|
145
|
+
const owner = { pid: process.pid, token: randomUUID(), createdAt: Date.now() };
|
|
146
|
+
const deadline = Date.now() + waitMs;
|
|
147
|
+
for (; ; ) {
|
|
148
|
+
try {
|
|
149
|
+
await writeFile(file, JSON.stringify(owner), { encoding: "utf8", flag: "wx", mode: 384 });
|
|
150
|
+
return { release: () => removeOwnedLock(file, owner.token) };
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (!exists(error)) throw error;
|
|
153
|
+
}
|
|
154
|
+
const current = await readLock(file);
|
|
155
|
+
if (!current) throw new TypeError("Device Control state lock is invalid: " + file);
|
|
156
|
+
if (!processAlive(current.pid)) {
|
|
157
|
+
await removeOwnedLock(file, current.token);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (Date.now() >= deadline) throw new TypeError(busyMessage);
|
|
161
|
+
await sleep(25);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
async function readLock(file) {
|
|
165
|
+
try {
|
|
166
|
+
const raw = JSON.parse(await readFile(file, "utf8"));
|
|
167
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
168
|
+
const value = raw;
|
|
169
|
+
if (!Number.isSafeInteger(value.pid) || Number(value.pid) < 1 || typeof value.token !== "string" || !/^[0-9a-f-]{36}$/.test(value.token) || !Number.isSafeInteger(value.createdAt)) return void 0;
|
|
170
|
+
return { pid: Number(value.pid), token: value.token, createdAt: Number(value.createdAt) };
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (missing(error)) return void 0;
|
|
173
|
+
return void 0;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async function removeOwnedLock(file, token) {
|
|
177
|
+
const current = await readLock(file);
|
|
178
|
+
if (current?.token === token) await rm(file, { force: true });
|
|
179
|
+
}
|
|
180
|
+
function processAlive(pid) {
|
|
181
|
+
try {
|
|
182
|
+
process.kill(pid, 0);
|
|
183
|
+
return true;
|
|
184
|
+
} catch (error) {
|
|
185
|
+
return !Boolean(error && typeof error === "object" && "code" in error && error.code === "ESRCH");
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function sleep(ms) {
|
|
189
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
190
|
+
}
|
|
131
191
|
function missing(error) {
|
|
132
192
|
return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
|
|
133
193
|
}
|
|
@@ -156,17 +216,17 @@ async function loginDeviceControl(origin, stateDirectory, options = {}) {
|
|
|
156
216
|
);
|
|
157
217
|
const clientId = text(registration.client_id, "OAuth client id");
|
|
158
218
|
const pkce = await createOAuthPkce();
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
219
|
+
const authorize2 = new URL(authorizationEndpoint);
|
|
220
|
+
authorize2.searchParams.set("response_type", "code");
|
|
221
|
+
authorize2.searchParams.set("client_id", clientId);
|
|
222
|
+
authorize2.searchParams.set("redirect_uri", callback.redirectUri);
|
|
223
|
+
authorize2.searchParams.set("resource", issuer + "/mcp");
|
|
224
|
+
authorize2.searchParams.set("scope", scopes);
|
|
225
|
+
authorize2.searchParams.set("state", pkce.state);
|
|
226
|
+
authorize2.searchParams.set("code_challenge", pkce.challenge);
|
|
227
|
+
authorize2.searchParams.set("code_challenge_method", "S256");
|
|
168
228
|
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,
|
|
229
|
+
const result = configuredBootstrap ? await automaticPairing(fetcher, issuer, authorize2, configuredBootstrap, pkce.state) : await browserAuthorization(options.open ?? openBrowser, authorize2.href, callback.result);
|
|
170
230
|
if (result.state !== pkce.state || !result.code) throw new TypeError("OAuth callback is invalid");
|
|
171
231
|
const token = await json(
|
|
172
232
|
fetcher(tokenEndpoint, {
|
|
@@ -186,27 +246,30 @@ async function loginDeviceControl(origin, stateDirectory, options = {}) {
|
|
|
186
246
|
}
|
|
187
247
|
}
|
|
188
248
|
async function accessToken(stateDirectory, fetcher = fetch, forceRefresh = false) {
|
|
189
|
-
const
|
|
190
|
-
if (!
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
249
|
+
const observed = await requiredDeviceAuth(stateDirectory);
|
|
250
|
+
if (!forceRefresh && usableAccessToken(observed)) return { auth: observed, token: observed.accessToken };
|
|
251
|
+
return withRemoteAuthRefreshLock(stateDirectory, async () => {
|
|
252
|
+
const auth = await requiredDeviceAuth(stateDirectory);
|
|
253
|
+
const refreshedElsewhere = authorizationChanged(observed, auth);
|
|
254
|
+
if (usableAccessToken(auth) && (!forceRefresh || refreshedElsewhere)) return { auth, token: auth.accessToken };
|
|
255
|
+
const tokenEndpoint = new URL("/oauth/token", auth.origin);
|
|
256
|
+
const token = await json(
|
|
257
|
+
fetcher(tokenEndpoint, {
|
|
258
|
+
method: "POST",
|
|
259
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
260
|
+
body: new URLSearchParams({ grant_type: "refresh_token", client_id: auth.clientId, refresh_token: auth.refreshToken, resource: auth.origin + "/mcp" })
|
|
261
|
+
})
|
|
262
|
+
);
|
|
263
|
+
const next = {
|
|
264
|
+
...auth,
|
|
265
|
+
refreshToken: text(token.refresh_token, "OAuth refresh token"),
|
|
266
|
+
accessToken: text(token.access_token, "OAuth access token"),
|
|
267
|
+
accessExpiresAt: Date.now() + integer(token.expires_in, "OAuth expiry") * 1e3,
|
|
268
|
+
scope: typeof token.scope === "string" ? token.scope : auth.scope
|
|
269
|
+
};
|
|
270
|
+
await saveRemoteAuth(stateDirectory, next);
|
|
271
|
+
return { auth: next, token: next.accessToken };
|
|
272
|
+
});
|
|
210
273
|
}
|
|
211
274
|
async function logoutDeviceControl(stateDirectory, fetcher = fetch) {
|
|
212
275
|
const auth = await loadRemoteAuth(stateDirectory);
|
|
@@ -219,9 +282,9 @@ async function logoutDeviceControl(stateDirectory, fetcher = fetch) {
|
|
|
219
282
|
await clearRemoteAuth(stateDirectory);
|
|
220
283
|
return true;
|
|
221
284
|
}
|
|
222
|
-
async function automaticPairing(fetcher, issuer,
|
|
285
|
+
async function automaticPairing(fetcher, issuer, authorize2, ownerSecret, expectedState) {
|
|
223
286
|
const started = await json(
|
|
224
|
-
fetcher(new URL("/pairing/start", issuer), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ authorizeUrl:
|
|
287
|
+
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
288
|
);
|
|
226
289
|
const pairingId = text(started.pairingId, "pairing id");
|
|
227
290
|
const pollToken = text(started.pollToken, "pairing poll token");
|
|
@@ -286,15 +349,27 @@ async function openBrowser(url) {
|
|
|
286
349
|
const launch = browserOpenCommand(process.platform, url);
|
|
287
350
|
await execute(launch.command, launch.args, { windowsHide: true });
|
|
288
351
|
}
|
|
352
|
+
async function requiredDeviceAuth(stateDirectory) {
|
|
353
|
+
const auth = await loadRemoteAuth(stateDirectory);
|
|
354
|
+
if (!auth) throw new TypeError("not logged in");
|
|
355
|
+
if (!auth.scope.split(" ").includes("device-control:device")) throw new TypeError("device authorization is required; run login again");
|
|
356
|
+
return auth;
|
|
357
|
+
}
|
|
358
|
+
function usableAccessToken(auth) {
|
|
359
|
+
return Boolean(auth.accessToken && auth.accessExpiresAt && auth.accessExpiresAt > Date.now() + 3e4);
|
|
360
|
+
}
|
|
361
|
+
function authorizationChanged(before, after) {
|
|
362
|
+
return before.accessToken !== after.accessToken || before.accessExpiresAt !== after.accessExpiresAt || before.refreshToken !== after.refreshToken;
|
|
363
|
+
}
|
|
289
364
|
async function json(response) {
|
|
290
365
|
const value = await response;
|
|
291
366
|
if (!value.ok) {
|
|
292
|
-
let
|
|
367
|
+
let path7 = "request";
|
|
293
368
|
try {
|
|
294
|
-
|
|
369
|
+
path7 = new URL(value.url).pathname || "request";
|
|
295
370
|
} catch {
|
|
296
371
|
}
|
|
297
|
-
throw new TypeError(`OAuth request failed (${value.status}) at ${
|
|
372
|
+
throw new TypeError(`OAuth request failed (${value.status}) at ${path7}`);
|
|
298
373
|
}
|
|
299
374
|
const raw = await value.json();
|
|
300
375
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("OAuth response is invalid");
|
|
@@ -323,7 +398,7 @@ function integer(value, label) {
|
|
|
323
398
|
|
|
324
399
|
// src/remote.ts
|
|
325
400
|
import os3 from "node:os";
|
|
326
|
-
import
|
|
401
|
+
import path4 from "node:path";
|
|
327
402
|
|
|
328
403
|
// ../device-agent/src/engine.ts
|
|
329
404
|
import { spawn } from "node:child_process";
|
|
@@ -351,7 +426,12 @@ var DeviceAgentEngine = class {
|
|
|
351
426
|
if (this.#roots.has(root2.id) || !path2.isAbsolute(root2.path)) throw new TypeError("device root is invalid");
|
|
352
427
|
this.#roots.set(root2.id, { ...root2, readOnly: root2.readOnly === true, path: realpathSync(path2.resolve(root2.path)) });
|
|
353
428
|
}
|
|
354
|
-
|
|
429
|
+
for (const adapter of options.capabilityAdapters ?? [])
|
|
430
|
+
for (const capability of adapter.capabilities) {
|
|
431
|
+
if (!/^[a-z][a-z0-9.-]{2,95}$/.test(capability) || this.#capabilityAdapters.has(capability)) throw new TypeError("device capability adapter is invalid");
|
|
432
|
+
this.#capabilityAdapters.set(capability, adapter);
|
|
433
|
+
}
|
|
434
|
+
this.#baseCapabilities = [
|
|
355
435
|
"device.info",
|
|
356
436
|
"device.health",
|
|
357
437
|
"filesystem.roots",
|
|
@@ -380,9 +460,10 @@ var DeviceAgentEngine = class {
|
|
|
380
460
|
...options.readClipboard ? ["clipboard.read"] : [],
|
|
381
461
|
...options.writeClipboard ? ["clipboard.write"] : []
|
|
382
462
|
];
|
|
463
|
+
if ([...this.#capabilityAdapters.keys()].some((capability) => this.#baseCapabilities.includes(capability))) throw new TypeError("device capability adapter collides with a built-in capability");
|
|
383
464
|
}
|
|
384
465
|
options;
|
|
385
|
-
|
|
466
|
+
#baseCapabilities;
|
|
386
467
|
#roots = /* @__PURE__ */ new Map();
|
|
387
468
|
#processes = /* @__PURE__ */ new Map();
|
|
388
469
|
#oneShots = /* @__PURE__ */ new Map();
|
|
@@ -395,7 +476,11 @@ var DeviceAgentEngine = class {
|
|
|
395
476
|
#sessionIdleTimeoutMs;
|
|
396
477
|
#allowed;
|
|
397
478
|
#allowedServices = /* @__PURE__ */ new Set();
|
|
479
|
+
#capabilityAdapters = /* @__PURE__ */ new Map();
|
|
398
480
|
#listeners = /* @__PURE__ */ new Set();
|
|
481
|
+
get capabilities() {
|
|
482
|
+
return [...this.#baseCapabilities, ...[...this.#capabilityAdapters].filter(([, adapter]) => adapter.available?.() !== false).map(([capability]) => capability)];
|
|
483
|
+
}
|
|
399
484
|
info() {
|
|
400
485
|
return {
|
|
401
486
|
deviceId: this.options.deviceId,
|
|
@@ -411,6 +496,7 @@ var DeviceAgentEngine = class {
|
|
|
411
496
|
}
|
|
412
497
|
close() {
|
|
413
498
|
this.panicStop();
|
|
499
|
+
for (const adapter of new Set(this.#capabilityAdapters.values())) void adapter.close?.();
|
|
414
500
|
this.#listeners.clear();
|
|
415
501
|
}
|
|
416
502
|
panicStop() {
|
|
@@ -524,6 +610,8 @@ var DeviceAgentEngine = class {
|
|
|
524
610
|
await this.options.writeClipboard(clipboardText(input.text));
|
|
525
611
|
return { accepted: true };
|
|
526
612
|
}
|
|
613
|
+
const adapter = this.#capabilityAdapters.get(capability);
|
|
614
|
+
if (adapter) return adapter.execute(capability, input);
|
|
527
615
|
throw new TypeError("device capability is unavailable");
|
|
528
616
|
}
|
|
529
617
|
async #filesystem(capability, input) {
|
|
@@ -716,7 +804,13 @@ var DeviceAgentEngine = class {
|
|
|
716
804
|
clearTimeout(session.timer);
|
|
717
805
|
session.timer = setTimeout(() => void this.#pushScreenFrame(sessionId), session.intervalMs);
|
|
718
806
|
session.timer.unref();
|
|
719
|
-
return {
|
|
807
|
+
return {
|
|
808
|
+
sessionId,
|
|
809
|
+
intervalMs: session.intervalMs,
|
|
810
|
+
format: session.format,
|
|
811
|
+
quality: session.quality,
|
|
812
|
+
adapted: session.intervalMs !== session.requestedIntervalMs || session.quality !== session.requestedQuality || session.requestedFormat === "auto" && session.format === "jpeg"
|
|
813
|
+
};
|
|
720
814
|
}
|
|
721
815
|
throw new TypeError("screen stream operation is invalid");
|
|
722
816
|
}
|
|
@@ -1349,6 +1443,236 @@ function isMissing2(error) {
|
|
|
1349
1443
|
return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
|
|
1350
1444
|
}
|
|
1351
1445
|
|
|
1446
|
+
// src/browser-bridge.ts
|
|
1447
|
+
import { createHash, randomBytes as randomBytes2, randomUUID as randomUUID3, timingSafeEqual } from "node:crypto";
|
|
1448
|
+
import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "node:fs/promises";
|
|
1449
|
+
import { createServer as createServer2 } from "node:http";
|
|
1450
|
+
import path3 from "node:path";
|
|
1451
|
+
var BROWSER_CONTROL_CAPABILITIES = ["browser.tabs", "browser.navigate", "browser.snapshot", "browser.click", "browser.type", "browser.scroll"];
|
|
1452
|
+
var EXTENSION_ID = /^[a-p]{32}$/;
|
|
1453
|
+
async function createBrowserBridge(stateDirectory, requestedPort = 8800, log) {
|
|
1454
|
+
if (!Number.isInteger(requestedPort) || requestedPort !== 0 && (requestedPort < 1024 || requestedPort > 65535)) throw new TypeError("browser bridge port is invalid");
|
|
1455
|
+
await mkdir3(stateDirectory, { recursive: true, mode: 448 });
|
|
1456
|
+
const statePath = path3.join(stateDirectory, "browser-bridge.json");
|
|
1457
|
+
let pairing = await loadPairing(statePath);
|
|
1458
|
+
let pairingCode = pairing ? void 0 : createPairingCode();
|
|
1459
|
+
let pairingExpiresAt = pairingCode ? Date.now() + 10 * 6e4 : 0;
|
|
1460
|
+
let lastSeen = 0;
|
|
1461
|
+
let waiter;
|
|
1462
|
+
const queue = [];
|
|
1463
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1464
|
+
const server = createServer2(async (request2, response) => {
|
|
1465
|
+
try {
|
|
1466
|
+
const origin = request2.headers.origin ?? "";
|
|
1467
|
+
if (request2.method === "OPTIONS") return cors(response, origin, 204);
|
|
1468
|
+
const url = new URL(request2.url ?? "/", "http://127.0.0.1");
|
|
1469
|
+
if (!url.pathname.startsWith("/browser/")) return send(response, 404, { error: "not_found" }, origin);
|
|
1470
|
+
if (url.pathname === "/browser/pair" && request2.method === "POST") {
|
|
1471
|
+
const body = await jsonBody(request2);
|
|
1472
|
+
const extensionId = extensionIdValue(body.extensionId);
|
|
1473
|
+
if (origin !== "chrome-extension://" + extensionId) throw new TypeError("browser extension origin is invalid");
|
|
1474
|
+
if (pairing) throw new TypeError("browser bridge is already paired");
|
|
1475
|
+
const candidate = pairingCodeValue(body.pairingCode);
|
|
1476
|
+
if (!pairingCode || Date.now() > pairingExpiresAt) {
|
|
1477
|
+
pairingCode = createPairingCode();
|
|
1478
|
+
pairingExpiresAt = Date.now() + 10 * 6e4;
|
|
1479
|
+
log?.({ event: "browser.bridge", status: "pairing-required", port: actualPort(server), pairingCode });
|
|
1480
|
+
throw new TypeError("browser pairing code expired; use the new code shown locally");
|
|
1481
|
+
}
|
|
1482
|
+
if (!secureEqual(candidate, pairingCode)) throw new TypeError("browser pairing code is invalid");
|
|
1483
|
+
const token = randomBytes2(32).toString("base64url");
|
|
1484
|
+
pairing = { extensionId, tokenHash: digest(token) };
|
|
1485
|
+
pairingCode = void 0;
|
|
1486
|
+
pairingExpiresAt = 0;
|
|
1487
|
+
await persistPairing(statePath, pairing);
|
|
1488
|
+
log?.({ event: "browser.bridge", status: "paired" });
|
|
1489
|
+
return send(response, 200, { token, port: actualPort(server) }, origin);
|
|
1490
|
+
}
|
|
1491
|
+
const current = authorize(request2, origin, pairing);
|
|
1492
|
+
if (url.pathname === "/browser/status" && request2.method === "POST") return send(response, 200, { paired: true, online: Date.now() - lastSeen < 45e3 }, current.origin);
|
|
1493
|
+
if (url.pathname === "/browser/unpair" && request2.method === "POST") {
|
|
1494
|
+
pairing = void 0;
|
|
1495
|
+
pairingCode = createPairingCode();
|
|
1496
|
+
pairingExpiresAt = Date.now() + 10 * 6e4;
|
|
1497
|
+
lastSeen = 0;
|
|
1498
|
+
await writeFile3(statePath, JSON.stringify({ version: 1 }) + "\n", { mode: 384 });
|
|
1499
|
+
rejectAll(pending, "browser bridge was unpaired");
|
|
1500
|
+
log?.({ event: "browser.bridge", status: "unpaired" });
|
|
1501
|
+
log?.({ event: "browser.bridge", status: "pairing-required", port: actualPort(server), pairingCode });
|
|
1502
|
+
return send(response, 200, { unpaired: true }, current.origin);
|
|
1503
|
+
}
|
|
1504
|
+
if (url.pathname === "/browser/poll" && request2.method === "POST") {
|
|
1505
|
+
const wasOffline = Date.now() - lastSeen >= 45e3;
|
|
1506
|
+
lastSeen = Date.now();
|
|
1507
|
+
if (wasOffline) log?.({ event: "browser.bridge", status: "connected" });
|
|
1508
|
+
const command = queue.shift() ?? await new Promise((resolve) => {
|
|
1509
|
+
const timer = setTimeout(() => {
|
|
1510
|
+
if (waiter === done) waiter = void 0;
|
|
1511
|
+
resolve(null);
|
|
1512
|
+
}, 2e4);
|
|
1513
|
+
timer.unref();
|
|
1514
|
+
const done = (value) => {
|
|
1515
|
+
clearTimeout(timer);
|
|
1516
|
+
resolve(value);
|
|
1517
|
+
};
|
|
1518
|
+
waiter = done;
|
|
1519
|
+
});
|
|
1520
|
+
return send(response, 200, { command }, current.origin);
|
|
1521
|
+
}
|
|
1522
|
+
if (url.pathname === "/browser/result" && request2.method === "POST") {
|
|
1523
|
+
lastSeen = Date.now();
|
|
1524
|
+
const body = await jsonBody(request2);
|
|
1525
|
+
const requestId = identifier(body.requestId, "requestId");
|
|
1526
|
+
const completion = pending.get(requestId);
|
|
1527
|
+
if (!completion) return send(response, 409, { error: "request_not_pending" }, current.origin);
|
|
1528
|
+
pending.delete(requestId);
|
|
1529
|
+
clearTimeout(completion.timer);
|
|
1530
|
+
if (body.ok === true) completion.resolve(jsonValue(body.output));
|
|
1531
|
+
else completion.reject(new TypeError(typeof body.error === "string" ? body.error.slice(0, 256) : "browser operation failed"));
|
|
1532
|
+
return send(response, 200, { accepted: true }, current.origin);
|
|
1533
|
+
}
|
|
1534
|
+
return send(response, 404, { error: "not_found" }, current.origin);
|
|
1535
|
+
} catch (error) {
|
|
1536
|
+
return send(response, 400, { error: error instanceof Error ? error.message.slice(0, 256) : "browser bridge failed" }, request2.headers.origin ?? "");
|
|
1537
|
+
}
|
|
1538
|
+
});
|
|
1539
|
+
await new Promise((resolve, reject) => {
|
|
1540
|
+
server.once("error", reject);
|
|
1541
|
+
server.listen(requestedPort, "127.0.0.1", () => resolve());
|
|
1542
|
+
});
|
|
1543
|
+
return {
|
|
1544
|
+
get port() {
|
|
1545
|
+
return actualPort(server);
|
|
1546
|
+
},
|
|
1547
|
+
get paired() {
|
|
1548
|
+
return Boolean(pairing);
|
|
1549
|
+
},
|
|
1550
|
+
capabilities: BROWSER_CONTROL_CAPABILITIES,
|
|
1551
|
+
get pairingCode() {
|
|
1552
|
+
return pairingCode;
|
|
1553
|
+
},
|
|
1554
|
+
available() {
|
|
1555
|
+
return Boolean(pairing);
|
|
1556
|
+
},
|
|
1557
|
+
execute(capability, parameters) {
|
|
1558
|
+
if (!BROWSER_CONTROL_CAPABILITIES.includes(capability)) throw new TypeError("browser capability is unavailable");
|
|
1559
|
+
if (!pairing || Date.now() - lastSeen >= 45e3) return Promise.reject(new TypeError("browser control extension is unavailable"));
|
|
1560
|
+
const requestId = randomUUID3();
|
|
1561
|
+
const command = { requestId, capability, parameters };
|
|
1562
|
+
const completion = new Promise((resolve, reject) => {
|
|
1563
|
+
const timer = setTimeout(() => {
|
|
1564
|
+
pending.delete(requestId);
|
|
1565
|
+
reject(new TypeError("browser operation timed out"));
|
|
1566
|
+
}, 45e3);
|
|
1567
|
+
timer.unref();
|
|
1568
|
+
pending.set(requestId, { resolve, reject, timer });
|
|
1569
|
+
});
|
|
1570
|
+
if (waiter) {
|
|
1571
|
+
const deliver = waiter;
|
|
1572
|
+
waiter = void 0;
|
|
1573
|
+
deliver(command);
|
|
1574
|
+
} else queue.push(command);
|
|
1575
|
+
return completion;
|
|
1576
|
+
},
|
|
1577
|
+
async close() {
|
|
1578
|
+
rejectAll(pending, "browser bridge closed");
|
|
1579
|
+
if (waiter) waiter(null);
|
|
1580
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
1581
|
+
}
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
function authorize(request2, origin, pairing) {
|
|
1585
|
+
if (!pairing || origin !== "chrome-extension://" + pairing.extensionId) throw new TypeError("browser bridge is not paired");
|
|
1586
|
+
const auth = request2.headers.authorization;
|
|
1587
|
+
if (!auth?.startsWith("Bearer ") || digest(auth.slice(7)) !== pairing.tokenHash) throw new TypeError("browser bridge authorization failed");
|
|
1588
|
+
return { origin };
|
|
1589
|
+
}
|
|
1590
|
+
function cors(response, origin, status) {
|
|
1591
|
+
if (/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) {
|
|
1592
|
+
response.setHeader("access-control-allow-origin", origin);
|
|
1593
|
+
response.setHeader("access-control-allow-headers", "authorization,content-type");
|
|
1594
|
+
response.setHeader("access-control-allow-methods", "POST,OPTIONS");
|
|
1595
|
+
response.setHeader("vary", "Origin");
|
|
1596
|
+
}
|
|
1597
|
+
response.statusCode = status;
|
|
1598
|
+
response.end();
|
|
1599
|
+
}
|
|
1600
|
+
function send(response, status, body, origin) {
|
|
1601
|
+
if (/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) {
|
|
1602
|
+
response.setHeader("access-control-allow-origin", origin);
|
|
1603
|
+
response.setHeader("vary", "Origin");
|
|
1604
|
+
}
|
|
1605
|
+
response.statusCode = status;
|
|
1606
|
+
response.setHeader("content-type", "application/json; charset=utf-8");
|
|
1607
|
+
response.setHeader("cache-control", "no-store");
|
|
1608
|
+
response.end(JSON.stringify(body));
|
|
1609
|
+
}
|
|
1610
|
+
async function jsonBody(request2) {
|
|
1611
|
+
const chunks = [];
|
|
1612
|
+
let size = 0;
|
|
1613
|
+
for await (const chunk of request2) {
|
|
1614
|
+
size += Buffer.byteLength(chunk);
|
|
1615
|
+
if (size > 1024 * 1024) throw new TypeError("browser bridge request is too large");
|
|
1616
|
+
chunks.push(Buffer.from(chunk));
|
|
1617
|
+
}
|
|
1618
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
|
1619
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("browser bridge request is invalid");
|
|
1620
|
+
return parsed;
|
|
1621
|
+
}
|
|
1622
|
+
async function loadPairing(file) {
|
|
1623
|
+
try {
|
|
1624
|
+
const parsed = JSON.parse(await readFile3(file, "utf8"));
|
|
1625
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
|
|
1626
|
+
const record = parsed;
|
|
1627
|
+
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;
|
|
1628
|
+
return { extensionId: record.extensionId, tokenHash: record.tokenHash };
|
|
1629
|
+
} catch {
|
|
1630
|
+
return void 0;
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
async function persistPairing(file, pairing) {
|
|
1634
|
+
await writeFile3(file, JSON.stringify({ version: 1, ...pairing }) + "\n", { mode: 384 });
|
|
1635
|
+
}
|
|
1636
|
+
function rejectAll(pending, message) {
|
|
1637
|
+
for (const value of pending.values()) {
|
|
1638
|
+
clearTimeout(value.timer);
|
|
1639
|
+
value.reject(new TypeError(message));
|
|
1640
|
+
}
|
|
1641
|
+
pending.clear();
|
|
1642
|
+
}
|
|
1643
|
+
function digest(value) {
|
|
1644
|
+
return createHash("sha256").update(value).digest("hex");
|
|
1645
|
+
}
|
|
1646
|
+
function extensionIdValue(value) {
|
|
1647
|
+
if (typeof value !== "string" || !EXTENSION_ID.test(value)) throw new TypeError("browser extension id is invalid");
|
|
1648
|
+
return value;
|
|
1649
|
+
}
|
|
1650
|
+
function identifier(value, label) {
|
|
1651
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(value)) throw new TypeError(label + " is invalid");
|
|
1652
|
+
return value;
|
|
1653
|
+
}
|
|
1654
|
+
function jsonValue(value) {
|
|
1655
|
+
JSON.stringify(value);
|
|
1656
|
+
return value;
|
|
1657
|
+
}
|
|
1658
|
+
function actualPort(server) {
|
|
1659
|
+
const address = server.address();
|
|
1660
|
+
if (!address || typeof address === "string") throw new TypeError("browser bridge is unavailable");
|
|
1661
|
+
return address.port;
|
|
1662
|
+
}
|
|
1663
|
+
function createPairingCode() {
|
|
1664
|
+
return randomBytes2(9).toString("base64url");
|
|
1665
|
+
}
|
|
1666
|
+
function pairingCodeValue(value) {
|
|
1667
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9_-]{12,32}$/.test(value)) throw new TypeError("browser pairing code is invalid");
|
|
1668
|
+
return value;
|
|
1669
|
+
}
|
|
1670
|
+
function secureEqual(left, right) {
|
|
1671
|
+
const a = Buffer.from(digest(left), "hex");
|
|
1672
|
+
const b = Buffer.from(digest(right), "hex");
|
|
1673
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1352
1676
|
// src/remote.ts
|
|
1353
1677
|
async function runRemote(options) {
|
|
1354
1678
|
const fetcher = options.fetcher ?? fetch;
|
|
@@ -1356,62 +1680,98 @@ async function runRemote(options) {
|
|
|
1356
1680
|
const desktop = await createNativeDesktopAdapter();
|
|
1357
1681
|
const services = options.allowedServices.length ? await createNativeServiceAdapter() : void 0;
|
|
1358
1682
|
if (options.allowedServices.length && !services) throw new TypeError("native service control is unavailable");
|
|
1683
|
+
let refreshSession = () => {
|
|
1684
|
+
};
|
|
1685
|
+
const browserLog = (event) => {
|
|
1686
|
+
options.log?.(event);
|
|
1687
|
+
if (event.event === "browser.bridge" && (event.status === "paired" || event.status === "unpaired")) refreshSession();
|
|
1688
|
+
};
|
|
1689
|
+
const browser = options.browserControl === false ? void 0 : await createBrowserBridge(options.stateDirectory, options.browserPort ?? 8800, browserLog);
|
|
1690
|
+
if (browser) {
|
|
1691
|
+
options.log?.({ event: "browser.bridge", status: "ready", port: browser.port, paired: browser.paired });
|
|
1692
|
+
if (browser.pairingCode) options.log?.({ event: "browser.bridge", status: "pairing-required", port: browser.port, pairingCode: browser.pairingCode });
|
|
1693
|
+
}
|
|
1359
1694
|
const engine = new DeviceAgentEngine({
|
|
1360
1695
|
deviceId,
|
|
1361
1696
|
name: os3.hostname(),
|
|
1362
1697
|
roots: options.roots,
|
|
1363
1698
|
...options.allowedExecutables.length ? { allowedExecutables: options.allowedExecutables } : {},
|
|
1364
1699
|
...services ? { services, allowedServices: options.allowedServices } : {},
|
|
1700
|
+
...browser ? { capabilityAdapters: [browser] } : {},
|
|
1365
1701
|
...desktop
|
|
1366
1702
|
});
|
|
1367
1703
|
try {
|
|
1368
1704
|
let delay = 500;
|
|
1369
1705
|
while (!options.signal?.aborted) {
|
|
1706
|
+
const sessionController = new AbortController();
|
|
1707
|
+
const abort = () => sessionController.abort();
|
|
1708
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
1709
|
+
refreshSession = abort;
|
|
1370
1710
|
try {
|
|
1371
|
-
await remoteSession(options.origin, options.stateDirectory, engine, fetcher, options.
|
|
1711
|
+
await remoteSession(options.origin, options.stateDirectory, engine, fetcher, sessionController.signal, options.log);
|
|
1372
1712
|
delay = 500;
|
|
1373
1713
|
} catch (error) {
|
|
1374
1714
|
if (options.signal?.aborted) break;
|
|
1375
|
-
if (
|
|
1376
|
-
await accessToken(options.stateDirectory, fetcher, true);
|
|
1715
|
+
if (sessionController.signal.aborted) {
|
|
1377
1716
|
delay = 500;
|
|
1378
1717
|
continue;
|
|
1379
1718
|
}
|
|
1719
|
+
if (error instanceof RemoteAuthorizationError) throw new TypeError("Device Control authorization was rejected after refresh; run login again");
|
|
1380
1720
|
if (!(error instanceof RemoteUnavailableError)) throw error;
|
|
1381
|
-
|
|
1721
|
+
options.log?.({
|
|
1722
|
+
event: "remote.session",
|
|
1723
|
+
status: "reconnecting",
|
|
1724
|
+
deviceId,
|
|
1725
|
+
retryMs: delay,
|
|
1726
|
+
...error.httpStatus === void 0 ? {} : { httpStatus: error.httpStatus },
|
|
1727
|
+
...error.pathname === void 0 ? {} : { pathname: error.pathname }
|
|
1728
|
+
});
|
|
1729
|
+
await sleep2(delay, options.signal);
|
|
1382
1730
|
delay = Math.min(delay * 2, 15e3);
|
|
1731
|
+
} finally {
|
|
1732
|
+
refreshSession = () => {
|
|
1733
|
+
};
|
|
1734
|
+
options.signal?.removeEventListener("abort", abort);
|
|
1383
1735
|
}
|
|
1384
1736
|
}
|
|
1385
1737
|
} finally {
|
|
1386
1738
|
engine.close();
|
|
1387
1739
|
}
|
|
1388
1740
|
}
|
|
1389
|
-
async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal) {
|
|
1390
|
-
const
|
|
1391
|
-
const
|
|
1741
|
+
async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal, log) {
|
|
1742
|
+
const deviceId = engine.options.deviceId;
|
|
1743
|
+
const invoke2 = (pathname, body, requestSignal = signal, timeoutMs = 15e3, requestLog = log) => authorizedRequest(fetcher, origin, stateDirectory, pathname, body, requestSignal, timeoutMs, requestLog, deviceId);
|
|
1744
|
+
const connected = await invoke2("/device-control/remote/connect", { device: engine.info() });
|
|
1392
1745
|
const sessionId = bounded2(connected.sessionId, "remote session id");
|
|
1746
|
+
log?.({ event: "remote.session", status: "connected", deviceId });
|
|
1393
1747
|
try {
|
|
1394
1748
|
while (!signal?.aborted) {
|
|
1395
|
-
const next = await
|
|
1749
|
+
const next = await invoke2("/device-control/remote/poll", { sessionId, deviceId }, signal, 35e3);
|
|
1750
|
+
if (next.notice !== void 0) log?.({ event: "plugin.tool", ...noticeValue(next.notice) });
|
|
1396
1751
|
if (next.command === null || next.command === void 0) continue;
|
|
1397
1752
|
const command = commandValue(next.command);
|
|
1398
1753
|
const startedAt = Date.now();
|
|
1399
1754
|
try {
|
|
1400
1755
|
const output = await engine.execute(command.capability, command.parameters, { workspaceId: bounded2(next.workspaceId, "workspace id") });
|
|
1401
|
-
await
|
|
1756
|
+
await invoke2("/device-control/remote/result", { sessionId, deviceId, requestId: command.requestId, ok: true, output, executionMs: elapsed(startedAt) });
|
|
1402
1757
|
} catch (error) {
|
|
1403
|
-
await
|
|
1404
|
-
fetcher,
|
|
1405
|
-
origin,
|
|
1406
|
-
"/device-control/remote/result",
|
|
1407
|
-
token,
|
|
1408
|
-
{ sessionId, deviceId: engine.options.deviceId, requestId: command.requestId, ok: false, error: safeError(error), executionMs: elapsed(startedAt) },
|
|
1409
|
-
signal
|
|
1410
|
-
);
|
|
1758
|
+
await invoke2("/device-control/remote/result", { sessionId, deviceId, requestId: command.requestId, ok: false, error: safeError(error), executionMs: elapsed(startedAt) });
|
|
1411
1759
|
}
|
|
1412
1760
|
}
|
|
1413
1761
|
} finally {
|
|
1414
|
-
await
|
|
1762
|
+
await invoke2("/device-control/remote/disconnect", { sessionId, deviceId }, void 0, 5e3, void 0).catch(() => void 0);
|
|
1763
|
+
log?.({ event: "remote.session", status: "disconnected", deviceId });
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
async function authorizedRequest(fetcher, origin, stateDirectory, pathname, body, signal, timeoutMs = 15e3, log, deviceId) {
|
|
1767
|
+
const current = await accessToken(stateDirectory, fetcher);
|
|
1768
|
+
try {
|
|
1769
|
+
return await request(fetcher, origin, pathname, current.token, body, signal, timeoutMs);
|
|
1770
|
+
} catch (error) {
|
|
1771
|
+
if (!(error instanceof RemoteAuthorizationError)) throw error;
|
|
1772
|
+
log?.({ event: "remote.session", status: "reauthorizing", ...deviceId ? { deviceId } : {}, httpStatus: error.httpStatus, pathname: error.pathname });
|
|
1773
|
+
const refreshed = await accessToken(stateDirectory, fetcher, true);
|
|
1774
|
+
return request(fetcher, origin, pathname, refreshed.token, body, signal, timeoutMs);
|
|
1415
1775
|
}
|
|
1416
1776
|
}
|
|
1417
1777
|
async function request(fetcher, origin, pathname, token, body, signal, timeoutMs = 15e3) {
|
|
@@ -1431,10 +1791,10 @@ async function request(fetcher, origin, pathname, token, body, signal, timeoutMs
|
|
|
1431
1791
|
signal: controller.signal
|
|
1432
1792
|
});
|
|
1433
1793
|
} catch {
|
|
1434
|
-
throw new RemoteUnavailableError();
|
|
1794
|
+
throw new RemoteUnavailableError(void 0, pathname);
|
|
1435
1795
|
}
|
|
1436
|
-
if (response.status === 401 || response.status === 403) throw new RemoteAuthorizationError();
|
|
1437
|
-
if (!response.ok) throw new RemoteUnavailableError();
|
|
1796
|
+
if (response.status === 401 || response.status === 403) throw new RemoteAuthorizationError(response.status, pathname);
|
|
1797
|
+
if (!response.ok) throw new RemoteUnavailableError(response.status, pathname);
|
|
1438
1798
|
const raw = await response.json();
|
|
1439
1799
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("remote response is invalid");
|
|
1440
1800
|
return raw;
|
|
@@ -1452,11 +1812,25 @@ async function remoteStatus(origin, stateDirectory, deviceId, fetcher = fetch) {
|
|
|
1452
1812
|
return { online: value.online, ...lastSeen === void 0 ? {} : { lastSeen: Number(lastSeen) } };
|
|
1453
1813
|
}
|
|
1454
1814
|
function defaultRemoteRoots(cwd = process.cwd()) {
|
|
1455
|
-
return [{ id: "cwd", label: "Current directory", path:
|
|
1815
|
+
return [{ id: "cwd", label: "Current directory", path: path4.resolve(cwd), readOnly: false }];
|
|
1456
1816
|
}
|
|
1457
1817
|
var RemoteUnavailableError = class extends Error {
|
|
1818
|
+
constructor(httpStatus, pathname) {
|
|
1819
|
+
super("remote endpoint is unavailable");
|
|
1820
|
+
this.httpStatus = httpStatus;
|
|
1821
|
+
this.pathname = pathname;
|
|
1822
|
+
}
|
|
1823
|
+
httpStatus;
|
|
1824
|
+
pathname;
|
|
1458
1825
|
};
|
|
1459
1826
|
var RemoteAuthorizationError = class extends Error {
|
|
1827
|
+
constructor(httpStatus, pathname) {
|
|
1828
|
+
super("remote authorization was rejected");
|
|
1829
|
+
this.httpStatus = httpStatus;
|
|
1830
|
+
this.pathname = pathname;
|
|
1831
|
+
}
|
|
1832
|
+
httpStatus;
|
|
1833
|
+
pathname;
|
|
1460
1834
|
};
|
|
1461
1835
|
function canonicalOrigin2(value) {
|
|
1462
1836
|
const url = new URL(value);
|
|
@@ -1467,6 +1841,21 @@ function bounded2(value, label) {
|
|
|
1467
1841
|
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(value)) throw new TypeError(label + " is invalid");
|
|
1468
1842
|
return value;
|
|
1469
1843
|
}
|
|
1844
|
+
function noticeValue(value) {
|
|
1845
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("remote notice is invalid");
|
|
1846
|
+
const record = value;
|
|
1847
|
+
const phase = record.phase;
|
|
1848
|
+
if (phase !== "invoking" && phase !== "invoked" && phase !== "failed") throw new TypeError("remote notice phase is invalid");
|
|
1849
|
+
const summary2 = record.summary;
|
|
1850
|
+
if (summary2 !== void 0 && (!summary2 || typeof summary2 !== "object" || Array.isArray(summary2))) throw new TypeError("remote notice summary is invalid");
|
|
1851
|
+
return {
|
|
1852
|
+
tool: bounded2(record.tool, "remote notice tool"),
|
|
1853
|
+
phase,
|
|
1854
|
+
...record.providerId === void 0 ? {} : { providerId: bounded2(record.providerId, "remote notice provider") },
|
|
1855
|
+
...record.deviceId === void 0 ? {} : { deviceId: bounded2(record.deviceId, "remote notice device") },
|
|
1856
|
+
...summary2 === void 0 ? {} : { summary: summary2 }
|
|
1857
|
+
};
|
|
1858
|
+
}
|
|
1470
1859
|
function commandValue(value) {
|
|
1471
1860
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("remote command is invalid");
|
|
1472
1861
|
const record = value;
|
|
@@ -1482,7 +1871,7 @@ function elapsed(startedAt) {
|
|
|
1482
1871
|
function safeError(error) {
|
|
1483
1872
|
return error instanceof TypeError ? error.message.slice(0, 256) : "device operation failed";
|
|
1484
1873
|
}
|
|
1485
|
-
function
|
|
1874
|
+
function sleep2(ms, signal) {
|
|
1486
1875
|
return new Promise((resolve) => {
|
|
1487
1876
|
const timer = setTimeout(resolve, ms);
|
|
1488
1877
|
const abort = () => {
|
|
@@ -1495,8 +1884,8 @@ function sleep(ms, signal) {
|
|
|
1495
1884
|
|
|
1496
1885
|
// src/service.ts
|
|
1497
1886
|
import os4 from "node:os";
|
|
1498
|
-
import
|
|
1499
|
-
import { chmod, copyFile, mkdir as
|
|
1887
|
+
import path5 from "node:path";
|
|
1888
|
+
import { chmod, copyFile, mkdir as mkdir4, writeFile as writeFile4 } from "node:fs/promises";
|
|
1500
1889
|
import { execFile as execFile4 } from "node:child_process";
|
|
1501
1890
|
import { promisify as promisify4 } from "node:util";
|
|
1502
1891
|
var execute4 = promisify4(execFile4);
|
|
@@ -1504,8 +1893,8 @@ async function installRemoteService(origin, stateDirectory) {
|
|
|
1504
1893
|
const command = process.execPath;
|
|
1505
1894
|
const source = process.argv[1];
|
|
1506
1895
|
if (!source) throw new TypeError("CLI executable path is unavailable");
|
|
1507
|
-
await
|
|
1508
|
-
const script =
|
|
1896
|
+
await mkdir4(stateDirectory, { recursive: true, mode: 448 });
|
|
1897
|
+
const script = path5.join(stateDirectory, "uap-device-control.mjs");
|
|
1509
1898
|
await copyFile(source, script);
|
|
1510
1899
|
if (process.platform !== "win32") await chmod(script, 448);
|
|
1511
1900
|
const args = [script, "remote", "--origin", origin, "--state-dir", stateDirectory, "--service"];
|
|
@@ -1515,10 +1904,10 @@ async function installRemoteService(origin, stateDirectory) {
|
|
|
1515
1904
|
throw new TypeError("service installation is unsupported on this platform");
|
|
1516
1905
|
}
|
|
1517
1906
|
async function installSystemd(command, args) {
|
|
1518
|
-
const directory =
|
|
1519
|
-
const location =
|
|
1520
|
-
await
|
|
1521
|
-
await
|
|
1907
|
+
const directory = path5.join(os4.homedir(), ".config", "systemd", "user");
|
|
1908
|
+
const location = path5.join(directory, "uap-device-control.service");
|
|
1909
|
+
await mkdir4(directory, { recursive: true });
|
|
1910
|
+
await writeFile4(
|
|
1522
1911
|
location,
|
|
1523
1912
|
[
|
|
1524
1913
|
"[Unit]",
|
|
@@ -1543,12 +1932,12 @@ async function installSystemd(command, args) {
|
|
|
1543
1932
|
return { platform: "linux", location };
|
|
1544
1933
|
}
|
|
1545
1934
|
async function installLaunchd(command, args) {
|
|
1546
|
-
const directory =
|
|
1547
|
-
const location =
|
|
1548
|
-
await
|
|
1935
|
+
const directory = path5.join(os4.homedir(), "Library", "LaunchAgents");
|
|
1936
|
+
const location = path5.join(directory, "ro.codingfrees.uap-device-control.plist");
|
|
1937
|
+
await mkdir4(directory, { recursive: true });
|
|
1549
1938
|
const escaped = [command, ...args].map((value) => "<string>" + xml(value) + "</string>").join("");
|
|
1550
1939
|
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
|
|
1940
|
+
await writeFile4(location, plist, { mode: 384 });
|
|
1552
1941
|
const domain = "gui/" + process.getuid?.();
|
|
1553
1942
|
await execute4("launchctl", ["bootout", domain, location]).catch(() => void 0);
|
|
1554
1943
|
await execute4("launchctl", ["bootstrap", domain, location]);
|
|
@@ -1582,6 +1971,9 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
|
|
|
1582
1971
|
const allowedExecutables = [];
|
|
1583
1972
|
const allowedServices = [];
|
|
1584
1973
|
let service = false;
|
|
1974
|
+
let browserControl = true;
|
|
1975
|
+
let browserPort = 8800;
|
|
1976
|
+
let json2 = false;
|
|
1585
1977
|
for (let index = 1; index < args.length; index++) {
|
|
1586
1978
|
const option = args[index];
|
|
1587
1979
|
const value = args[index + 1];
|
|
@@ -1591,25 +1983,40 @@ function parseDeviceControlArguments(args, cwd = process.cwd()) {
|
|
|
1591
1983
|
roots.push(root(required(value, option), option === "--read-only-root"));
|
|
1592
1984
|
index++;
|
|
1593
1985
|
} else if (option === "--allow-executable") allowedExecutables.push(absolute(value, option)), index++;
|
|
1594
|
-
else if (option === "--allow-service") allowedServices.push(
|
|
1986
|
+
else if (option === "--allow-service") allowedServices.push(identifier2(value, option)), index++;
|
|
1595
1987
|
else if (option === "--service") service = true;
|
|
1988
|
+
else if (option === "--no-browser-control") browserControl = false;
|
|
1989
|
+
else if (option === "--browser-port") browserPort = port(value, option), index++;
|
|
1990
|
+
else if (option === "--json") json2 = true;
|
|
1596
1991
|
else throw new TypeError("unsupported UAP Device Control option: " + option);
|
|
1597
1992
|
}
|
|
1598
1993
|
const normalizedOrigin = origin === void 0 ? void 0 : canonicalOrigin3(origin);
|
|
1599
1994
|
if (!roots.length && command === "remote") roots.push(...defaultRemoteRoots(cwd));
|
|
1600
|
-
return {
|
|
1995
|
+
return {
|
|
1996
|
+
command,
|
|
1997
|
+
...normalizedOrigin ? { origin: normalizedOrigin } : {},
|
|
1998
|
+
stateDirectory,
|
|
1999
|
+
roots,
|
|
2000
|
+
allowedExecutables,
|
|
2001
|
+
allowedServices,
|
|
2002
|
+
service,
|
|
2003
|
+
browserControl,
|
|
2004
|
+
browserPort,
|
|
2005
|
+
json: json2
|
|
2006
|
+
};
|
|
1601
2007
|
}
|
|
1602
2008
|
async function runDeviceControlCli(args = process.argv.slice(2)) {
|
|
1603
2009
|
const config = parseDeviceControlArguments(args);
|
|
1604
2010
|
const existingAuth = await loadRemoteAuth(config.stateDirectory);
|
|
1605
2011
|
const resolvedOrigin = resolveConfiguredOrigin(config.origin, existingAuth?.origin);
|
|
2012
|
+
const output = (event) => process.stdout.write(formatCliEvent(event, config.json) + "\n");
|
|
1606
2013
|
if (config.command === "login") {
|
|
1607
2014
|
const auth = await loginDeviceControl(resolvedOrigin, config.stateDirectory);
|
|
1608
|
-
|
|
2015
|
+
output({ status: "authenticated", origin: auth.origin });
|
|
1609
2016
|
return;
|
|
1610
2017
|
}
|
|
1611
2018
|
if (config.command === "logout") {
|
|
1612
|
-
|
|
2019
|
+
output({ status: await logoutDeviceControl(config.stateDirectory) ? "logged-out" : "not-logged-in" });
|
|
1613
2020
|
return;
|
|
1614
2021
|
}
|
|
1615
2022
|
if (config.command === "status") {
|
|
@@ -1617,25 +2024,75 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
|
|
|
1617
2024
|
const deviceAuthorized = Boolean(auth?.scope.split(" ").includes("device-control:device"));
|
|
1618
2025
|
let remote;
|
|
1619
2026
|
if (auth && deviceAuthorized) remote = await remoteStatus(auth.origin, config.stateDirectory, deviceId).catch(() => ({ online: false }));
|
|
1620
|
-
process.
|
|
1621
|
-
JSON.stringify({ deviceId, origin: auth?.origin ?? resolvedOrigin, authenticated: Boolean(auth), deviceAuthorized, remote: remote ?? null, serviceMode: config.service, platform: process.platform }) + "\n"
|
|
1622
|
-
);
|
|
2027
|
+
output({ deviceId, origin: auth?.origin ?? resolvedOrigin, authenticated: Boolean(auth), deviceAuthorized, remote: remote ?? null, serviceMode: config.service, platform: process.platform });
|
|
1623
2028
|
return;
|
|
1624
2029
|
}
|
|
1625
2030
|
if (config.command === "install-service") {
|
|
1626
2031
|
if (!existingAuth) throw new TypeError("login is required before install-service");
|
|
1627
|
-
|
|
2032
|
+
output({ status: "installed", ...await installRemoteService(resolvedOrigin, config.stateDirectory) });
|
|
1628
2033
|
return;
|
|
1629
2034
|
}
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
2035
|
+
const lease = await acquireRemoteProcessLock(config.stateDirectory);
|
|
2036
|
+
try {
|
|
2037
|
+
if (!existingAuth) {
|
|
2038
|
+
if (config.service) throw new TypeError("service mode requires login");
|
|
2039
|
+
await loginDeviceControl(resolvedOrigin, config.stateDirectory);
|
|
2040
|
+
}
|
|
2041
|
+
const controller = new AbortController();
|
|
2042
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => controller.abort());
|
|
2043
|
+
const remoteOrigin = resolvedOrigin;
|
|
2044
|
+
output({ status: "connecting", origin: remoteOrigin, platform: process.platform });
|
|
2045
|
+
await runRemote({
|
|
2046
|
+
origin: remoteOrigin,
|
|
2047
|
+
stateDirectory: config.stateDirectory,
|
|
2048
|
+
roots: config.roots,
|
|
2049
|
+
allowedExecutables: config.allowedExecutables,
|
|
2050
|
+
allowedServices: config.allowedServices,
|
|
2051
|
+
browserControl: config.browserControl,
|
|
2052
|
+
browserPort: config.browserPort,
|
|
2053
|
+
signal: controller.signal,
|
|
2054
|
+
log: output
|
|
2055
|
+
});
|
|
2056
|
+
} finally {
|
|
2057
|
+
await lease.release();
|
|
1633
2058
|
}
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
2059
|
+
}
|
|
2060
|
+
function formatCliEvent(event, json2 = false) {
|
|
2061
|
+
if (json2) return JSON.stringify(event);
|
|
2062
|
+
const status = String(event.status ?? "");
|
|
2063
|
+
if (event.event === "plugin.tool") {
|
|
2064
|
+
const tool = String(event.tool ?? "tool");
|
|
2065
|
+
const phase = String(event.phase ?? "");
|
|
2066
|
+
if (phase === "invoking") return "\u{1F527} " + tool + " \xB7 running";
|
|
2067
|
+
if (phase === "failed") return "\u274C " + tool + " \xB7 failed";
|
|
2068
|
+
const summary2 = event.summary && typeof event.summary === "object" ? " \xB7 " + JSON.stringify(event.summary) : "";
|
|
2069
|
+
return "\u2705 " + tool + " \xB7 completed" + summary2;
|
|
2070
|
+
}
|
|
2071
|
+
if (event.event === "browser.bridge") {
|
|
2072
|
+
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");
|
|
2073
|
+
if (status === "pairing-required") return "\u{1F510} Browser pairing code: " + String(event.pairingCode) + " \xB7 port " + String(event.port);
|
|
2074
|
+
if (status === "paired") return "\u2705 UAP Browser Extension paired";
|
|
2075
|
+
if (status === "connected") return "\u{1F310} UAP Browser Extension connected";
|
|
2076
|
+
if (status === "unpaired") return "\u{1F50C} UAP Browser Extension unpaired";
|
|
2077
|
+
}
|
|
2078
|
+
if (event.event === "remote.session") {
|
|
2079
|
+
if (status === "connected") return "\u2705 Device connected \xB7 " + String(event.deviceId);
|
|
2080
|
+
if (status === "disconnected") return "\u{1F50C} Device disconnected \xB7 " + String(event.deviceId);
|
|
2081
|
+
if (status === "reconnecting") return "\u26A0\uFE0F Connection interrupted" + httpDetail(event) + " \xB7 retrying in " + String(event.retryMs) + " ms";
|
|
2082
|
+
if (status === "reauthorizing") return "\u{1F510} Refreshing Device Control authorization" + httpDetail(event);
|
|
2083
|
+
}
|
|
2084
|
+
if (status === "connecting") return "\u{1F310} Connecting to " + String(event.origin) + " \xB7 " + String(event.platform);
|
|
2085
|
+
if (status === "authenticated") return "\u2705 Authenticated \xB7 " + String(event.origin);
|
|
2086
|
+
if (status === "logged-out") return "\u2705 Logged out";
|
|
2087
|
+
if (status === "not-logged-in") return "\u26A0\uFE0F Not logged in";
|
|
2088
|
+
if (status === "installed") return "\u2705 Remote service installed";
|
|
2089
|
+
if ("authenticated" in event) return (event.authenticated ? "\u2705" : "\u26A0\uFE0F") + " Device " + String(event.deviceId) + " \xB7 " + String(event.origin) + " \xB7 remote=" + JSON.stringify(event.remote);
|
|
2090
|
+
return "\u2139\uFE0F " + JSON.stringify(event);
|
|
2091
|
+
}
|
|
2092
|
+
function httpDetail(event) {
|
|
2093
|
+
const status = Number(event.httpStatus);
|
|
2094
|
+
const pathname = typeof event.pathname === "string" && /^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]{1,255}$/.test(event.pathname) ? event.pathname : "";
|
|
2095
|
+
return Number.isInteger(status) && status >= 100 && status <= 599 ? " \xB7 HTTP " + status + (pathname ? " " + pathname : "") : pathname ? " \xB7 " + pathname : "";
|
|
1639
2096
|
}
|
|
1640
2097
|
function resolveConfiguredOrigin(explicit, stored) {
|
|
1641
2098
|
if (explicit && stored && explicit !== stored) throw new TypeError("configured origin does not match the authenticated origin; logout before changing environments");
|
|
@@ -1652,10 +2109,15 @@ function required(value, label) {
|
|
|
1652
2109
|
}
|
|
1653
2110
|
function absolute(value, label) {
|
|
1654
2111
|
const resolved = required(value, label);
|
|
1655
|
-
if (!
|
|
1656
|
-
return
|
|
2112
|
+
if (!path6.isAbsolute(resolved)) throw new TypeError(label + " must be absolute");
|
|
2113
|
+
return path6.resolve(resolved);
|
|
1657
2114
|
}
|
|
1658
|
-
function
|
|
2115
|
+
function port(value, label) {
|
|
2116
|
+
const result = Number(required(value, label));
|
|
2117
|
+
if (!Number.isInteger(result) || result < 1024 || result > 65535) throw new TypeError(label + " is invalid");
|
|
2118
|
+
return result;
|
|
2119
|
+
}
|
|
2120
|
+
function identifier2(value, label) {
|
|
1659
2121
|
const result = required(value, label);
|
|
1660
2122
|
if (!/^[A-Za-z0-9_.@:-]{1,256}$/.test(result)) throw new TypeError(label + " is invalid");
|
|
1661
2123
|
return result;
|
|
@@ -1663,12 +2125,13 @@ function identifier(value, label) {
|
|
|
1663
2125
|
function root(value, readOnly) {
|
|
1664
2126
|
const split = value.indexOf("=");
|
|
1665
2127
|
if (split < 1) throw new TypeError("root must use id=absolute-path");
|
|
1666
|
-
const id =
|
|
2128
|
+
const id = identifier2(value.slice(0, split), "root id");
|
|
1667
2129
|
return { id, label: id, path: absolute(value.slice(split + 1), "root path"), readOnly };
|
|
1668
2130
|
}
|
|
1669
2131
|
|
|
1670
2132
|
// src/bin.ts
|
|
1671
2133
|
runDeviceControlCli().catch((error) => {
|
|
1672
|
-
|
|
2134
|
+
const message = error instanceof Error ? error.message : "UAP Device Control failed";
|
|
2135
|
+
process.stderr.write(process.argv.includes("--json") ? JSON.stringify({ error: message }) + "\n" : "\u274C " + message + "\n");
|
|
1673
2136
|
process.exitCode = 1;
|
|
1674
2137
|
});
|