@codingfrees/uap-device-control 0.0.0-stage → 0.1.2
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 +66 -2
- package/dist/uap-device-control.mjs +1620 -0
- package/package.json +20 -4
|
@@ -0,0 +1,1620 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import path5 from "node:path";
|
|
5
|
+
|
|
6
|
+
// src/auth.ts
|
|
7
|
+
import { createServer } from "node:http";
|
|
8
|
+
import { execFile } from "node:child_process";
|
|
9
|
+
import { promisify } from "node:util";
|
|
10
|
+
|
|
11
|
+
// ../../packages/web-crypto/src/index.ts
|
|
12
|
+
var encoder = new TextEncoder();
|
|
13
|
+
function randomBytes(length) {
|
|
14
|
+
if (!Number.isInteger(length) || length < 1 || length > 4096) {
|
|
15
|
+
throw new TypeError("random byte length is invalid");
|
|
16
|
+
}
|
|
17
|
+
const bytes = new Uint8Array(length);
|
|
18
|
+
crypto.getRandomValues(bytes);
|
|
19
|
+
return bytes;
|
|
20
|
+
}
|
|
21
|
+
async function sha256Bytes(value) {
|
|
22
|
+
const input = typeof value === "string" ? encoder.encode(value) : value;
|
|
23
|
+
if (!isUint8Array(input)) {
|
|
24
|
+
throw new TypeError("SHA-256 input is invalid");
|
|
25
|
+
}
|
|
26
|
+
const digestInput = new Uint8Array(input.byteLength);
|
|
27
|
+
digestInput.set(input);
|
|
28
|
+
return new Uint8Array(await crypto.subtle.digest("SHA-256", digestInput.buffer));
|
|
29
|
+
}
|
|
30
|
+
function base64EncodeBytes(bytes) {
|
|
31
|
+
if (!isUint8Array(bytes)) {
|
|
32
|
+
throw new TypeError("base64 input is invalid");
|
|
33
|
+
}
|
|
34
|
+
let binary = "";
|
|
35
|
+
const chunkSize = 32768;
|
|
36
|
+
for (let offset = 0; offset < bytes.length; offset += chunkSize) {
|
|
37
|
+
binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
|
|
38
|
+
}
|
|
39
|
+
return btoa(binary);
|
|
40
|
+
}
|
|
41
|
+
function isUint8Array(value) {
|
|
42
|
+
return ArrayBuffer.isView(value) && Object.prototype.toString.call(value) === "[object Uint8Array]";
|
|
43
|
+
}
|
|
44
|
+
function base64UrlEncodeBytes(bytes) {
|
|
45
|
+
return base64EncodeBytes(bytes).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/g, "");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ../../packages/oauth-pkce/src/index.ts
|
|
49
|
+
async function createOAuthPkce() {
|
|
50
|
+
for (let attempt = 0; attempt < 32; attempt += 1) {
|
|
51
|
+
const verifier = base64UrlEncodeBytes(randomBytes(32));
|
|
52
|
+
const challenge = base64UrlEncodeBytes(await sha256Bytes(verifier));
|
|
53
|
+
if (/^[A-Za-z0-9]/.test(challenge)) {
|
|
54
|
+
return { state: base64UrlEncodeBytes(randomBytes(32)), verifier, challenge };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
throw new Error("OAuth PKCE generation failed");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/state.ts
|
|
61
|
+
import os from "node:os";
|
|
62
|
+
import path from "node:path";
|
|
63
|
+
import { mkdir, readFile, rm, rename, writeFile } from "node:fs/promises";
|
|
64
|
+
import { randomUUID } from "node:crypto";
|
|
65
|
+
function defaultDeviceControlStateDirectory(home = os.homedir(), platform = process.platform) {
|
|
66
|
+
if (platform === "win32") return path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "UAP", "DeviceControl");
|
|
67
|
+
if (platform === "darwin") return path.join(home, "Library", "Application Support", "UAP", "DeviceControl");
|
|
68
|
+
return path.join(process.env.XDG_STATE_HOME || path.join(home, ".local", "state"), "uap", "device-control");
|
|
69
|
+
}
|
|
70
|
+
async function loadRemoteDeviceId(stateDirectory) {
|
|
71
|
+
await mkdir(stateDirectory, { recursive: true, mode: 448 });
|
|
72
|
+
const file = path.join(stateDirectory, "device-id");
|
|
73
|
+
try {
|
|
74
|
+
const value = (await readFile(file, "utf8")).trim();
|
|
75
|
+
if (!/^device-[0-9a-f-]{36}$/.test(value)) throw new TypeError("stored device id is invalid");
|
|
76
|
+
return value;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (!missing(error)) throw error;
|
|
79
|
+
}
|
|
80
|
+
const created = "device-" + randomUUID();
|
|
81
|
+
try {
|
|
82
|
+
await writeFile(file, created + "\n", { encoding: "utf8", flag: "wx", mode: 384 });
|
|
83
|
+
return created;
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (!exists(error)) throw error;
|
|
86
|
+
return loadRemoteDeviceId(stateDirectory);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function loadRemoteAuth(stateDirectory) {
|
|
90
|
+
try {
|
|
91
|
+
const raw = JSON.parse(await readFile(path.join(stateDirectory, "auth.json"), "utf8"));
|
|
92
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("stored remote auth is invalid");
|
|
93
|
+
const value = raw;
|
|
94
|
+
if (typeof value.origin !== "string" || typeof value.clientId !== "string" || typeof value.refreshToken !== "string" || typeof value.scope !== "string" || value.accessToken !== void 0 && typeof value.accessToken !== "string" || value.accessExpiresAt !== void 0 && !Number.isSafeInteger(value.accessExpiresAt))
|
|
95
|
+
throw new TypeError("stored remote auth is invalid");
|
|
96
|
+
return value;
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (missing(error)) return void 0;
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async function saveRemoteAuth(stateDirectory, value) {
|
|
103
|
+
await mkdir(stateDirectory, { recursive: true, mode: 448 });
|
|
104
|
+
const target = path.join(stateDirectory, "auth.json");
|
|
105
|
+
const temporary = target + ".tmp-" + randomUUID();
|
|
106
|
+
await writeFile(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384 });
|
|
107
|
+
await rename(temporary, target);
|
|
108
|
+
}
|
|
109
|
+
async function clearRemoteAuth(stateDirectory) {
|
|
110
|
+
await rm(path.join(stateDirectory, "auth.json"), { force: true });
|
|
111
|
+
}
|
|
112
|
+
function missing(error) {
|
|
113
|
+
return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
|
|
114
|
+
}
|
|
115
|
+
function exists(error) {
|
|
116
|
+
return Boolean(error && typeof error === "object" && "code" in error && error.code === "EEXIST");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/auth.ts
|
|
120
|
+
var execute = promisify(execFile);
|
|
121
|
+
var scopes = "device-control:device offline_access";
|
|
122
|
+
async function loginDeviceControl(origin, stateDirectory, options = {}) {
|
|
123
|
+
const fetcher = options.fetcher ?? fetch;
|
|
124
|
+
const issuer = canonicalOrigin(origin);
|
|
125
|
+
const metadata = await json(fetcher(new URL("/.well-known/oauth-authorization-server", issuer), { redirect: "error", cache: "no-store" }));
|
|
126
|
+
const authorizationEndpoint = exactHttps(metadata.authorization_endpoint, issuer);
|
|
127
|
+
const tokenEndpoint = exactHttps(metadata.token_endpoint, issuer);
|
|
128
|
+
const registrationEndpoint = exactHttps(metadata.registration_endpoint, issuer);
|
|
129
|
+
const callback = await callbackServer(options.timeoutMs ?? 12e4);
|
|
130
|
+
try {
|
|
131
|
+
const registration = await json(
|
|
132
|
+
fetcher(registrationEndpoint, {
|
|
133
|
+
method: "POST",
|
|
134
|
+
headers: { "content-type": "application/json" },
|
|
135
|
+
body: JSON.stringify({ redirect_uris: [callback.redirectUri], token_endpoint_auth_method: "none", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"] })
|
|
136
|
+
})
|
|
137
|
+
);
|
|
138
|
+
const clientId = text(registration.client_id, "OAuth client id");
|
|
139
|
+
const pkce = await createOAuthPkce();
|
|
140
|
+
const authorize = new URL(authorizationEndpoint);
|
|
141
|
+
authorize.searchParams.set("response_type", "code");
|
|
142
|
+
authorize.searchParams.set("client_id", clientId);
|
|
143
|
+
authorize.searchParams.set("redirect_uri", callback.redirectUri);
|
|
144
|
+
authorize.searchParams.set("resource", issuer + "/mcp");
|
|
145
|
+
authorize.searchParams.set("scope", scopes);
|
|
146
|
+
authorize.searchParams.set("state", pkce.state);
|
|
147
|
+
authorize.searchParams.set("code_challenge", pkce.challenge);
|
|
148
|
+
authorize.searchParams.set("code_challenge_method", "S256");
|
|
149
|
+
await (options.open ?? openBrowser)(authorize.href);
|
|
150
|
+
const result = await callback.result;
|
|
151
|
+
if (result.state !== pkce.state || !result.code) throw new TypeError("OAuth callback is invalid");
|
|
152
|
+
const token = await json(
|
|
153
|
+
fetcher(tokenEndpoint, {
|
|
154
|
+
method: "POST",
|
|
155
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
156
|
+
body: new URLSearchParams({ grant_type: "authorization_code", client_id: clientId, code: result.code, redirect_uri: callback.redirectUri, code_verifier: pkce.verifier, resource: issuer + "/mcp" })
|
|
157
|
+
})
|
|
158
|
+
);
|
|
159
|
+
const refreshToken = text(token.refresh_token, "OAuth refresh token");
|
|
160
|
+
const accessToken2 = text(token.access_token, "OAuth access token");
|
|
161
|
+
const expiresIn = integer(token.expires_in, "OAuth expiry");
|
|
162
|
+
const stored = { origin: issuer, clientId, refreshToken, accessToken: accessToken2, accessExpiresAt: Date.now() + expiresIn * 1e3, scope: typeof token.scope === "string" ? token.scope : scopes };
|
|
163
|
+
await saveRemoteAuth(stateDirectory, stored);
|
|
164
|
+
return stored;
|
|
165
|
+
} finally {
|
|
166
|
+
await callback.close();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async function accessToken(stateDirectory, fetcher = fetch, forceRefresh = false) {
|
|
170
|
+
const auth = await loadRemoteAuth(stateDirectory);
|
|
171
|
+
if (!auth) throw new TypeError("not logged in");
|
|
172
|
+
if (!auth.scope.split(" ").includes("device-control:device")) throw new TypeError("device authorization is required; run login again");
|
|
173
|
+
if (!forceRefresh && auth.accessToken && auth.accessExpiresAt && auth.accessExpiresAt > Date.now() + 3e4) return { auth, token: auth.accessToken };
|
|
174
|
+
const tokenEndpoint = new URL("/oauth/token", auth.origin);
|
|
175
|
+
const token = await json(
|
|
176
|
+
fetcher(tokenEndpoint, {
|
|
177
|
+
method: "POST",
|
|
178
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
179
|
+
body: new URLSearchParams({ grant_type: "refresh_token", client_id: auth.clientId, refresh_token: auth.refreshToken, resource: auth.origin + "/mcp" })
|
|
180
|
+
})
|
|
181
|
+
);
|
|
182
|
+
const next = {
|
|
183
|
+
...auth,
|
|
184
|
+
refreshToken: text(token.refresh_token, "OAuth refresh token"),
|
|
185
|
+
accessToken: text(token.access_token, "OAuth access token"),
|
|
186
|
+
accessExpiresAt: Date.now() + integer(token.expires_in, "OAuth expiry") * 1e3,
|
|
187
|
+
scope: typeof token.scope === "string" ? token.scope : auth.scope
|
|
188
|
+
};
|
|
189
|
+
await saveRemoteAuth(stateDirectory, next);
|
|
190
|
+
return { auth: next, token: next.accessToken };
|
|
191
|
+
}
|
|
192
|
+
async function logoutDeviceControl(stateDirectory, fetcher = fetch) {
|
|
193
|
+
const auth = await loadRemoteAuth(stateDirectory);
|
|
194
|
+
if (!auth) return false;
|
|
195
|
+
await fetcher(new URL("/oauth/revoke", auth.origin), {
|
|
196
|
+
method: "POST",
|
|
197
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
198
|
+
body: new URLSearchParams({ client_id: auth.clientId, token: auth.refreshToken, resource: auth.origin + "/mcp" })
|
|
199
|
+
}).catch(() => void 0);
|
|
200
|
+
await clearRemoteAuth(stateDirectory);
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
203
|
+
async function callbackServer(timeoutMs) {
|
|
204
|
+
let settle;
|
|
205
|
+
let reject;
|
|
206
|
+
const result = new Promise((resolve, rejectResult) => (settle = resolve, reject = rejectResult));
|
|
207
|
+
const server = createServer((request2, response) => {
|
|
208
|
+
const url = new URL(request2.url ?? "/", "http://127.0.0.1");
|
|
209
|
+
if (url.pathname !== "/callback") {
|
|
210
|
+
response.writeHead(404).end();
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
response.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
|
|
214
|
+
response.end("UAP Device Control login completed. You can close this window.");
|
|
215
|
+
settle({ code: url.searchParams.get("code") ?? void 0, state: url.searchParams.get("state") ?? void 0 });
|
|
216
|
+
});
|
|
217
|
+
await new Promise((resolve, rejectListen) => {
|
|
218
|
+
server.once("error", rejectListen);
|
|
219
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
220
|
+
});
|
|
221
|
+
const address = server.address();
|
|
222
|
+
if (!address || typeof address === "string") throw new TypeError("OAuth callback address is unavailable");
|
|
223
|
+
const timer = setTimeout(() => reject(new TypeError("OAuth login timed out")), timeoutMs);
|
|
224
|
+
timer.unref();
|
|
225
|
+
return {
|
|
226
|
+
redirectUri: "http://127.0.0.1:" + address.port + "/callback",
|
|
227
|
+
result,
|
|
228
|
+
close: async () => {
|
|
229
|
+
clearTimeout(timer);
|
|
230
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
async function openBrowser(url) {
|
|
235
|
+
if (process.platform === "win32") await execute("cmd.exe", ["/d", "/s", "/c", "start", "", url], { windowsHide: true });
|
|
236
|
+
else if (process.platform === "darwin") await execute("open", [url]);
|
|
237
|
+
else await execute("xdg-open", [url]);
|
|
238
|
+
}
|
|
239
|
+
async function json(response) {
|
|
240
|
+
const value = await response;
|
|
241
|
+
if (!value.ok) throw new TypeError("OAuth request failed");
|
|
242
|
+
const raw = await value.json();
|
|
243
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("OAuth response is invalid");
|
|
244
|
+
return raw;
|
|
245
|
+
}
|
|
246
|
+
function canonicalOrigin(value) {
|
|
247
|
+
const url = new URL(value);
|
|
248
|
+
if (url.protocol !== "https:" || url.origin !== value || url.username || url.password) throw new TypeError("origin must be canonical HTTPS");
|
|
249
|
+
return url.origin;
|
|
250
|
+
}
|
|
251
|
+
function exactHttps(value, origin) {
|
|
252
|
+
if (typeof value !== "string") throw new TypeError("OAuth metadata is invalid");
|
|
253
|
+
const url = new URL(value);
|
|
254
|
+
if (url.protocol !== "https:" || url.origin !== origin || url.username || url.password) throw new TypeError("OAuth metadata endpoint is invalid");
|
|
255
|
+
return url;
|
|
256
|
+
}
|
|
257
|
+
function text(value, label) {
|
|
258
|
+
if (typeof value !== "string" || !value || value.length > 8192) throw new TypeError(label + " is invalid");
|
|
259
|
+
return value;
|
|
260
|
+
}
|
|
261
|
+
function integer(value, label) {
|
|
262
|
+
const number = Number(value);
|
|
263
|
+
if (!Number.isSafeInteger(number) || number < 1 || number > 86400) throw new TypeError(label + " is invalid");
|
|
264
|
+
return number;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/remote.ts
|
|
268
|
+
import os3 from "node:os";
|
|
269
|
+
import path3 from "node:path";
|
|
270
|
+
|
|
271
|
+
// ../device-agent/src/engine.ts
|
|
272
|
+
import { spawn } from "node:child_process";
|
|
273
|
+
import { cp, mkdir as mkdir2, readdir, readFile as readFile2, realpath, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
|
|
274
|
+
import { realpathSync } from "node:fs";
|
|
275
|
+
import os2 from "node:os";
|
|
276
|
+
import path2 from "node:path";
|
|
277
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
278
|
+
var DeviceAgentEngine = class {
|
|
279
|
+
constructor(options) {
|
|
280
|
+
this.options = options;
|
|
281
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(options.deviceId)) throw new TypeError("device id is invalid");
|
|
282
|
+
this.#maxTransfer = bounded(options.maxTransferBytes ?? 8 * 1024 * 1024, 1024, 64 * 1024 * 1024, "transfer limit");
|
|
283
|
+
this.#maxOutput = bounded(options.maxOutputBytes ?? 1024 * 1024, 1024, 8 * 1024 * 1024, "output limit");
|
|
284
|
+
this.#maxProcesses = bounded(options.maxProcesses ?? 8, 1, 64, "process limit");
|
|
285
|
+
this.#maxSessions = bounded(options.maxSessions ?? 4, 1, 16, "session limit");
|
|
286
|
+
this.#sessionIdleTimeoutMs = bounded(options.sessionIdleTimeoutMs ?? 30 * 6e4, 100, 24 * 60 * 6e4, "session idle timeout");
|
|
287
|
+
this.#allowed = new Set(options.allowedExecutables ?? defaultExecutables());
|
|
288
|
+
for (const name of options.allowedServices ?? []) {
|
|
289
|
+
const normalized = serviceName(name);
|
|
290
|
+
if (this.#allowedServices.has(normalized)) throw new TypeError("duplicate allowed service");
|
|
291
|
+
this.#allowedServices.add(normalized);
|
|
292
|
+
}
|
|
293
|
+
for (const root2 of options.roots) {
|
|
294
|
+
if (this.#roots.has(root2.id) || !path2.isAbsolute(root2.path)) throw new TypeError("device root is invalid");
|
|
295
|
+
this.#roots.set(root2.id, { ...root2, readOnly: root2.readOnly === true, path: realpathSync(path2.resolve(root2.path)) });
|
|
296
|
+
}
|
|
297
|
+
this.capabilities = [
|
|
298
|
+
"device.info",
|
|
299
|
+
"device.health",
|
|
300
|
+
"filesystem.roots",
|
|
301
|
+
"filesystem.list",
|
|
302
|
+
"filesystem.metadata",
|
|
303
|
+
"filesystem.preview",
|
|
304
|
+
"filesystem.read",
|
|
305
|
+
"filesystem.write",
|
|
306
|
+
"filesystem.mkdir",
|
|
307
|
+
"filesystem.move",
|
|
308
|
+
"filesystem.copy",
|
|
309
|
+
"filesystem.delete",
|
|
310
|
+
"filesystem.upload",
|
|
311
|
+
"filesystem.download",
|
|
312
|
+
"process.list",
|
|
313
|
+
"process.start",
|
|
314
|
+
"process.stop",
|
|
315
|
+
"process.output",
|
|
316
|
+
"terminal.exec",
|
|
317
|
+
"terminal.session",
|
|
318
|
+
...options.services && this.#allowedServices.size ? ["service.read", "service.control"] : [],
|
|
319
|
+
...options.captureScreen ? ["screen.capture", "screen.stream"] : [],
|
|
320
|
+
...options.monitors ? ["screen.monitors"] : [],
|
|
321
|
+
...options.pointer ? ["pointer.control"] : [],
|
|
322
|
+
...options.keyboard ? ["keyboard.control"] : [],
|
|
323
|
+
...options.readClipboard ? ["clipboard.read"] : [],
|
|
324
|
+
...options.writeClipboard ? ["clipboard.write"] : []
|
|
325
|
+
];
|
|
326
|
+
}
|
|
327
|
+
options;
|
|
328
|
+
capabilities;
|
|
329
|
+
#roots = /* @__PURE__ */ new Map();
|
|
330
|
+
#processes = /* @__PURE__ */ new Map();
|
|
331
|
+
#oneShots = /* @__PURE__ */ new Map();
|
|
332
|
+
#sessions = /* @__PURE__ */ new Map();
|
|
333
|
+
#screenSessions = /* @__PURE__ */ new Map();
|
|
334
|
+
#maxTransfer;
|
|
335
|
+
#maxOutput;
|
|
336
|
+
#maxProcesses;
|
|
337
|
+
#maxSessions;
|
|
338
|
+
#sessionIdleTimeoutMs;
|
|
339
|
+
#allowed;
|
|
340
|
+
#allowedServices = /* @__PURE__ */ new Set();
|
|
341
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
342
|
+
info() {
|
|
343
|
+
return {
|
|
344
|
+
deviceId: this.options.deviceId,
|
|
345
|
+
name: this.options.name ?? os2.hostname(),
|
|
346
|
+
status: "online",
|
|
347
|
+
os: os2.platform(),
|
|
348
|
+
architecture: os2.arch(),
|
|
349
|
+
agentVersion: "0.1.0",
|
|
350
|
+
lastSeen: Date.now(),
|
|
351
|
+
capabilities: [...this.capabilities],
|
|
352
|
+
activeSessions: this.#sessions.size
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
close() {
|
|
356
|
+
this.panicStop();
|
|
357
|
+
this.#listeners.clear();
|
|
358
|
+
}
|
|
359
|
+
panicStop() {
|
|
360
|
+
const activity = { processes: this.#processes.size, oneShotCommands: this.#oneShots.size, terminalSessions: this.#sessions.size, screenSessions: this.#screenSessions.size };
|
|
361
|
+
for (const value of [...this.#processes.values(), ...this.#oneShots.values()]) {
|
|
362
|
+
if (value.exitCode === null) value.child.kill("SIGKILL");
|
|
363
|
+
value.child.stdin.destroy();
|
|
364
|
+
value.child.stdout.destroy();
|
|
365
|
+
value.child.stderr.destroy();
|
|
366
|
+
}
|
|
367
|
+
for (const value of this.#sessions.values()) {
|
|
368
|
+
if (value.idleTimer) clearTimeout(value.idleTimer);
|
|
369
|
+
if (value.exitCode === null) value.child.kill("SIGKILL");
|
|
370
|
+
value.child.stdin.destroy();
|
|
371
|
+
value.child.stdout.destroy();
|
|
372
|
+
value.child.stderr.destroy();
|
|
373
|
+
}
|
|
374
|
+
this.#processes.clear();
|
|
375
|
+
this.#oneShots.clear();
|
|
376
|
+
this.#sessions.clear();
|
|
377
|
+
for (const session of this.#screenSessions.values()) {
|
|
378
|
+
clearTimeout(session.timer);
|
|
379
|
+
if (session.idleTimer) clearTimeout(session.idleTimer);
|
|
380
|
+
}
|
|
381
|
+
this.#screenSessions.clear();
|
|
382
|
+
this.#emit("device-agent.panic-stop", "device.health", activity);
|
|
383
|
+
return activity;
|
|
384
|
+
}
|
|
385
|
+
subscribe(listener) {
|
|
386
|
+
this.#listeners.add(listener);
|
|
387
|
+
return () => this.#listeners.delete(listener);
|
|
388
|
+
}
|
|
389
|
+
revokeWorkspace(workspaceId) {
|
|
390
|
+
const owner = executionWorkspaceId(workspaceId);
|
|
391
|
+
if (!owner) throw new TypeError("workspace id is required");
|
|
392
|
+
let processes = 0;
|
|
393
|
+
let oneShotCommands = 0;
|
|
394
|
+
let terminalSessions = 0;
|
|
395
|
+
let screenSessions = 0;
|
|
396
|
+
for (const [id, value] of [...this.#processes]) {
|
|
397
|
+
if (value.workspaceId !== owner) continue;
|
|
398
|
+
this.#processes.delete(id);
|
|
399
|
+
if (value.exitCode === null) value.child.kill("SIGKILL");
|
|
400
|
+
value.child.stdin.destroy();
|
|
401
|
+
processes++;
|
|
402
|
+
}
|
|
403
|
+
for (const [id, value] of [...this.#oneShots]) {
|
|
404
|
+
if (value.workspaceId !== owner) continue;
|
|
405
|
+
this.#oneShots.delete(id);
|
|
406
|
+
if (value.exitCode === null) value.child.kill("SIGKILL");
|
|
407
|
+
value.child.stdin.destroy();
|
|
408
|
+
oneShotCommands++;
|
|
409
|
+
}
|
|
410
|
+
for (const [id, value] of [...this.#sessions]) {
|
|
411
|
+
if (value.workspaceId !== owner) continue;
|
|
412
|
+
this.#sessions.delete(id);
|
|
413
|
+
if (value.idleTimer) clearTimeout(value.idleTimer);
|
|
414
|
+
value.idleTimer = null;
|
|
415
|
+
if (value.exitCode === null) value.child.kill("SIGKILL");
|
|
416
|
+
value.child.stdin.destroy();
|
|
417
|
+
terminalSessions++;
|
|
418
|
+
}
|
|
419
|
+
for (const [id, session] of [...this.#screenSessions]) {
|
|
420
|
+
if (session.workspaceId !== owner) continue;
|
|
421
|
+
this.#screenSessions.delete(id);
|
|
422
|
+
clearTimeout(session.timer);
|
|
423
|
+
if (session.idleTimer) clearTimeout(session.idleTimer);
|
|
424
|
+
session.idleTimer = null;
|
|
425
|
+
screenSessions++;
|
|
426
|
+
}
|
|
427
|
+
return { processes, oneShotCommands, terminalSessions, screenSessions };
|
|
428
|
+
}
|
|
429
|
+
async execute(capability, input, context = {}) {
|
|
430
|
+
if (!this.capabilities.includes(capability)) throw new TypeError("device capability is unavailable");
|
|
431
|
+
const workspaceId = executionWorkspaceId(context.workspaceId);
|
|
432
|
+
if (capability === "device.info" || capability === "device.health") return this.info();
|
|
433
|
+
if (capability.startsWith("filesystem.")) {
|
|
434
|
+
const output = await this.#filesystem(capability, input);
|
|
435
|
+
if (["filesystem.write", "filesystem.mkdir", "filesystem.move", "filesystem.copy", "filesystem.delete", "filesystem.upload"].includes(capability))
|
|
436
|
+
this.#emit("device-agent.filesystem.mutated", capability, { rootId: String(input.rootId), path: String(input.path ?? input.relativePath ?? "") }, workspaceId);
|
|
437
|
+
return output;
|
|
438
|
+
}
|
|
439
|
+
if (capability === "terminal.exec") return this.#oneShot(input, workspaceId);
|
|
440
|
+
if (capability.startsWith("process.")) return this.#process(capability, input, workspaceId);
|
|
441
|
+
if (capability === "terminal.session") return this.#terminal(input, workspaceId);
|
|
442
|
+
if ((capability === "service.read" || capability === "service.control") && this.options.services) {
|
|
443
|
+
const name = serviceName(input.name);
|
|
444
|
+
if (!this.#allowedServices.has(name)) throw new TypeError("service is unavailable");
|
|
445
|
+
return capability === "service.read" ? this.options.services.read(name) : this.options.services.control(name, serviceOperation(input.operation));
|
|
446
|
+
}
|
|
447
|
+
if (capability === "screen.monitors" && this.options.monitors) return { monitors: await this.options.monitors() };
|
|
448
|
+
if (capability === "screen.capture" && this.options.captureScreen) {
|
|
449
|
+
const format = screenFormat(input.format);
|
|
450
|
+
return this.options.captureScreen(optionalText(input.monitorId, 128, "monitor id"), { format, quality: screenQuality(input.quality, format) });
|
|
451
|
+
}
|
|
452
|
+
if (capability === "screen.stream" && this.options.captureScreen) {
|
|
453
|
+
const output = await this.#screen(input, workspaceId);
|
|
454
|
+
this.#emit("device-agent.screen.session", capability, { operation: String(input.operation), output }, workspaceId);
|
|
455
|
+
return output;
|
|
456
|
+
}
|
|
457
|
+
if (capability === "pointer.control" && this.options.pointer) {
|
|
458
|
+
await this.options.pointer(input);
|
|
459
|
+
return { accepted: true };
|
|
460
|
+
}
|
|
461
|
+
if (capability === "keyboard.control" && this.options.keyboard) {
|
|
462
|
+
await this.options.keyboard(input);
|
|
463
|
+
return { accepted: true };
|
|
464
|
+
}
|
|
465
|
+
if (capability === "clipboard.read" && this.options.readClipboard) return this.options.readClipboard();
|
|
466
|
+
if (capability === "clipboard.write" && this.options.writeClipboard) {
|
|
467
|
+
await this.options.writeClipboard(clipboardText(input.text));
|
|
468
|
+
return { accepted: true };
|
|
469
|
+
}
|
|
470
|
+
throw new TypeError("device capability is unavailable");
|
|
471
|
+
}
|
|
472
|
+
async #filesystem(capability, input) {
|
|
473
|
+
if (capability === "filesystem.roots") return { roots: [...this.#roots.values()].map(({ path: _path, ...root3 }) => root3) };
|
|
474
|
+
const root2 = this.#root(input.rootId);
|
|
475
|
+
const relative = safeRelative(input.path ?? input.relativePath ?? "", capability === "filesystem.list");
|
|
476
|
+
const target = capability === "filesystem.write" || capability === "filesystem.upload" || capability === "filesystem.mkdir" ? await safeWritable(root2.path, relative) : await safeExisting(root2.path, relative);
|
|
477
|
+
if (capability === "filesystem.list") {
|
|
478
|
+
const entries = await readdir(target, { withFileTypes: true });
|
|
479
|
+
return {
|
|
480
|
+
entries: await Promise.all(
|
|
481
|
+
entries.slice(0, 2e3).map(async (entry) => {
|
|
482
|
+
const value = await stat(path2.join(target, entry.name));
|
|
483
|
+
return { name: entry.name, path: path2.posix.join(relative.replaceAll("\\", "/"), entry.name), kind: entry.isDirectory() ? "directory" : "file", size: value.size, modifiedAt: value.mtimeMs };
|
|
484
|
+
})
|
|
485
|
+
)
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
if (capability === "filesystem.metadata") {
|
|
489
|
+
const value = await stat(target);
|
|
490
|
+
return { path: relative, kind: value.isDirectory() ? "directory" : "file", size: value.size, modifiedAt: value.mtimeMs, createdAt: value.birthtimeMs };
|
|
491
|
+
}
|
|
492
|
+
if (capability === "filesystem.read" || capability === "filesystem.download" || capability === "filesystem.preview") {
|
|
493
|
+
const data = await readFile2(target);
|
|
494
|
+
if (data.byteLength > this.#maxTransfer) throw new TypeError("file exceeds transfer limit");
|
|
495
|
+
return { contentBase64: data.toString("base64"), size: data.byteLength, ...capability === "filesystem.preview" ? { preview: data.subarray(0, 64 * 1024).toString("utf8") } : {} };
|
|
496
|
+
}
|
|
497
|
+
if (root2.readOnly) throw new TypeError("device root is read only");
|
|
498
|
+
if (capability === "filesystem.write" || capability === "filesystem.upload") {
|
|
499
|
+
const data = decodeBase64(input.contentBase64, this.#maxTransfer);
|
|
500
|
+
await writeFile2(target, data);
|
|
501
|
+
return { written: data.byteLength };
|
|
502
|
+
}
|
|
503
|
+
if (capability === "filesystem.mkdir") {
|
|
504
|
+
await mkdir2(target);
|
|
505
|
+
return { created: true };
|
|
506
|
+
}
|
|
507
|
+
if (capability === "filesystem.delete") {
|
|
508
|
+
await rm2(target, { recursive: input.recursive === true, force: false });
|
|
509
|
+
return { deleted: true };
|
|
510
|
+
}
|
|
511
|
+
const destination = await safeWritable(root2.path, safeRelative(input.destinationPath, false));
|
|
512
|
+
if (capability === "filesystem.move") {
|
|
513
|
+
await rename2(target, destination);
|
|
514
|
+
return { moved: true };
|
|
515
|
+
}
|
|
516
|
+
if (capability === "filesystem.copy") {
|
|
517
|
+
await cp(target, destination, { recursive: input.recursive === true, errorOnExist: true });
|
|
518
|
+
return { copied: true };
|
|
519
|
+
}
|
|
520
|
+
throw new TypeError("filesystem capability is unavailable");
|
|
521
|
+
}
|
|
522
|
+
async #oneShot(input, workspaceId) {
|
|
523
|
+
const startedAt = Date.now();
|
|
524
|
+
const process2 = this.#spawn(input, false, workspaceId);
|
|
525
|
+
process2.capability = "terminal.exec";
|
|
526
|
+
this.#oneShots.set(process2.id, process2);
|
|
527
|
+
const timeoutMs = bounded(Number(input.timeoutMs ?? 3e4), 100, 12e4, "command timeout");
|
|
528
|
+
try {
|
|
529
|
+
const timedOut = await new Promise((resolve) => {
|
|
530
|
+
const timer = setTimeout(() => {
|
|
531
|
+
process2.child.kill();
|
|
532
|
+
resolve(true);
|
|
533
|
+
}, timeoutMs);
|
|
534
|
+
process2.child.once("close", () => {
|
|
535
|
+
clearTimeout(timer);
|
|
536
|
+
resolve(false);
|
|
537
|
+
});
|
|
538
|
+
});
|
|
539
|
+
return { exitCode: process2.exitCode, stdout: process2.stdout, stderr: process2.stderr, duration: Date.now() - startedAt, truncated: process2.truncated, timedOut };
|
|
540
|
+
} finally {
|
|
541
|
+
this.#oneShots.delete(process2.id);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
async #process(capability, input, workspaceId) {
|
|
545
|
+
this.#prune();
|
|
546
|
+
if (capability === "process.list") return { processes: [...this.#processes.values()].filter((value2) => value2.workspaceId === workspaceId).map(summary) };
|
|
547
|
+
if (capability === "process.start") {
|
|
548
|
+
if (this.#running(this.#processes) >= this.#maxProcesses) throw new TypeError("process limit reached");
|
|
549
|
+
const value2 = this.#spawn(input, false, workspaceId);
|
|
550
|
+
this.#processes.set(value2.id, value2);
|
|
551
|
+
return summary(value2);
|
|
552
|
+
}
|
|
553
|
+
const value = this.#ownedRecord(this.#processes, input.processId, workspaceId, "process");
|
|
554
|
+
if (capability === "process.stop") {
|
|
555
|
+
value.child.kill();
|
|
556
|
+
return { stopped: true };
|
|
557
|
+
}
|
|
558
|
+
return summary(value);
|
|
559
|
+
}
|
|
560
|
+
async #terminal(input, workspaceId) {
|
|
561
|
+
const operation = String(input.operation);
|
|
562
|
+
if (operation === "start") {
|
|
563
|
+
if (this.#running(this.#sessions) >= this.#maxSessions) throw new TypeError("terminal session limit reached");
|
|
564
|
+
const value2 = this.#spawn(input, true, workspaceId);
|
|
565
|
+
value2.lastActivityAt = Date.now();
|
|
566
|
+
value2.expiresAt = value2.lastActivityAt + this.#sessionIdleTimeoutMs;
|
|
567
|
+
value2.idleTimer = null;
|
|
568
|
+
this.#sessions.set(value2.id, value2);
|
|
569
|
+
this.#touchTerminalSession(value2);
|
|
570
|
+
return sessionSummary(value2);
|
|
571
|
+
}
|
|
572
|
+
const value = this.#ownedRecord(this.#sessions, input.sessionId, workspaceId, "terminal session");
|
|
573
|
+
if (operation === "close") {
|
|
574
|
+
if (value.idleTimer) clearTimeout(value.idleTimer);
|
|
575
|
+
value.idleTimer = null;
|
|
576
|
+
this.#sessions.delete(value.id);
|
|
577
|
+
if (value.exitCode === null) value.child.kill();
|
|
578
|
+
value.child.stdin.destroy();
|
|
579
|
+
return { closed: true };
|
|
580
|
+
}
|
|
581
|
+
if (operation === "input") {
|
|
582
|
+
this.#touchTerminalSession(value);
|
|
583
|
+
const data = text2(input.data, 65536, "terminal input");
|
|
584
|
+
value.child.stdin.write(data);
|
|
585
|
+
return { accepted: true, expiresAt: value.expiresAt };
|
|
586
|
+
}
|
|
587
|
+
if (operation === "resize") {
|
|
588
|
+
this.#touchTerminalSession(value);
|
|
589
|
+
return { accepted: true, expiresAt: value.expiresAt };
|
|
590
|
+
}
|
|
591
|
+
if (operation === "output") {
|
|
592
|
+
this.#touchTerminalSession(value);
|
|
593
|
+
return sessionSummary(value);
|
|
594
|
+
}
|
|
595
|
+
if (operation === "resume") {
|
|
596
|
+
this.#touchTerminalSession(value);
|
|
597
|
+
return terminalResumeSummary(value, input);
|
|
598
|
+
}
|
|
599
|
+
throw new TypeError("terminal operation is invalid");
|
|
600
|
+
}
|
|
601
|
+
async #screen(input, workspaceId) {
|
|
602
|
+
const operation = String(input.operation);
|
|
603
|
+
if (operation === "start") {
|
|
604
|
+
if (this.#screenSessions.size >= this.#maxSessions) throw new TypeError("screen session limit reached");
|
|
605
|
+
const sessionId2 = randomUUID2();
|
|
606
|
+
const intervalMs = bounded(Number(input.intervalMs ?? 500), 100, 5e3, "screen frame interval");
|
|
607
|
+
const requestedFormat = screenStreamFormat(input.format);
|
|
608
|
+
const format = requestedFormat === "auto" ? "png" : requestedFormat;
|
|
609
|
+
const quality = screenQuality(input.quality, format);
|
|
610
|
+
const now = Date.now();
|
|
611
|
+
const session2 = {
|
|
612
|
+
workspaceId,
|
|
613
|
+
monitorId: optionalText(input.monitorId, 128, "monitor id"),
|
|
614
|
+
createdAt: now,
|
|
615
|
+
requestedIntervalMs: intervalMs,
|
|
616
|
+
intervalMs,
|
|
617
|
+
format,
|
|
618
|
+
requestedFormat,
|
|
619
|
+
requestedQuality: quality,
|
|
620
|
+
quality,
|
|
621
|
+
sequence: 0,
|
|
622
|
+
capturing: false,
|
|
623
|
+
lastActivityAt: now,
|
|
624
|
+
expiresAt: now + this.#sessionIdleTimeoutMs,
|
|
625
|
+
timer: setTimeout(() => void this.#pushScreenFrame(sessionId2), intervalMs),
|
|
626
|
+
idleTimer: null
|
|
627
|
+
};
|
|
628
|
+
session2.timer.unref();
|
|
629
|
+
this.#screenSessions.set(sessionId2, session2);
|
|
630
|
+
this.#touchScreenSession(sessionId2, session2);
|
|
631
|
+
queueMicrotask(() => void this.#pushScreenFrame(sessionId2));
|
|
632
|
+
return { sessionId: sessionId2, status: "streaming", intervalMs, format, formatMode: requestedFormat, quality, expiresAt: session2.expiresAt };
|
|
633
|
+
}
|
|
634
|
+
const sessionId = text2(input.sessionId, 128, "screen session id");
|
|
635
|
+
const session = this.#screenSessions.get(sessionId);
|
|
636
|
+
if (!session || session.workspaceId !== workspaceId) throw new TypeError("screen session is unavailable");
|
|
637
|
+
if (operation === "close") {
|
|
638
|
+
clearTimeout(session.timer);
|
|
639
|
+
if (session.idleTimer) clearTimeout(session.idleTimer);
|
|
640
|
+
session.idleTimer = null;
|
|
641
|
+
this.#screenSessions.delete(sessionId);
|
|
642
|
+
return { closed: true };
|
|
643
|
+
}
|
|
644
|
+
if (operation === "frame") {
|
|
645
|
+
this.#touchScreenSession(sessionId, session);
|
|
646
|
+
return { sessionId, frame: await this.options.captureScreen(session.monitorId, { format: session.format, quality: session.quality }), capturedAt: Date.now(), expiresAt: session.expiresAt };
|
|
647
|
+
}
|
|
648
|
+
if (operation === "feedback") {
|
|
649
|
+
this.#touchScreenSession(sessionId, session);
|
|
650
|
+
const observedLatencyMs = bounded(Number(input.observedLatencyMs), 0, 6e4, "observed screen latency");
|
|
651
|
+
const droppedFrames = bounded(Number(input.droppedFrames ?? 0), 0, 1e4, "dropped screen frames");
|
|
652
|
+
const degraded = droppedFrames > 0 || observedLatencyMs > session.intervalMs * 1.5;
|
|
653
|
+
session.intervalMs = degraded ? Math.min(5e3, session.intervalMs + 100) : Math.max(session.requestedIntervalMs, session.intervalMs - 50);
|
|
654
|
+
if (session.requestedFormat === "auto") {
|
|
655
|
+
session.format = degraded ? "jpeg" : session.intervalMs === session.requestedIntervalMs ? "png" : session.format;
|
|
656
|
+
if (session.format === "png") session.quality = session.requestedQuality;
|
|
657
|
+
}
|
|
658
|
+
if (session.format === "jpeg") session.quality = degraded ? Math.max(30, session.quality - 10) : Math.min(session.requestedQuality, session.quality + 5);
|
|
659
|
+
clearTimeout(session.timer);
|
|
660
|
+
session.timer = setTimeout(() => void this.#pushScreenFrame(sessionId), session.intervalMs);
|
|
661
|
+
session.timer.unref();
|
|
662
|
+
return { sessionId, intervalMs: session.intervalMs, format: session.format, quality: session.quality, adapted: session.intervalMs !== session.requestedIntervalMs || session.quality !== session.requestedQuality || session.requestedFormat === "auto" && session.format === "jpeg" };
|
|
663
|
+
}
|
|
664
|
+
throw new TypeError("screen stream operation is invalid");
|
|
665
|
+
}
|
|
666
|
+
async #pushScreenFrame(sessionId) {
|
|
667
|
+
const session = this.#screenSessions.get(sessionId);
|
|
668
|
+
if (!session || session.capturing) return;
|
|
669
|
+
session.capturing = true;
|
|
670
|
+
try {
|
|
671
|
+
const frame = await this.options.captureScreen(session.monitorId, { format: session.format, quality: session.quality });
|
|
672
|
+
if (this.#screenSessions.get(sessionId) !== session) return;
|
|
673
|
+
this.#emit("device-agent.screen.frame", "screen.stream", { sessionId, sequence: ++session.sequence, capturedAt: Date.now(), frame }, session.workspaceId);
|
|
674
|
+
} catch {
|
|
675
|
+
if (this.#screenSessions.get(sessionId) === session) this.#emit("device-agent.screen.error", "screen.stream", { sessionId, sequence: session.sequence, code: "capture_failed" }, session.workspaceId);
|
|
676
|
+
} finally {
|
|
677
|
+
session.capturing = false;
|
|
678
|
+
if (this.#screenSessions.get(sessionId) === session) {
|
|
679
|
+
clearTimeout(session.timer);
|
|
680
|
+
session.timer = setTimeout(() => void this.#pushScreenFrame(sessionId), session.intervalMs);
|
|
681
|
+
session.timer.unref();
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
#touchTerminalSession(value) {
|
|
686
|
+
if (this.#sessions.get(value.id) !== value) return;
|
|
687
|
+
if (value.idleTimer) clearTimeout(value.idleTimer);
|
|
688
|
+
value.lastActivityAt = Date.now();
|
|
689
|
+
value.expiresAt = value.lastActivityAt + this.#sessionIdleTimeoutMs;
|
|
690
|
+
value.idleTimer = setTimeout(() => this.#expireTerminalSession(value.id, value), this.#sessionIdleTimeoutMs);
|
|
691
|
+
value.idleTimer.unref();
|
|
692
|
+
}
|
|
693
|
+
#expireTerminalSession(sessionId, value) {
|
|
694
|
+
if (this.#sessions.get(sessionId) !== value) return;
|
|
695
|
+
if (value.idleTimer) clearTimeout(value.idleTimer);
|
|
696
|
+
value.idleTimer = null;
|
|
697
|
+
this.#sessions.delete(sessionId);
|
|
698
|
+
if (value.exitCode === null) value.child.kill("SIGKILL");
|
|
699
|
+
value.child.stdin.destroy();
|
|
700
|
+
this.#emit("device-agent.terminal.expired", "terminal.session", { sessionId, idleTimeoutMs: this.#sessionIdleTimeoutMs }, value.workspaceId);
|
|
701
|
+
}
|
|
702
|
+
#touchScreenSession(sessionId, session) {
|
|
703
|
+
if (this.#screenSessions.get(sessionId) !== session) return;
|
|
704
|
+
if (session.idleTimer) clearTimeout(session.idleTimer);
|
|
705
|
+
session.lastActivityAt = Date.now();
|
|
706
|
+
session.expiresAt = session.lastActivityAt + this.#sessionIdleTimeoutMs;
|
|
707
|
+
session.idleTimer = setTimeout(() => this.#expireScreenSession(sessionId, session), this.#sessionIdleTimeoutMs);
|
|
708
|
+
session.idleTimer.unref();
|
|
709
|
+
}
|
|
710
|
+
#expireScreenSession(sessionId, session) {
|
|
711
|
+
if (this.#screenSessions.get(sessionId) !== session) return;
|
|
712
|
+
clearTimeout(session.timer);
|
|
713
|
+
if (session.idleTimer) clearTimeout(session.idleTimer);
|
|
714
|
+
session.idleTimer = null;
|
|
715
|
+
this.#screenSessions.delete(sessionId);
|
|
716
|
+
this.#emit("device-agent.screen.expired", "screen.stream", { sessionId, idleTimeoutMs: this.#sessionIdleTimeoutMs }, session.workspaceId);
|
|
717
|
+
}
|
|
718
|
+
#spawn(input, terminal, workspaceId) {
|
|
719
|
+
const executable = text2(input.executable ?? defaultShell(), 260, "executable");
|
|
720
|
+
if (![...this.#allowed].some((allowed) => executable === allowed || path2.basename(executable).toLowerCase() === path2.basename(allowed).toLowerCase())) throw new TypeError("executable is not allowed");
|
|
721
|
+
const args = Array.isArray(input.args) ? input.args.map((value) => text2(value, 8192, "argument")) : terminal ? [] : [text2(input.command ?? "", 8192, "command")];
|
|
722
|
+
if (args.length > 128 || JSON.stringify(args).length > 32768) throw new TypeError("command length limit exceeded");
|
|
723
|
+
const cwd = input.cwd === void 0 ? void 0 : this.#cwd(input.cwd);
|
|
724
|
+
const env = environment(input.environment);
|
|
725
|
+
const child = spawn(executable, args, { cwd, env: { ...process.env, ...env }, shell: false, windowsHide: true });
|
|
726
|
+
const record = {
|
|
727
|
+
id: randomUUID2(),
|
|
728
|
+
capability: terminal ? "terminal.session" : "process.output",
|
|
729
|
+
child,
|
|
730
|
+
stdout: "",
|
|
731
|
+
stderr: "",
|
|
732
|
+
stdoutBaseBytes: 0,
|
|
733
|
+
stderrBaseBytes: 0,
|
|
734
|
+
stdoutBytes: 0,
|
|
735
|
+
stderrBytes: 0,
|
|
736
|
+
startedAt: Date.now(),
|
|
737
|
+
exitCode: null,
|
|
738
|
+
truncated: false,
|
|
739
|
+
workspaceId
|
|
740
|
+
};
|
|
741
|
+
child.stdout.on("data", (chunk) => this.#append(record, "stdout", chunk));
|
|
742
|
+
child.stderr.on("data", (chunk) => this.#append(record, "stderr", chunk));
|
|
743
|
+
child.once("close", (code) => {
|
|
744
|
+
record.exitCode = code;
|
|
745
|
+
});
|
|
746
|
+
return record;
|
|
747
|
+
}
|
|
748
|
+
#append(record, target, chunk) {
|
|
749
|
+
const totalKey = target === "stdout" ? "stdoutBytes" : "stderrBytes";
|
|
750
|
+
const baseKey = target === "stdout" ? "stdoutBaseBytes" : "stderrBaseBytes";
|
|
751
|
+
record[totalKey] += chunk.byteLength;
|
|
752
|
+
const next = record[target] + chunk.toString("utf8");
|
|
753
|
+
if (record.capability === "terminal.session") {
|
|
754
|
+
const retained = retainUtf8Tail(next, this.#maxOutput);
|
|
755
|
+
record[target] = retained.text;
|
|
756
|
+
record[baseKey] += retained.droppedBytes;
|
|
757
|
+
if (retained.droppedBytes > 0) record.truncated = true;
|
|
758
|
+
} else if (Buffer.byteLength(next) > this.#maxOutput) {
|
|
759
|
+
record[target] = Buffer.from(next).subarray(0, this.#maxOutput).toString("utf8");
|
|
760
|
+
record.truncated = true;
|
|
761
|
+
} else record[target] = next;
|
|
762
|
+
this.#emit("device-agent.output", record.capability, { id: record.id, stream: target, chunk: chunk.subarray(0, this.#maxOutput).toString("utf8"), truncated: record.truncated }, record.workspaceId);
|
|
763
|
+
}
|
|
764
|
+
#emit(type, capability, payload, workspaceId = null) {
|
|
765
|
+
const event = { type, capability, payload, ...workspaceId ? { workspaceId } : {} };
|
|
766
|
+
for (const listener of this.#listeners) listener(event);
|
|
767
|
+
}
|
|
768
|
+
#root(value) {
|
|
769
|
+
const root2 = this.#roots.get(String(value));
|
|
770
|
+
if (!root2) throw new TypeError("device root is unavailable");
|
|
771
|
+
return root2;
|
|
772
|
+
}
|
|
773
|
+
#cwd(value) {
|
|
774
|
+
const raw = text2(value, 1024, "cwd");
|
|
775
|
+
let candidate;
|
|
776
|
+
try {
|
|
777
|
+
candidate = realpathSync(path2.resolve(raw));
|
|
778
|
+
} catch {
|
|
779
|
+
throw new TypeError("cwd is unavailable");
|
|
780
|
+
}
|
|
781
|
+
for (const root2 of this.#roots.values()) {
|
|
782
|
+
if (inside(root2.path, candidate)) return candidate;
|
|
783
|
+
}
|
|
784
|
+
throw new TypeError("cwd escapes configured roots");
|
|
785
|
+
}
|
|
786
|
+
#ownedRecord(map, value, workspaceId, label) {
|
|
787
|
+
const record = map.get(String(value));
|
|
788
|
+
if (!record || record.workspaceId !== workspaceId) throw new TypeError(label + " is unavailable");
|
|
789
|
+
return record;
|
|
790
|
+
}
|
|
791
|
+
#running(map) {
|
|
792
|
+
return [...map.values()].filter((value) => value.exitCode === null).length;
|
|
793
|
+
}
|
|
794
|
+
#prune() {
|
|
795
|
+
for (const [id, value] of this.#processes) if (value.exitCode !== null && Date.now() - value.startedAt > 3e5) this.#processes.delete(id);
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
var summary = (value) => ({
|
|
799
|
+
id: value.id,
|
|
800
|
+
status: value.exitCode === null ? "running" : "exited",
|
|
801
|
+
exitCode: value.exitCode,
|
|
802
|
+
stdout: value.stdout,
|
|
803
|
+
stderr: value.stderr,
|
|
804
|
+
startedAt: value.startedAt,
|
|
805
|
+
truncated: value.truncated
|
|
806
|
+
});
|
|
807
|
+
var sessionSummary = (value) => ({
|
|
808
|
+
...summary(value),
|
|
809
|
+
stdoutBaseBytes: value.stdoutBaseBytes,
|
|
810
|
+
stderrBaseBytes: value.stderrBaseBytes,
|
|
811
|
+
stdoutBytes: value.stdoutBytes,
|
|
812
|
+
stderrBytes: value.stderrBytes,
|
|
813
|
+
lastActivityAt: value.lastActivityAt,
|
|
814
|
+
expiresAt: value.expiresAt
|
|
815
|
+
});
|
|
816
|
+
var terminalResumeSummary = (value, input) => ({
|
|
817
|
+
id: value.id,
|
|
818
|
+
status: value.exitCode === null ? "running" : "exited",
|
|
819
|
+
exitCode: value.exitCode,
|
|
820
|
+
startedAt: value.startedAt,
|
|
821
|
+
lastActivityAt: value.lastActivityAt,
|
|
822
|
+
expiresAt: value.expiresAt,
|
|
823
|
+
truncated: value.truncated,
|
|
824
|
+
stdout: resumeStream(value.stdout, value.stdoutBaseBytes, value.stdoutBytes, cursor(input.afterStdoutBytes, "stdout cursor")),
|
|
825
|
+
stderr: resumeStream(value.stderr, value.stderrBaseBytes, value.stderrBytes, cursor(input.afterStderrBytes, "stderr cursor"))
|
|
826
|
+
});
|
|
827
|
+
var resumeStream = (retained, baseBytes, totalBytes, afterBytes) => {
|
|
828
|
+
if (afterBytes > totalBytes) throw new TypeError("terminal resume cursor is ahead of output");
|
|
829
|
+
const resyncRequired = afterBytes < baseBytes;
|
|
830
|
+
const fromBytes = resyncRequired ? baseBytes : afterBytes;
|
|
831
|
+
const relative = fromBytes - baseBytes;
|
|
832
|
+
const bytes = Buffer.from(retained, "utf8");
|
|
833
|
+
if (relative > bytes.byteLength) throw new TypeError("terminal resume cursor is unavailable");
|
|
834
|
+
return { chunk: bytes.subarray(relative).toString("utf8"), fromBytes, nextBytes: totalBytes, baseBytes, resyncRequired };
|
|
835
|
+
};
|
|
836
|
+
var cursor = (value, label) => {
|
|
837
|
+
if (value === void 0 || value === null || value === "") return 0;
|
|
838
|
+
if (!Number.isSafeInteger(value) || Number(value) < 0) throw new TypeError(label + " is invalid");
|
|
839
|
+
return Number(value);
|
|
840
|
+
};
|
|
841
|
+
var retainUtf8Tail = (value, maximumBytes) => {
|
|
842
|
+
const bytes = Buffer.from(value, "utf8");
|
|
843
|
+
if (bytes.byteLength <= maximumBytes) return { text: value, droppedBytes: 0 };
|
|
844
|
+
let start = bytes.byteLength - maximumBytes;
|
|
845
|
+
while (start < bytes.byteLength && (bytes[start] & 192) === 128) start++;
|
|
846
|
+
return { text: bytes.subarray(start).toString("utf8"), droppedBytes: start };
|
|
847
|
+
};
|
|
848
|
+
var inside = (root2, target) => target === root2 || target.startsWith(root2 + path2.sep);
|
|
849
|
+
var executionWorkspaceId = (value) => {
|
|
850
|
+
if (value === void 0) return null;
|
|
851
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) throw new TypeError("workspace id is invalid");
|
|
852
|
+
return value;
|
|
853
|
+
};
|
|
854
|
+
async function safeExisting(root2, relative) {
|
|
855
|
+
const lexical = path2.resolve(root2, relative);
|
|
856
|
+
if (!inside(root2, lexical)) throw new TypeError("path escapes configured root");
|
|
857
|
+
let target;
|
|
858
|
+
try {
|
|
859
|
+
target = await realpath(lexical);
|
|
860
|
+
} catch {
|
|
861
|
+
throw new TypeError("device path is unavailable");
|
|
862
|
+
}
|
|
863
|
+
if (!inside(root2, target)) throw new TypeError("path escapes configured root");
|
|
864
|
+
return target;
|
|
865
|
+
}
|
|
866
|
+
async function safeWritable(root2, relative) {
|
|
867
|
+
const lexical = path2.resolve(root2, relative);
|
|
868
|
+
if (!inside(root2, lexical) || lexical === root2) {
|
|
869
|
+
throw new TypeError("relative path is invalid");
|
|
870
|
+
}
|
|
871
|
+
const parts = path2.relative(root2, lexical).split(path2.sep);
|
|
872
|
+
const leaf = parts.pop();
|
|
873
|
+
if (!leaf) throw new TypeError("relative path is invalid");
|
|
874
|
+
let parent = root2;
|
|
875
|
+
for (const part of parts) {
|
|
876
|
+
const next = path2.join(parent, part);
|
|
877
|
+
try {
|
|
878
|
+
const resolved = await realpath(next);
|
|
879
|
+
if (!inside(root2, resolved)) throw new TypeError("path escapes configured root");
|
|
880
|
+
parent = resolved;
|
|
881
|
+
} catch (error) {
|
|
882
|
+
if (error instanceof TypeError || !isMissing(error)) throw error;
|
|
883
|
+
await mkdir2(next);
|
|
884
|
+
const resolved = await realpath(next);
|
|
885
|
+
if (!inside(root2, resolved)) throw new TypeError("path escapes configured root");
|
|
886
|
+
parent = resolved;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
const target = path2.join(parent, leaf);
|
|
890
|
+
try {
|
|
891
|
+
const resolved = await realpath(target);
|
|
892
|
+
if (!inside(root2, resolved)) throw new TypeError("path escapes configured root");
|
|
893
|
+
return resolved;
|
|
894
|
+
} catch (error) {
|
|
895
|
+
if (error instanceof TypeError || !isMissing(error)) throw error;
|
|
896
|
+
return target;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
function isMissing(error) {
|
|
900
|
+
return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
|
|
901
|
+
}
|
|
902
|
+
function safeRelative(value, empty) {
|
|
903
|
+
const result = String(value ?? "");
|
|
904
|
+
if (!empty && !result || result.length > 1024 || path2.isAbsolute(result) || result.split(/[\\/]/).some((part) => part === "..") || result.includes("\0")) {
|
|
905
|
+
throw new TypeError("relative path is invalid");
|
|
906
|
+
}
|
|
907
|
+
return result;
|
|
908
|
+
}
|
|
909
|
+
function decodeBase64(value, limit) {
|
|
910
|
+
if (typeof value !== "string" || value.length > Math.ceil(limit * 4 / 3) + 4 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) throw new TypeError("file content is invalid");
|
|
911
|
+
const data = Buffer.from(value, "base64");
|
|
912
|
+
if (data.byteLength > limit) throw new TypeError("file exceeds transfer limit");
|
|
913
|
+
return data;
|
|
914
|
+
}
|
|
915
|
+
function text2(value, maximum, label) {
|
|
916
|
+
if (typeof value !== "string" || !value || value.length > maximum || /[\0]/.test(value)) throw new TypeError(label + " is invalid");
|
|
917
|
+
return value;
|
|
918
|
+
}
|
|
919
|
+
function clipboardText(value) {
|
|
920
|
+
if (typeof value !== "string" || value.includes("\0") || Buffer.byteLength(value, "utf8") > 1048576) throw new TypeError("clipboard text is invalid");
|
|
921
|
+
return value;
|
|
922
|
+
}
|
|
923
|
+
function optionalText(value, maximum, label) {
|
|
924
|
+
return value === void 0 || value === null || value === "" ? void 0 : text2(value, maximum, label);
|
|
925
|
+
}
|
|
926
|
+
function screenFormat(value) {
|
|
927
|
+
if (value === void 0 || value === "png") return "png";
|
|
928
|
+
if (value === "jpeg") return "jpeg";
|
|
929
|
+
throw new TypeError("screen format is invalid");
|
|
930
|
+
}
|
|
931
|
+
function screenStreamFormat(value) {
|
|
932
|
+
if (value === void 0 || value === "auto") return "auto";
|
|
933
|
+
return screenFormat(value);
|
|
934
|
+
}
|
|
935
|
+
function screenQuality(value, format) {
|
|
936
|
+
if (format === "png") return 100;
|
|
937
|
+
return bounded(Number(value ?? 80), 30, 95, "screen quality");
|
|
938
|
+
}
|
|
939
|
+
function serviceName(value) {
|
|
940
|
+
if (typeof value !== "string" || value.length > 256 || !/^[A-Za-z0-9_.@:-]+$/.test(value)) throw new TypeError("service name is invalid");
|
|
941
|
+
return value;
|
|
942
|
+
}
|
|
943
|
+
function serviceOperation(value) {
|
|
944
|
+
if (value !== "start" && value !== "stop" && value !== "restart") throw new TypeError("service operation is invalid");
|
|
945
|
+
return value;
|
|
946
|
+
}
|
|
947
|
+
function bounded(value, min, max, label) {
|
|
948
|
+
if (!Number.isInteger(value) || value < min || value > max) throw new TypeError(label + " is invalid");
|
|
949
|
+
return value;
|
|
950
|
+
}
|
|
951
|
+
function environment(value) {
|
|
952
|
+
if (value === void 0) return {};
|
|
953
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length > 32) throw new TypeError("environment is invalid");
|
|
954
|
+
const result = {};
|
|
955
|
+
for (const [key, item] of Object.entries(value)) {
|
|
956
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(key)) throw new TypeError("environment key is invalid");
|
|
957
|
+
result[key] = text2(item, 4096, "environment value");
|
|
958
|
+
}
|
|
959
|
+
return result;
|
|
960
|
+
}
|
|
961
|
+
var defaultShell = () => process.platform === "win32" ? "powershell.exe" : "/bin/sh";
|
|
962
|
+
var defaultExecutables = () => process.platform === "win32" ? ["powershell.exe", "cmd.exe"] : ["/bin/sh", "/bin/bash"];
|
|
963
|
+
|
|
964
|
+
// ../device-agent/src/native-desktop.ts
|
|
965
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
966
|
+
import { promisify as promisify2 } from "node:util";
|
|
967
|
+
var execute2 = promisify2(execFile2);
|
|
968
|
+
async function createNativeDesktopAdapter(platform = process.platform, run = execute2) {
|
|
969
|
+
if (platform === "win32") return windowsAdapter(run);
|
|
970
|
+
if (platform === "linux") {
|
|
971
|
+
const interop = await windowsInteropScreenAdapter(run);
|
|
972
|
+
return interop ?? linuxAdapter(run);
|
|
973
|
+
}
|
|
974
|
+
return {};
|
|
975
|
+
}
|
|
976
|
+
async function windowsAdapter(run) {
|
|
977
|
+
if (!await available(run, "powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "$PSVersionTable.PSVersion.ToString()"])) {
|
|
978
|
+
return {};
|
|
979
|
+
}
|
|
980
|
+
const invoke2 = (script, args = []) => powershellInvoke(run, "powershell.exe", script, args);
|
|
981
|
+
return {
|
|
982
|
+
monitors: async () => JSON.parse(asText((await invoke2(WINDOWS_MONITORS)).stdout)),
|
|
983
|
+
captureScreen: async (monitorId, options) => JSON.parse(asText((await invoke2(WINDOWS_CAPTURE, [monitorId ?? "0", options?.format ?? "png", String(options?.quality ?? 100)])).stdout)),
|
|
984
|
+
pointer: async (input) => {
|
|
985
|
+
const monitorId = input.monitorId === void 0 ? void 0 : text3(input.monitorId, 128, "monitor id");
|
|
986
|
+
const monitors = monitorId ? JSON.parse(asText((await invoke2(WINDOWS_MONITORS)).stdout)) : [];
|
|
987
|
+
const monitor = monitorId ? monitors.find((item) => item.id === monitorId) : void 0;
|
|
988
|
+
if (monitorId && !monitor) throw new TypeError("screen monitor is unavailable");
|
|
989
|
+
await invoke2(WINDOWS_POINTER, pointerArguments(monitor ? { ...input, x: integer2(input.x, 0, 1e5, "x") + monitor.x, y: integer2(input.y, 0, 1e5, "y") + monitor.y, toX: integer2(input.toX ?? input.x, 0, 1e5, "toX") + monitor.x, toY: integer2(input.toY ?? input.y, 0, 1e5, "toY") + monitor.y } : input));
|
|
990
|
+
},
|
|
991
|
+
keyboard: async (input) => {
|
|
992
|
+
await invoke2(WINDOWS_KEYBOARD, [windowsKeyboardSequence(input)]);
|
|
993
|
+
},
|
|
994
|
+
readClipboard: async () => ({ text: asText((await invoke2(WINDOWS_CLIPBOARD_READ)).stdout) }),
|
|
995
|
+
writeClipboard: async (text4) => {
|
|
996
|
+
await invoke2(WINDOWS_CLIPBOARD_WRITE, [boundedText(text4, 1048576, "clipboard text")]);
|
|
997
|
+
}
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
async function windowsInteropScreenAdapter(run) {
|
|
1001
|
+
for (const executable of ["powershell.exe", "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"]) {
|
|
1002
|
+
try {
|
|
1003
|
+
const version = await run(executable, ["-NoProfile", "-NonInteractive", "-Command", "$PSVersionTable.PSVersion.ToString()"], { ...commandOptions(), timeout: 2e3 });
|
|
1004
|
+
if (!/^\d+(?:\.\d+)+/.test(asText(version.stdout).trim())) continue;
|
|
1005
|
+
const invoke2 = (script, args = []) => powershellInvoke(run, executable, script, args);
|
|
1006
|
+
return { monitors: async () => JSON.parse(asText((await invoke2(WINDOWS_MONITORS)).stdout)), captureScreen: async (monitorId, options) => JSON.parse(asText((await invoke2(WINDOWS_CAPTURE, [monitorId ?? "0", options?.format ?? "png", String(options?.quality ?? 100)])).stdout)) };
|
|
1007
|
+
} catch {
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
return void 0;
|
|
1011
|
+
}
|
|
1012
|
+
async function linuxAdapter(run) {
|
|
1013
|
+
const hasXrandr = await available(run, "xrandr", ["--query"]);
|
|
1014
|
+
const hasImport = hasXrandr && await available(run, "import", ["-version"]);
|
|
1015
|
+
const hasGrim = await available(run, "grim", ["--help"]);
|
|
1016
|
+
const hasInput = await available(run, "xdotool", ["version"]);
|
|
1017
|
+
return {
|
|
1018
|
+
...hasXrandr ? { monitors: async () => parseXrandr(asText((await run("xrandr", ["--query"], commandOptions())).stdout)) } : {},
|
|
1019
|
+
...hasImport || hasGrim ? {
|
|
1020
|
+
captureScreen: async (monitorId, options = { format: "png", quality: 100 }) => {
|
|
1021
|
+
if (hasImport && hasXrandr) {
|
|
1022
|
+
const monitors = parseXrandrGeometry(asText((await run("xrandr", ["--query"], commandOptions())).stdout));
|
|
1023
|
+
const monitor2 = monitorId ? monitors.find((item) => item.id === monitorId) : monitors.find((item) => item.primary) ?? monitors[0];
|
|
1024
|
+
if (!monitor2) throw new TypeError("screen monitor is unavailable");
|
|
1025
|
+
const output2 = await run("import", ["-window", "root", "-crop", `${monitor2.width}x${monitor2.height}+${monitor2.x}+${monitor2.y}`, ...options.format === "jpeg" ? ["-quality", String(options.quality)] : [], `${options.format}:-`], binaryOptions());
|
|
1026
|
+
const bytes2 = screenImage(asBuffer(output2.stdout), options.format);
|
|
1027
|
+
return { contentType: `image/${options.format}`, contentBase64: bytes2.toString("base64"), width: monitor2.width, height: monitor2.height, monitorId: monitor2.id };
|
|
1028
|
+
}
|
|
1029
|
+
if (options.format !== "png") throw new TypeError("screen format is unavailable");
|
|
1030
|
+
const monitor = monitorId ?? "primary";
|
|
1031
|
+
const output = await run("grim", [...monitorId ? ["-o", monitorId] : [], "-"], binaryOptions());
|
|
1032
|
+
const bytes = screenPng(asBuffer(output.stdout));
|
|
1033
|
+
const dimensions = pngDimensions(bytes);
|
|
1034
|
+
return { contentType: "image/png", contentBase64: bytes.toString("base64"), width: dimensions.width, height: dimensions.height, monitorId: monitor };
|
|
1035
|
+
}
|
|
1036
|
+
} : {},
|
|
1037
|
+
...hasInput ? {
|
|
1038
|
+
pointer: async (input) => {
|
|
1039
|
+
const operation = String(input.operation ?? "move");
|
|
1040
|
+
const monitorId = input.monitorId === void 0 ? void 0 : text3(input.monitorId, 128, "monitor id");
|
|
1041
|
+
const monitor = monitorId ? parseXrandrGeometry(asText((await run("xrandr", ["--query"], commandOptions())).stdout)).find((item) => item.id === monitorId) : void 0;
|
|
1042
|
+
if (monitorId && !monitor) throw new TypeError("screen monitor is unavailable");
|
|
1043
|
+
const offsetX = monitor?.x ?? 0;
|
|
1044
|
+
const offsetY = monitor?.y ?? 0;
|
|
1045
|
+
const x = String(integer2(input.x, 0, 1e5, "x") + offsetX);
|
|
1046
|
+
const y = String(integer2(input.y, 0, 1e5, "y") + offsetY);
|
|
1047
|
+
await run("xdotool", ["mousemove", x, y], commandOptions());
|
|
1048
|
+
if (operation === "click") await run("xdotool", ["click", mouseButton(input.button)], commandOptions());
|
|
1049
|
+
else if (operation === "doubleClick") await run("xdotool", ["click", "--repeat", "2", "--delay", "100", mouseButton(input.button)], commandOptions());
|
|
1050
|
+
else if (operation === "drag") {
|
|
1051
|
+
await run("xdotool", ["mousedown", mouseButton(input.button)], commandOptions());
|
|
1052
|
+
await run("xdotool", ["mousemove", String(integer2(input.toX, 0, 1e5, "toX") + offsetX), String(integer2(input.toY, 0, 1e5, "toY") + offsetY)], commandOptions());
|
|
1053
|
+
await run("xdotool", ["mouseup", mouseButton(input.button)], commandOptions());
|
|
1054
|
+
} else if (operation === "scroll") {
|
|
1055
|
+
const deltaY = integer2(input.deltaY ?? 0, -1e4, 1e4, "deltaY");
|
|
1056
|
+
const deltaX = integer2(input.deltaX ?? 0, -1e4, 1e4, "deltaX");
|
|
1057
|
+
for (const [delta, positive, negative] of [
|
|
1058
|
+
[deltaY, "5", "4"],
|
|
1059
|
+
[deltaX, "7", "6"]
|
|
1060
|
+
])
|
|
1061
|
+
if (delta) await run("xdotool", ["click", "--repeat", String(Math.min(Math.abs(delta), 100)), delta > 0 ? positive : negative], commandOptions());
|
|
1062
|
+
} else if (operation !== "move") throw new TypeError("pointer operation is invalid");
|
|
1063
|
+
},
|
|
1064
|
+
keyboard: async (input) => {
|
|
1065
|
+
const value = text3(input.text ?? input.key, 4096, "keyboard input");
|
|
1066
|
+
await run("xdotool", input.text === void 0 ? ["key", linuxKeySequence(value, input.modifiers)] : ["type", "--", value], commandOptions());
|
|
1067
|
+
}
|
|
1068
|
+
} : {}
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
var WINDOWS_KEY_TOKENS = {
|
|
1072
|
+
Enter: "{ENTER}",
|
|
1073
|
+
Tab: "{TAB}",
|
|
1074
|
+
Escape: "{ESC}",
|
|
1075
|
+
Backspace: "{BACKSPACE}",
|
|
1076
|
+
Delete: "{DELETE}",
|
|
1077
|
+
Space: " ",
|
|
1078
|
+
Home: "{HOME}",
|
|
1079
|
+
End: "{END}",
|
|
1080
|
+
PageUp: "{PGUP}",
|
|
1081
|
+
PageDown: "{PGDN}",
|
|
1082
|
+
ArrowLeft: "{LEFT}",
|
|
1083
|
+
ArrowUp: "{UP}",
|
|
1084
|
+
ArrowRight: "{RIGHT}",
|
|
1085
|
+
ArrowDown: "{DOWN}"
|
|
1086
|
+
};
|
|
1087
|
+
var SEND_KEYS_LITERAL = { "+": "{+}", "^": "{^}", "%": "{%}", "~": "{~}", "(": "{(}", ")": "{)}", "{": "{{}", "}": "{}}" };
|
|
1088
|
+
function windowsKeyboardSequence(input) {
|
|
1089
|
+
if (input.text !== void 0) {
|
|
1090
|
+
const value = text3(input.text, 4096, "keyboard input");
|
|
1091
|
+
return [...value].map((character) => SEND_KEYS_LITERAL[character] ?? character).join("");
|
|
1092
|
+
}
|
|
1093
|
+
const key = text3(input.key, 64, "keyboard key");
|
|
1094
|
+
if (/^F(?:[1-9]|1[0-2])$/.test(key)) return "{" + key + "}";
|
|
1095
|
+
const token = WINDOWS_KEY_TOKENS[key];
|
|
1096
|
+
if (!token) throw new TypeError("keyboard key is invalid");
|
|
1097
|
+
const modifiers = modifierList(input.modifiers);
|
|
1098
|
+
return (modifiers.includes("Control") ? "^" : "") + (modifiers.includes("Alt") ? "%" : "") + (modifiers.includes("Shift") ? "+" : "") + token;
|
|
1099
|
+
}
|
|
1100
|
+
function linuxKeySequence(key, rawModifiers) {
|
|
1101
|
+
const aliases = { Control: "ctrl", Alt: "alt", Shift: "shift", Meta: "super" };
|
|
1102
|
+
return [...modifierList(rawModifiers).map((modifier) => aliases[modifier]), key].join("+");
|
|
1103
|
+
}
|
|
1104
|
+
function modifierList(value) {
|
|
1105
|
+
if (value === void 0) return [];
|
|
1106
|
+
if (!Array.isArray(value) || value.length > 4) throw new TypeError("keyboard modifiers are invalid");
|
|
1107
|
+
const allowed = /* @__PURE__ */ new Set(["Control", "Alt", "Shift", "Meta"]);
|
|
1108
|
+
const modifiers = value.map((item) => text3(item, 16, "keyboard modifier"));
|
|
1109
|
+
if (new Set(modifiers).size !== modifiers.length || modifiers.some((item) => !allowed.has(item))) throw new TypeError("keyboard modifiers are invalid");
|
|
1110
|
+
return modifiers;
|
|
1111
|
+
}
|
|
1112
|
+
function pointerArguments(input) {
|
|
1113
|
+
const operation = String(input.operation ?? "move");
|
|
1114
|
+
if (!["move", "click", "doubleClick", "drag", "scroll"].includes(operation)) throw new TypeError("pointer operation is invalid");
|
|
1115
|
+
return [
|
|
1116
|
+
String(integer2(input.x, 0, 1e5, "x")),
|
|
1117
|
+
String(integer2(input.y, 0, 1e5, "y")),
|
|
1118
|
+
operation,
|
|
1119
|
+
String(input.button ?? "left"),
|
|
1120
|
+
String(integer2(input.toX ?? input.x, 0, 1e5, "toX")),
|
|
1121
|
+
String(integer2(input.toY ?? input.y, 0, 1e5, "toY")),
|
|
1122
|
+
String(integer2(input.deltaX ?? 0, -1e4, 1e4, "deltaX")),
|
|
1123
|
+
String(integer2(input.deltaY ?? 0, -1e4, 1e4, "deltaY"))
|
|
1124
|
+
];
|
|
1125
|
+
}
|
|
1126
|
+
function powershellInvoke(run, executable, script, args = []) {
|
|
1127
|
+
const encodedScript = Buffer.from(script, "utf8").toString("base64");
|
|
1128
|
+
const encodedArgs = args.map((value) => Buffer.from(value, "utf8").toString("base64"));
|
|
1129
|
+
const command = "$s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + encodedScript + "'));$a=@(" + encodedArgs.map((value) => "'" + value + "'").join(",") + ");$a=@($a|%{[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($_))});& ([ScriptBlock]::Create($s)) @a";
|
|
1130
|
+
return run(executable, ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", command], commandOptions());
|
|
1131
|
+
}
|
|
1132
|
+
async function available(run, file, args) {
|
|
1133
|
+
try {
|
|
1134
|
+
await run(file, args, { ...commandOptions(), timeout: 2e3 });
|
|
1135
|
+
return true;
|
|
1136
|
+
} catch {
|
|
1137
|
+
return false;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
function parseXrandr(output) {
|
|
1141
|
+
return parseXrandrGeometry(output);
|
|
1142
|
+
}
|
|
1143
|
+
function parseXrandrGeometry(output) {
|
|
1144
|
+
return output.split("\n").flatMap((line) => {
|
|
1145
|
+
const match = /^(\S+) connected(?: primary)? (\d+)x(\d+)([+-]\d+)([+-]\d+)/.exec(line);
|
|
1146
|
+
return match ? [{ id: match[1], label: match[1], width: Number(match[2]), height: Number(match[3]), x: Number(match[4]), y: Number(match[5]), scale: 1, primary: line.includes(" connected primary ") }] : [];
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
function screenPng(bytes) {
|
|
1150
|
+
if (!bytes.length || bytes.length > 8 * 1024 * 1024) throw new TypeError("screen capture is invalid");
|
|
1151
|
+
pngDimensions(bytes);
|
|
1152
|
+
return bytes;
|
|
1153
|
+
}
|
|
1154
|
+
function screenImage(bytes, format) {
|
|
1155
|
+
if (format === "png") return screenPng(bytes);
|
|
1156
|
+
if (bytes.length < 4 || bytes.length > 8 * 1024 * 1024 || bytes[0] !== 255 || bytes[1] !== 216 || bytes.at(-2) !== 255 || bytes.at(-1) !== 217) throw new TypeError("screen capture is invalid");
|
|
1157
|
+
return bytes;
|
|
1158
|
+
}
|
|
1159
|
+
function pngDimensions(bytes) {
|
|
1160
|
+
if (bytes.length < 24 || bytes.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a" || bytes.subarray(12, 16).toString("ascii") !== "IHDR") throw new TypeError("screen capture is invalid");
|
|
1161
|
+
const width = bytes.readUInt32BE(16);
|
|
1162
|
+
const height = bytes.readUInt32BE(20);
|
|
1163
|
+
if (!width || !height || width > 1e5 || height > 1e5) throw new TypeError("screen capture is invalid");
|
|
1164
|
+
return { width, height };
|
|
1165
|
+
}
|
|
1166
|
+
function mouseButton(value) {
|
|
1167
|
+
const button = value ?? "left";
|
|
1168
|
+
if (button === "left") return "1";
|
|
1169
|
+
if (button === "middle") return "2";
|
|
1170
|
+
if (button === "right") return "3";
|
|
1171
|
+
throw new TypeError("pointer button is invalid");
|
|
1172
|
+
}
|
|
1173
|
+
function integer2(value, min, max, label) {
|
|
1174
|
+
const result = Number(value);
|
|
1175
|
+
if (!Number.isInteger(result) || result < min || result > max) throw new TypeError(label + " is invalid");
|
|
1176
|
+
return result;
|
|
1177
|
+
}
|
|
1178
|
+
function text3(value, maximum, label) {
|
|
1179
|
+
if (typeof value !== "string" || !value || value.length > maximum || /[\0]/.test(value)) throw new TypeError(label + " is invalid");
|
|
1180
|
+
return value;
|
|
1181
|
+
}
|
|
1182
|
+
function boundedText(value, maximumBytes, label) {
|
|
1183
|
+
if (typeof value !== "string" || value.includes("\0") || Buffer.byteLength(value, "utf8") > maximumBytes) throw new TypeError(label + " is invalid");
|
|
1184
|
+
return value;
|
|
1185
|
+
}
|
|
1186
|
+
function asText(value) {
|
|
1187
|
+
return typeof value === "string" ? value : value.toString("utf8");
|
|
1188
|
+
}
|
|
1189
|
+
function asBuffer(value) {
|
|
1190
|
+
return Buffer.isBuffer(value) ? value : Buffer.from(value, "binary");
|
|
1191
|
+
}
|
|
1192
|
+
var commandOptions = () => ({ encoding: "utf8", maxBuffer: 10 * 1024 * 1024, timeout: 15e3, windowsHide: true });
|
|
1193
|
+
var binaryOptions = () => ({ ...commandOptions(), encoding: "buffer" });
|
|
1194
|
+
var WINDOWS_DPI_AWARE = `Add-Type -TypeDefinition 'using System;using System.Runtime.InteropServices;public class UapDpi{[DllImport("user32.dll")]public static extern bool SetProcessDpiAwarenessContext(IntPtr v);}' ;[UapDpi]::SetProcessDpiAwarenessContext([IntPtr](-4))|Out-Null;`;
|
|
1195
|
+
var WINDOWS_MONITOR_DPI = `Add-Type -TypeDefinition 'using System;using System.Runtime.InteropServices;public class UapMonitorDpi{[StructLayout(LayoutKind.Sequential)]public struct POINT{public int X;public int Y;}[DllImport("user32.dll")]public static extern IntPtr MonitorFromPoint(POINT p,uint f);[DllImport("shcore.dll")]public static extern int GetDpiForMonitor(IntPtr h,int t,out uint x,out uint y);}' ;`;
|
|
1196
|
+
var WINDOWS_MONITORS = WINDOWS_DPI_AWARE + WINDOWS_MONITOR_DPI + "Add-Type -AssemblyName System.Windows.Forms;$r=@([System.Windows.Forms.Screen]::AllScreens|ForEach-Object -Begin {$i=0} -Process {$p=New-Object UapMonitorDpi+POINT;$p.X=$_.Bounds.X+[Math]::Floor($_.Bounds.Width/2);$p.Y=$_.Bounds.Y+[Math]::Floor($_.Bounds.Height/2);$h=[UapMonitorDpi]::MonitorFromPoint($p,2);[uint32]$dx=96;[uint32]$dy=96;if($h -ne [IntPtr]::Zero){[void][UapMonitorDpi]::GetDpiForMonitor($h,0,[ref]$dx,[ref]$dy)};@{id=[string]$i;label=$_.DeviceName;x=$_.Bounds.X;y=$_.Bounds.Y;width=$_.Bounds.Width;height=$_.Bounds.Height;scale=[Math]::Round($dx/96,4);primary=$_.Primary};$i++});$r|ConvertTo-Json -Compress";
|
|
1197
|
+
var WINDOWS_CAPTURE = "param($id,$format,$quality) " + WINDOWS_DPI_AWARE + "Add-Type -AssemblyName System.Windows.Forms;Add-Type -AssemblyName System.Drawing;$s=@([System.Windows.Forms.Screen]::AllScreens)[$id];if(!$s){throw 'monitor'};$b=New-Object Drawing.Bitmap $s.Bounds.Width,$s.Bounds.Height;$g=[Drawing.Graphics]::FromImage($b);$g.CopyFromScreen($s.Bounds.Location,[Drawing.Point]::Empty,$s.Bounds.Size);$m=New-Object IO.MemoryStream;if($format -eq 'jpeg'){$codec=[Drawing.Imaging.ImageCodecInfo]::GetImageEncoders()|Where-Object {$_.MimeType -eq 'image/jpeg'};$p=New-Object Drawing.Imaging.EncoderParameters 1;$p.Param[0]=New-Object Drawing.Imaging.EncoderParameter ([Drawing.Imaging.Encoder]::Quality),([long]$quality);$b.Save($m,$codec,$p);$p.Dispose();$contentType='image/jpeg'}elseif($format -eq 'png'){$b.Save($m,[Drawing.Imaging.ImageFormat]::Png);$contentType='image/png'}else{throw 'format'};@{contentType=$contentType;contentBase64=[Convert]::ToBase64String($m.ToArray());width=$s.Bounds.Width;height=$s.Bounds.Height;monitorId=[string]$id}|ConvertTo-Json -Compress;$g.Dispose();$b.Dispose();$m.Dispose()";
|
|
1198
|
+
var WINDOWS_POINTER = "param($x,$y,$op,$button,$toX,$toY,$dx,$dy) " + WINDOWS_DPI_AWARE + `Add-Type -TypeDefinition 'using System;using System.Runtime.InteropServices;public class UapMouse{[DllImport("user32.dll")]public static extern bool SetCursorPos(int x,int y);[DllImport("user32.dll")]public static extern void mouse_event(uint f,uint dx,uint dy,uint d,UIntPtr e);}' ;$down=if($button -eq 'right'){8}elseif($button -eq 'middle'){32}else{2};$up=$down*2;[UapMouse]::SetCursorPos($x,$y)|Out-Null;if($op -eq 'click' -or $op -eq 'doubleClick'){1..$(if($op -eq 'doubleClick'){2}else{1})|%{[UapMouse]::mouse_event($down,0,0,0,[UIntPtr]::Zero);[UapMouse]::mouse_event($up,0,0,0,[UIntPtr]::Zero)}}elseif($op -eq 'drag'){[UapMouse]::mouse_event($down,0,0,0,[UIntPtr]::Zero);[UapMouse]::SetCursorPos($toX,$toY)|Out-Null;[UapMouse]::mouse_event($up,0,0,0,[UIntPtr]::Zero)}elseif($op -eq 'scroll'){if([int]$dy -ne 0){[UapMouse]::mouse_event(2048,0,0,[uint32]([int64](-[int]$dy*120)-band 0xffffffff),[UIntPtr]::Zero)};if([int]$dx -ne 0){[UapMouse]::mouse_event(4096,0,0,[uint32]([int64]([int]$dx*120)-band 0xffffffff),[UIntPtr]::Zero)}}elseif($op -ne 'move'){throw 'operation'}`;
|
|
1199
|
+
var WINDOWS_KEYBOARD = "param($sequence) Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.SendKeys]::SendWait($sequence)";
|
|
1200
|
+
var WINDOWS_CLIPBOARD_READ = "Add-Type -AssemblyName System.Windows.Forms;[Console]::Out.Write([System.Windows.Forms.Clipboard]::GetText())";
|
|
1201
|
+
var WINDOWS_CLIPBOARD_WRITE = "param($text) Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Clipboard]::SetText($text)";
|
|
1202
|
+
|
|
1203
|
+
// ../device-agent/src/native-services.ts
|
|
1204
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
1205
|
+
import { realpath as realpath2, stat as stat2 } from "node:fs/promises";
|
|
1206
|
+
import { win32 } from "node:path";
|
|
1207
|
+
import { promisify as promisify3 } from "node:util";
|
|
1208
|
+
var execute3 = promisify3(execFile3);
|
|
1209
|
+
async function createNativeServiceAdapter(options = {}) {
|
|
1210
|
+
const platform = options.platform ?? process.platform;
|
|
1211
|
+
const environment2 = options.environment ?? process.env;
|
|
1212
|
+
const run = options.run ?? execute3;
|
|
1213
|
+
const resolveExecutable = options.resolveExecutable ?? firstExecutable;
|
|
1214
|
+
let readCommand;
|
|
1215
|
+
let controlCommands;
|
|
1216
|
+
if (platform === "win32") {
|
|
1217
|
+
const sc = await resolveExecutable([win32.join(environment2.SystemRoot ?? "C:\\Windows", "System32", "sc.exe")], "service control").catch(() => void 0);
|
|
1218
|
+
if (!sc) return void 0;
|
|
1219
|
+
readCommand = async (name) => [sc, "query", name];
|
|
1220
|
+
controlCommands = async (name, operation) => operation === "restart" ? [
|
|
1221
|
+
[sc, "stop", name],
|
|
1222
|
+
[sc, "start", name]
|
|
1223
|
+
] : [[sc, operation, name]];
|
|
1224
|
+
} else if (platform === "linux") {
|
|
1225
|
+
const systemctl = await resolveExecutable(["/usr/bin/systemctl", "/bin/systemctl"], "service control").catch(() => void 0);
|
|
1226
|
+
if (!systemctl) return void 0;
|
|
1227
|
+
readCommand = async (name) => [systemctl, "show", name, "--no-page", "--property=Id,LoadState,ActiveState,SubState"];
|
|
1228
|
+
controlCommands = async (name, operation) => [[systemctl, operation, name]];
|
|
1229
|
+
} else {
|
|
1230
|
+
return void 0;
|
|
1231
|
+
}
|
|
1232
|
+
return {
|
|
1233
|
+
async read(name) {
|
|
1234
|
+
const output = await invoke(run, await readCommand(serviceName2(name)), "service inspection");
|
|
1235
|
+
return platform === "win32" ? parseWindowsService(name, output) : parseSystemdService(name, output);
|
|
1236
|
+
},
|
|
1237
|
+
async control(name, operation) {
|
|
1238
|
+
const normalizedName = serviceName2(name);
|
|
1239
|
+
const normalizedOperation = serviceOperation2(operation);
|
|
1240
|
+
for (const [program, ...args] of await controlCommands(normalizedName, normalizedOperation)) {
|
|
1241
|
+
await invoke(run, [program, ...args], "service control");
|
|
1242
|
+
}
|
|
1243
|
+
return { name: normalizedName, operation: normalizedOperation, accepted: true };
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
async function invoke(run, [program, ...args], label) {
|
|
1248
|
+
try {
|
|
1249
|
+
const result = await run(program, args, { encoding: "utf8", maxBuffer: 1024 * 1024, timeout: 15e3, windowsHide: true });
|
|
1250
|
+
const output = typeof result.stdout === "string" ? result.stdout : result.stdout.toString("utf8");
|
|
1251
|
+
if (Buffer.byteLength(output) > 1024 * 1024) throw new TypeError(label + " output exceeds limit");
|
|
1252
|
+
return output;
|
|
1253
|
+
} catch {
|
|
1254
|
+
throw new TypeError(label + " failed");
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
function parseWindowsService(name, output) {
|
|
1258
|
+
const state = /STATE\s*:\s*\d+\s+([A-Z_]+)/i.exec(output)?.[1]?.toLowerCase();
|
|
1259
|
+
if (!state) throw new TypeError("service inspection output is invalid");
|
|
1260
|
+
return { name, state };
|
|
1261
|
+
}
|
|
1262
|
+
function parseSystemdService(name, output) {
|
|
1263
|
+
const values = Object.fromEntries(
|
|
1264
|
+
output.split("\n").flatMap((line) => {
|
|
1265
|
+
const split = line.indexOf("=");
|
|
1266
|
+
return split > 0 ? [[line.slice(0, split), line.slice(split + 1)]] : [];
|
|
1267
|
+
})
|
|
1268
|
+
);
|
|
1269
|
+
if (!values.Id || !values.LoadState || !values.ActiveState || !values.SubState) throw new TypeError("service inspection output is invalid");
|
|
1270
|
+
return { name, id: values.Id, loadState: values.LoadState, activeState: values.ActiveState, subState: values.SubState };
|
|
1271
|
+
}
|
|
1272
|
+
async function firstExecutable(candidates, label) {
|
|
1273
|
+
for (const candidate of candidates) {
|
|
1274
|
+
try {
|
|
1275
|
+
const value = await realpath2(candidate);
|
|
1276
|
+
if ((await stat2(value)).isFile()) return value;
|
|
1277
|
+
} catch (error) {
|
|
1278
|
+
if (!isMissing2(error)) throw error;
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
throw new TypeError(label + " executable is unavailable");
|
|
1282
|
+
}
|
|
1283
|
+
function serviceName2(value) {
|
|
1284
|
+
if (typeof value !== "string" || value.length > 256 || !/^[A-Za-z0-9_.@:-]+$/.test(value)) throw new TypeError("service name is invalid");
|
|
1285
|
+
return value;
|
|
1286
|
+
}
|
|
1287
|
+
function serviceOperation2(value) {
|
|
1288
|
+
if (value !== "start" && value !== "stop" && value !== "restart") throw new TypeError("service operation is invalid");
|
|
1289
|
+
return value;
|
|
1290
|
+
}
|
|
1291
|
+
function isMissing2(error) {
|
|
1292
|
+
return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
// src/remote.ts
|
|
1296
|
+
async function runRemote(options) {
|
|
1297
|
+
const fetcher = options.fetcher ?? fetch;
|
|
1298
|
+
const deviceId = await loadRemoteDeviceId(options.stateDirectory);
|
|
1299
|
+
const desktop = await createNativeDesktopAdapter();
|
|
1300
|
+
const services = options.allowedServices.length ? await createNativeServiceAdapter() : void 0;
|
|
1301
|
+
if (options.allowedServices.length && !services) throw new TypeError("native service control is unavailable");
|
|
1302
|
+
const engine = new DeviceAgentEngine({
|
|
1303
|
+
deviceId,
|
|
1304
|
+
name: os3.hostname(),
|
|
1305
|
+
roots: options.roots,
|
|
1306
|
+
...options.allowedExecutables.length ? { allowedExecutables: options.allowedExecutables } : {},
|
|
1307
|
+
...services ? { services, allowedServices: options.allowedServices } : {},
|
|
1308
|
+
...desktop
|
|
1309
|
+
});
|
|
1310
|
+
try {
|
|
1311
|
+
let delay = 500;
|
|
1312
|
+
while (!options.signal?.aborted) {
|
|
1313
|
+
try {
|
|
1314
|
+
await remoteSession(options.origin, options.stateDirectory, engine, fetcher, options.signal);
|
|
1315
|
+
delay = 500;
|
|
1316
|
+
} catch (error) {
|
|
1317
|
+
if (options.signal?.aborted) break;
|
|
1318
|
+
if (error instanceof RemoteAuthorizationError) {
|
|
1319
|
+
await accessToken(options.stateDirectory, fetcher, true);
|
|
1320
|
+
delay = 500;
|
|
1321
|
+
continue;
|
|
1322
|
+
}
|
|
1323
|
+
if (!(error instanceof RemoteUnavailableError)) throw error;
|
|
1324
|
+
await sleep(delay, options.signal);
|
|
1325
|
+
delay = Math.min(delay * 2, 15e3);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
} finally {
|
|
1329
|
+
engine.close();
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal) {
|
|
1333
|
+
const { token } = await accessToken(stateDirectory, fetcher);
|
|
1334
|
+
const connected = await request(fetcher, origin, "/device-control/remote/connect", token, { device: engine.info() }, signal);
|
|
1335
|
+
const sessionId = bounded2(connected.sessionId, "remote session id");
|
|
1336
|
+
try {
|
|
1337
|
+
while (!signal?.aborted) {
|
|
1338
|
+
const next = await request(fetcher, origin, "/device-control/remote/poll", token, { sessionId, deviceId: engine.options.deviceId }, signal, 35e3);
|
|
1339
|
+
if (next.command === null || next.command === void 0) continue;
|
|
1340
|
+
const command = commandValue(next.command);
|
|
1341
|
+
const startedAt = Date.now();
|
|
1342
|
+
try {
|
|
1343
|
+
const output = await engine.execute(command.capability, command.parameters, { workspaceId: bounded2(next.workspaceId, "workspace id") });
|
|
1344
|
+
await request(fetcher, origin, "/device-control/remote/result", token, { sessionId, deviceId: engine.options.deviceId, requestId: command.requestId, ok: true, output, executionMs: elapsed(startedAt) }, signal);
|
|
1345
|
+
} catch (error) {
|
|
1346
|
+
await request(
|
|
1347
|
+
fetcher,
|
|
1348
|
+
origin,
|
|
1349
|
+
"/device-control/remote/result",
|
|
1350
|
+
token,
|
|
1351
|
+
{ sessionId, deviceId: engine.options.deviceId, requestId: command.requestId, ok: false, error: safeError(error), executionMs: elapsed(startedAt) },
|
|
1352
|
+
signal
|
|
1353
|
+
);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
} finally {
|
|
1357
|
+
await request(fetcher, origin, "/device-control/remote/disconnect", token, { sessionId, deviceId: engine.options.deviceId }, void 0, 5e3).catch(() => void 0);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
async function request(fetcher, origin, pathname, token, body, signal, timeoutMs = 15e3) {
|
|
1361
|
+
const controller = new AbortController();
|
|
1362
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
1363
|
+
const onAbort = () => controller.abort();
|
|
1364
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1365
|
+
try {
|
|
1366
|
+
let response;
|
|
1367
|
+
try {
|
|
1368
|
+
response = await fetcher(new URL(pathname, canonicalOrigin2(origin)), {
|
|
1369
|
+
method: "POST",
|
|
1370
|
+
headers: { "content-type": "application/json", authorization: "Bearer " + token },
|
|
1371
|
+
body: JSON.stringify(body),
|
|
1372
|
+
redirect: "error",
|
|
1373
|
+
cache: "no-store",
|
|
1374
|
+
signal: controller.signal
|
|
1375
|
+
});
|
|
1376
|
+
} catch {
|
|
1377
|
+
throw new RemoteUnavailableError();
|
|
1378
|
+
}
|
|
1379
|
+
if (response.status === 401 || response.status === 403) throw new RemoteAuthorizationError();
|
|
1380
|
+
if (!response.ok) throw new RemoteUnavailableError();
|
|
1381
|
+
const raw = await response.json();
|
|
1382
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("remote response is invalid");
|
|
1383
|
+
return raw;
|
|
1384
|
+
} finally {
|
|
1385
|
+
clearTimeout(timeout);
|
|
1386
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
async function remoteStatus(origin, stateDirectory, deviceId, fetcher = fetch) {
|
|
1390
|
+
const { token } = await accessToken(stateDirectory, fetcher);
|
|
1391
|
+
const value = await request(fetcher, origin, "/device-control/remote/status", token, { deviceId }, void 0, 5e3);
|
|
1392
|
+
if (typeof value.online !== "boolean") throw new TypeError("remote status response is invalid");
|
|
1393
|
+
const lastSeen = value.lastSeen;
|
|
1394
|
+
if (lastSeen !== void 0 && (!Number.isSafeInteger(lastSeen) || Number(lastSeen) < 0)) throw new TypeError("remote status response is invalid");
|
|
1395
|
+
return { online: value.online, ...lastSeen === void 0 ? {} : { lastSeen: Number(lastSeen) } };
|
|
1396
|
+
}
|
|
1397
|
+
function defaultRemoteRoots(cwd = process.cwd()) {
|
|
1398
|
+
return [{ id: "cwd", label: "Current directory", path: path3.resolve(cwd), readOnly: false }];
|
|
1399
|
+
}
|
|
1400
|
+
var RemoteUnavailableError = class extends Error {
|
|
1401
|
+
};
|
|
1402
|
+
var RemoteAuthorizationError = class extends Error {
|
|
1403
|
+
};
|
|
1404
|
+
function canonicalOrigin2(value) {
|
|
1405
|
+
const url = new URL(value);
|
|
1406
|
+
if (url.protocol !== "https:" || url.origin !== value || url.username || url.password) throw new TypeError("origin must be canonical HTTPS");
|
|
1407
|
+
return url.origin;
|
|
1408
|
+
}
|
|
1409
|
+
function bounded2(value, label) {
|
|
1410
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(value)) throw new TypeError(label + " is invalid");
|
|
1411
|
+
return value;
|
|
1412
|
+
}
|
|
1413
|
+
function commandValue(value) {
|
|
1414
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("remote command is invalid");
|
|
1415
|
+
const record = value;
|
|
1416
|
+
const requestId = bounded2(record.requestId, "remote request id");
|
|
1417
|
+
const capability = bounded2(record.capability, "remote capability");
|
|
1418
|
+
const parameters = record.parameters;
|
|
1419
|
+
if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) throw new TypeError("remote parameters are invalid");
|
|
1420
|
+
return { requestId, capability, parameters };
|
|
1421
|
+
}
|
|
1422
|
+
function elapsed(startedAt) {
|
|
1423
|
+
return Math.min(864e5, Math.max(0, Math.round(Date.now() - startedAt)));
|
|
1424
|
+
}
|
|
1425
|
+
function safeError(error) {
|
|
1426
|
+
return error instanceof TypeError ? error.message.slice(0, 256) : "device operation failed";
|
|
1427
|
+
}
|
|
1428
|
+
function sleep(ms, signal) {
|
|
1429
|
+
return new Promise((resolve) => {
|
|
1430
|
+
const timer = setTimeout(resolve, ms);
|
|
1431
|
+
const abort = () => {
|
|
1432
|
+
clearTimeout(timer);
|
|
1433
|
+
resolve();
|
|
1434
|
+
};
|
|
1435
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
// src/service.ts
|
|
1440
|
+
import os4 from "node:os";
|
|
1441
|
+
import path4 from "node:path";
|
|
1442
|
+
import { chmod, copyFile, mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
|
|
1443
|
+
import { execFile as execFile4 } from "node:child_process";
|
|
1444
|
+
import { promisify as promisify4 } from "node:util";
|
|
1445
|
+
var execute4 = promisify4(execFile4);
|
|
1446
|
+
async function installRemoteService(origin, stateDirectory) {
|
|
1447
|
+
const command = process.execPath;
|
|
1448
|
+
const source = process.argv[1];
|
|
1449
|
+
if (!source) throw new TypeError("CLI executable path is unavailable");
|
|
1450
|
+
await mkdir3(stateDirectory, { recursive: true, mode: 448 });
|
|
1451
|
+
const script = path4.join(stateDirectory, "uap-device-control.mjs");
|
|
1452
|
+
await copyFile(source, script);
|
|
1453
|
+
if (process.platform !== "win32") await chmod(script, 448);
|
|
1454
|
+
const args = [script, "remote", "--origin", origin, "--state-dir", stateDirectory, "--service"];
|
|
1455
|
+
if (process.platform === "linux") return installSystemd(command, args);
|
|
1456
|
+
if (process.platform === "darwin") return installLaunchd(command, args);
|
|
1457
|
+
if (process.platform === "win32") return installWindowsTask(command, args);
|
|
1458
|
+
throw new TypeError("service installation is unsupported on this platform");
|
|
1459
|
+
}
|
|
1460
|
+
async function installSystemd(command, args) {
|
|
1461
|
+
const directory = path4.join(os4.homedir(), ".config", "systemd", "user");
|
|
1462
|
+
const location = path4.join(directory, "uap-device-control.service");
|
|
1463
|
+
await mkdir3(directory, { recursive: true });
|
|
1464
|
+
await writeFile3(
|
|
1465
|
+
location,
|
|
1466
|
+
[
|
|
1467
|
+
"[Unit]",
|
|
1468
|
+
"Description=UAP Device Control Remote",
|
|
1469
|
+
"After=network-online.target",
|
|
1470
|
+
"Wants=network-online.target",
|
|
1471
|
+
"",
|
|
1472
|
+
"[Service]",
|
|
1473
|
+
"Type=simple",
|
|
1474
|
+
"ExecStart=" + systemdEscape(command, args),
|
|
1475
|
+
"Restart=on-failure",
|
|
1476
|
+
"RestartSec=5",
|
|
1477
|
+
"",
|
|
1478
|
+
"[Install]",
|
|
1479
|
+
"WantedBy=default.target",
|
|
1480
|
+
""
|
|
1481
|
+
].join("\n"),
|
|
1482
|
+
{ mode: 384 }
|
|
1483
|
+
);
|
|
1484
|
+
await execute4("systemctl", ["--user", "daemon-reload"]);
|
|
1485
|
+
await execute4("systemctl", ["--user", "enable", "--now", "uap-device-control.service"]);
|
|
1486
|
+
return { platform: "linux", location };
|
|
1487
|
+
}
|
|
1488
|
+
async function installLaunchd(command, args) {
|
|
1489
|
+
const directory = path4.join(os4.homedir(), "Library", "LaunchAgents");
|
|
1490
|
+
const location = path4.join(directory, "ro.codingfrees.uap-device-control.plist");
|
|
1491
|
+
await mkdir3(directory, { recursive: true });
|
|
1492
|
+
const escaped = [command, ...args].map((value) => "<string>" + xml(value) + "</string>").join("");
|
|
1493
|
+
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>";
|
|
1494
|
+
await writeFile3(location, plist, { mode: 384 });
|
|
1495
|
+
const domain = "gui/" + process.getuid?.();
|
|
1496
|
+
await execute4("launchctl", ["bootout", domain, location]).catch(() => void 0);
|
|
1497
|
+
await execute4("launchctl", ["bootstrap", domain, location]);
|
|
1498
|
+
return { platform: "darwin", location };
|
|
1499
|
+
}
|
|
1500
|
+
async function installWindowsTask(command, args) {
|
|
1501
|
+
const location = "UAP Device Control";
|
|
1502
|
+
const taskCommand = quoteWindows(command) + " " + args.map(quoteWindows).join(" ");
|
|
1503
|
+
await execute4("schtasks.exe", ["/Create", "/F", "/SC", "ONLOGON", "/TN", location, "/TR", taskCommand]);
|
|
1504
|
+
await execute4("schtasks.exe", ["/Run", "/TN", location]);
|
|
1505
|
+
return { platform: "win32", location };
|
|
1506
|
+
}
|
|
1507
|
+
function systemdEscape(command, args) {
|
|
1508
|
+
return [command, ...args].map((value) => '"' + value.replaceAll("\\", "\\\\").replaceAll('"', '\\"') + '"').join(" ");
|
|
1509
|
+
}
|
|
1510
|
+
function quoteWindows(value) {
|
|
1511
|
+
return '"' + value.replaceAll('"', '\\"') + '"';
|
|
1512
|
+
}
|
|
1513
|
+
function xml(value) {
|
|
1514
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// src/cli.ts
|
|
1518
|
+
function parseDeviceControlArguments(args, cwd = process.cwd()) {
|
|
1519
|
+
const command = args[0];
|
|
1520
|
+
if (!["remote", "status", "login", "logout", "install-service"].includes(command ?? "")) throw new TypeError("command must be remote, status, login, logout, or install-service");
|
|
1521
|
+
let origin = process.env.UAP_DEVICE_CONTROL_ORIGIN;
|
|
1522
|
+
let stateDirectory = defaultDeviceControlStateDirectory();
|
|
1523
|
+
const roots = [];
|
|
1524
|
+
const allowedExecutables = [];
|
|
1525
|
+
const allowedServices = [];
|
|
1526
|
+
let service = false;
|
|
1527
|
+
for (let index = 1; index < args.length; index++) {
|
|
1528
|
+
const option = args[index];
|
|
1529
|
+
const value = args[index + 1];
|
|
1530
|
+
if (option === "--origin") origin = required(value, option), index++;
|
|
1531
|
+
else if (option === "--state-dir") stateDirectory = absolute(value, option), index++;
|
|
1532
|
+
else if (option === "--root" || option === "--read-only-root") {
|
|
1533
|
+
roots.push(root(required(value, option), option === "--read-only-root"));
|
|
1534
|
+
index++;
|
|
1535
|
+
} else if (option === "--allow-executable") allowedExecutables.push(absolute(value, option)), index++;
|
|
1536
|
+
else if (option === "--allow-service") allowedServices.push(identifier(value, option)), index++;
|
|
1537
|
+
else if (option === "--service") service = true;
|
|
1538
|
+
else throw new TypeError("unsupported UAP Device Control option: " + option);
|
|
1539
|
+
}
|
|
1540
|
+
const normalizedOrigin = origin === void 0 ? void 0 : canonicalOrigin3(origin);
|
|
1541
|
+
if (!roots.length && command === "remote") roots.push(...defaultRemoteRoots(cwd));
|
|
1542
|
+
return { command, ...normalizedOrigin ? { origin: normalizedOrigin } : {}, stateDirectory, roots, allowedExecutables, allowedServices, service };
|
|
1543
|
+
}
|
|
1544
|
+
async function runDeviceControlCli(args = process.argv.slice(2)) {
|
|
1545
|
+
const config = parseDeviceControlArguments(args);
|
|
1546
|
+
const existingAuth = await loadRemoteAuth(config.stateDirectory);
|
|
1547
|
+
const resolvedOrigin = resolveConfiguredOrigin(config.origin, existingAuth?.origin);
|
|
1548
|
+
if (config.command === "login") {
|
|
1549
|
+
if (!resolvedOrigin) throw new TypeError("origin is required for first login; use --origin or UAP_DEVICE_CONTROL_ORIGIN");
|
|
1550
|
+
const auth = await loginDeviceControl(resolvedOrigin, config.stateDirectory);
|
|
1551
|
+
process.stdout.write(JSON.stringify({ status: "authenticated", origin: auth.origin }) + "\n");
|
|
1552
|
+
return;
|
|
1553
|
+
}
|
|
1554
|
+
if (config.command === "logout") {
|
|
1555
|
+
process.stdout.write(JSON.stringify({ status: await logoutDeviceControl(config.stateDirectory) ? "logged-out" : "not-logged-in" }) + "\n");
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
if (config.command === "status") {
|
|
1559
|
+
const [auth, deviceId] = await Promise.all([Promise.resolve(existingAuth), loadRemoteDeviceId(config.stateDirectory)]);
|
|
1560
|
+
const deviceAuthorized = Boolean(auth?.scope.split(" ").includes("device-control:device"));
|
|
1561
|
+
let remote;
|
|
1562
|
+
if (auth && deviceAuthorized) remote = await remoteStatus(auth.origin, config.stateDirectory, deviceId).catch(() => ({ online: false }));
|
|
1563
|
+
process.stdout.write(
|
|
1564
|
+
JSON.stringify({ deviceId, origin: auth?.origin ?? config.origin ?? null, authenticated: Boolean(auth), deviceAuthorized, remote: remote ?? null, serviceMode: config.service, platform: process.platform }) + "\n"
|
|
1565
|
+
);
|
|
1566
|
+
return;
|
|
1567
|
+
}
|
|
1568
|
+
if (config.command === "install-service") {
|
|
1569
|
+
if (!existingAuth) throw new TypeError("login is required before install-service");
|
|
1570
|
+
if (!resolvedOrigin) throw new TypeError("origin is unavailable");
|
|
1571
|
+
process.stdout.write(JSON.stringify({ status: "installed", ...await installRemoteService(resolvedOrigin, config.stateDirectory) }) + "\n");
|
|
1572
|
+
return;
|
|
1573
|
+
}
|
|
1574
|
+
if (!existingAuth) {
|
|
1575
|
+
if (config.service) throw new TypeError("service mode requires login");
|
|
1576
|
+
if (!resolvedOrigin) throw new TypeError("origin is required for first remote connection; use --origin or UAP_DEVICE_CONTROL_ORIGIN");
|
|
1577
|
+
await loginDeviceControl(resolvedOrigin, config.stateDirectory);
|
|
1578
|
+
}
|
|
1579
|
+
const controller = new AbortController();
|
|
1580
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => controller.abort());
|
|
1581
|
+
const remoteOrigin = resolvedOrigin ?? existingAuth?.origin;
|
|
1582
|
+
if (!remoteOrigin) throw new TypeError("origin is unavailable");
|
|
1583
|
+
process.stdout.write(JSON.stringify({ status: "connecting", origin: remoteOrigin, platform: process.platform }) + "\n");
|
|
1584
|
+
await runRemote({ origin: remoteOrigin, stateDirectory: config.stateDirectory, roots: config.roots, allowedExecutables: config.allowedExecutables, allowedServices: config.allowedServices, signal: controller.signal });
|
|
1585
|
+
}
|
|
1586
|
+
function resolveConfiguredOrigin(explicit, stored) {
|
|
1587
|
+
if (explicit && stored && explicit !== stored) throw new TypeError("configured origin does not match the authenticated origin; logout before changing environments");
|
|
1588
|
+
return explicit ?? stored;
|
|
1589
|
+
}
|
|
1590
|
+
function canonicalOrigin3(value) {
|
|
1591
|
+
const url = new URL(value);
|
|
1592
|
+
if (url.protocol !== "https:" || url.origin !== value || url.username || url.password) throw new TypeError("origin must be canonical HTTPS");
|
|
1593
|
+
return url.origin;
|
|
1594
|
+
}
|
|
1595
|
+
function required(value, label) {
|
|
1596
|
+
if (!value || value.includes("\0") || value.length > 4096) throw new TypeError(label + " is invalid");
|
|
1597
|
+
return value;
|
|
1598
|
+
}
|
|
1599
|
+
function absolute(value, label) {
|
|
1600
|
+
const resolved = required(value, label);
|
|
1601
|
+
if (!path5.isAbsolute(resolved)) throw new TypeError(label + " must be absolute");
|
|
1602
|
+
return path5.resolve(resolved);
|
|
1603
|
+
}
|
|
1604
|
+
function identifier(value, label) {
|
|
1605
|
+
const result = required(value, label);
|
|
1606
|
+
if (!/^[A-Za-z0-9_.@:-]{1,256}$/.test(result)) throw new TypeError(label + " is invalid");
|
|
1607
|
+
return result;
|
|
1608
|
+
}
|
|
1609
|
+
function root(value, readOnly) {
|
|
1610
|
+
const split = value.indexOf("=");
|
|
1611
|
+
if (split < 1) throw new TypeError("root must use id=absolute-path");
|
|
1612
|
+
const id = identifier(value.slice(0, split), "root id");
|
|
1613
|
+
return { id, label: id, path: absolute(value.slice(split + 1), "root path"), readOnly };
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
// src/bin.ts
|
|
1617
|
+
runDeviceControlCli().catch((error) => {
|
|
1618
|
+
process.stderr.write(JSON.stringify({ error: error instanceof Error ? error.message : "UAP Device Control failed" }) + "\n");
|
|
1619
|
+
process.exitCode = 1;
|
|
1620
|
+
});
|