@amd-gaia/agent-ui 0.26.1-rc.2 → 0.27.0-rc.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/dist/assets/AdvancedSettings-DHERtrno.js +1 -0
- package/dist/assets/AutomationsSettings-4FWcRau9.js +1 -0
- package/dist/assets/ConnectorsPane-BGI8nBUb.css +1 -0
- package/dist/assets/ConnectorsPane-Dkat1zLC.js +1 -0
- package/dist/assets/DocumentLibrary-Dll55N7l.js +5 -0
- package/dist/assets/DocumentLibrary-fEMoY7lH.css +1 -0
- package/dist/assets/FileBrowser-1goNp4CP.css +1 -0
- package/dist/assets/FileBrowser-wFHqH6K_.js +4 -0
- package/dist/assets/MemoryDashboard-BuUBoNq8.js +1 -0
- package/dist/assets/MemoryDashboard-RpfLag-v.css +1 -0
- package/dist/assets/MessagingSettings-DomiT2rX.js +1 -0
- package/dist/assets/MobileAccessModal-B2gaE8nk.js +2 -0
- package/dist/assets/{MobileAccessModal-CX4NZmr4.css → MobileAccessModal-BrZMaERi.css} +1 -1
- package/dist/assets/ScheduleManager-8UE81KlQ.js +1 -0
- package/dist/assets/ScheduleManager-BZzEH2-W.css +1 -0
- package/dist/assets/Temml-CCjoacWt.woff2 +0 -0
- package/dist/assets/index-BiETDNik.css +1 -0
- package/dist/assets/index-HCZ86cyP.js +220 -0
- package/dist/assets/useFocusTrap-BFi0chLf.js +6 -0
- package/dist/assets/zap-DjkIffnX.js +1 -0
- package/dist/index.html +3 -3
- package/dist/sw.js +1 -1
- package/main.cjs +130 -40
- package/package.json +5 -3
- package/preload.cjs +28 -0
- package/services/browser-pane/bridge-error.cjs +20 -0
- package/services/browser-pane/bridge-server.cjs +496 -0
- package/services/browser-pane/cdp-session.cjs +375 -0
- package/services/browser-pane/contract.d.ts +448 -0
- package/services/browser-pane/dev-servers.cjs +478 -0
- package/services/browser-pane/input.cjs +375 -0
- package/services/browser-pane/ipc.cjs +267 -0
- package/services/browser-pane/navigation-policy.cjs +255 -0
- package/services/browser-pane/pane-host.cjs +1686 -0
- package/services/browser-pane/picker-world.js +360 -0
- package/services/browser-pane/picker.cjs +261 -0
- package/services/browser-pane/service-ports.cjs +66 -0
- package/services/dev-qa-mode.cjs +32 -0
- package/dist/assets/AdvancedSettings-C-9ErldS.js +0 -1
- package/dist/assets/AutomationsSettings-CL3K4hLZ.js +0 -1
- package/dist/assets/ConnectorsPane-DpGR78cA.js +0 -1
- package/dist/assets/ConnectorsPane-w-HLcq3n.css +0 -1
- package/dist/assets/DocumentLibrary-BKZdx6rJ.css +0 -1
- package/dist/assets/DocumentLibrary-N7tBbt9v.js +0 -5
- package/dist/assets/FileBrowser-CO2p3xa2.js +0 -4
- package/dist/assets/FileBrowser-CrRQXiPo.css +0 -1
- package/dist/assets/MemoryDashboard-1OIrKFIa.js +0 -1
- package/dist/assets/MemoryDashboard-B4AO_CU8.css +0 -1
- package/dist/assets/MessagingSettings-0AJnsoWA.js +0 -1
- package/dist/assets/MobileAccessModal-CnPB1BEN.js +0 -2
- package/dist/assets/ScheduleManager-BYOhqnfv.js +0 -1
- package/dist/assets/ScheduleManager-DQBnf_IN.css +0 -1
- package/dist/assets/index-Bkx-QRv4.css +0 -1
- package/dist/assets/index-C-3wCH_s.js +0 -116
- package/dist/assets/useT-DuzpQY8p.js +0 -6
- package/dist/assets/zap-gF9QDKfa.js +0 -1
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
// Copyright(C) 2026 Advanced Micro Devices, Inc. All rights reserved.
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The browser pane's bridge: how the GAIA agent, in the backend or in a
|
|
6
|
+
* daemon sidecar, reaches the pane. A loopback HTTP server with a bearer
|
|
7
|
+
* token, announced in a discovery file only the user can read.
|
|
8
|
+
*
|
|
9
|
+
* Thin by design. It refuses anything a web page or a rebound DNS name could
|
|
10
|
+
* send, parses each body into a typed op, and hands it to PaneHost. Python's
|
|
11
|
+
* half is gaia/browser/_pane_bridge.py; both test against
|
|
12
|
+
* tests/fixtures/browser_pane/bridge/*.json.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
"use strict";
|
|
16
|
+
|
|
17
|
+
const crypto = require("crypto");
|
|
18
|
+
const fs = require("fs");
|
|
19
|
+
const http = require("http");
|
|
20
|
+
const path = require("path");
|
|
21
|
+
const { BridgeError } = require("./bridge-error.cjs");
|
|
22
|
+
const { KEYS } = require("./input.cjs");
|
|
23
|
+
const { envNameAllowed } = require("./dev-servers.cjs");
|
|
24
|
+
|
|
25
|
+
/** @typedef {import("./contract").BridgeDiscovery} BridgeDiscovery */
|
|
26
|
+
/** @typedef {import("./contract").BridgeOp} BridgeOp */
|
|
27
|
+
|
|
28
|
+
const BRIDGE_PROTOCOL = 1;
|
|
29
|
+
/** Env var naming the discovery file for the backend main starts. Python reads it first. */
|
|
30
|
+
const DISCOVERY_ENV = "GAIA_BROWSER_PANE_DISCOVERY";
|
|
31
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
32
|
+
const MAX_SCRIPT_CHARS = 512 * 1024;
|
|
33
|
+
const MAX_LOG_LIMIT = 500;
|
|
34
|
+
const MAX_SHOT_WIDTH = 4096;
|
|
35
|
+
const MAX_TYPED_CHARS = 10000;
|
|
36
|
+
const MAX_EXPRESSION_CHARS = 2000;
|
|
37
|
+
const VIEWPORT_MIN = 200;
|
|
38
|
+
const VIEWPORT_MAX = 4000;
|
|
39
|
+
const MAX_ARGV = 64;
|
|
40
|
+
const MAX_READY_MS = 120000;
|
|
41
|
+
|
|
42
|
+
const STATUS = {
|
|
43
|
+
bad_request: 400,
|
|
44
|
+
unauthorized: 401,
|
|
45
|
+
forbidden: 403,
|
|
46
|
+
unknown_op: 404,
|
|
47
|
+
no_such_tab: 404,
|
|
48
|
+
timeout: 504,
|
|
49
|
+
internal: 500,
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Where the discovery file goes. Dev QA mode keeps it in the throwaway user
|
|
54
|
+
* data dir, so a dev build never overwrites the installed app's file.
|
|
55
|
+
*
|
|
56
|
+
* @param {{ devQa: boolean, userDataDir: string, gaiaDir: string }} where
|
|
57
|
+
*/
|
|
58
|
+
function discoveryPath({ devQa, userDataDir, gaiaDir }) {
|
|
59
|
+
return devQa ? path.join(userDataDir, "run", "browser-pane.json") : path.join(gaiaDir, "run", "browser-pane.json");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ── Parsing ─────────────────────────────────────────────────────────────
|
|
63
|
+
|
|
64
|
+
const bad = (message) => new BridgeError("bad_request", message);
|
|
65
|
+
|
|
66
|
+
function str(body, key, { max = 4096 } = {}) {
|
|
67
|
+
const v = body[key];
|
|
68
|
+
if (typeof v !== "string" || v === "" || v.length > max) throw bad(`"${key}" must be a non-empty string of at most ${max} characters.`);
|
|
69
|
+
return v;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const session = (body) => str(body, "sessionId", { max: 200 });
|
|
73
|
+
|
|
74
|
+
function tabIdOrActive(body) {
|
|
75
|
+
const v = body.tabId;
|
|
76
|
+
if (v === null || v === undefined) return null;
|
|
77
|
+
if (typeof v !== "string" || v === "") throw bad('"tabId" must be a tab id or null for the active tab.');
|
|
78
|
+
return v;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function bool(body, key) {
|
|
82
|
+
if (typeof body[key] !== "boolean") throw bad(`"${key}" must be true or false.`);
|
|
83
|
+
return body[key];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function int(body, key, min, max) {
|
|
87
|
+
const v = body[key];
|
|
88
|
+
if (!Number.isInteger(v) || v < min || v > max) throw bad(`"${key}" must be a whole number from ${min} to ${max}.`);
|
|
89
|
+
return v;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function oneOf(body, key, values) {
|
|
93
|
+
if (!values.includes(body[key])) throw bad(`"${key}" must be one of ${values.join(", ")}.`);
|
|
94
|
+
return body[key];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Origins exactly as URL.origin spells them; anything looser could widen the scope. */
|
|
98
|
+
function origins(body) {
|
|
99
|
+
const v = body.allowedOrigins;
|
|
100
|
+
if (!Array.isArray(v)) throw bad('"allowedOrigins" must be a list of origins.');
|
|
101
|
+
for (const o of v) {
|
|
102
|
+
let parsed = null;
|
|
103
|
+
try {
|
|
104
|
+
parsed = typeof o === "string" ? new URL(o) : null;
|
|
105
|
+
} catch {
|
|
106
|
+
parsed = null;
|
|
107
|
+
}
|
|
108
|
+
if (!parsed || !/^https?:$/.test(parsed.protocol) || parsed.origin !== o) {
|
|
109
|
+
throw bad(`"allowedOrigins" holds ${JSON.stringify(o)}, which is not an http(s) origin like https://example.com.`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return v;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** An element: { frameId, selector }, with frameId null for the main frame. */
|
|
116
|
+
function element(value, key) {
|
|
117
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw bad(`"${key}" must be { frameId, selector }.`);
|
|
118
|
+
const frameId = value.frameId;
|
|
119
|
+
if (frameId !== null && typeof frameId !== "string") throw bad(`"${key}.frameId" must be a frame id or null.`);
|
|
120
|
+
return { frameId, selector: str(value, "selector", { max: 200 }) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function action(body) {
|
|
124
|
+
const a = body.action;
|
|
125
|
+
if (typeof a !== "object" || a === null) throw bad('"action" must be { kind, ... }.');
|
|
126
|
+
const kind = oneOf(a, "kind", ["click", "fill", "press"]);
|
|
127
|
+
if (kind === "click") return { kind };
|
|
128
|
+
if (kind === "press") return { kind, key: oneOf(a, "key", Object.keys(KEYS)) };
|
|
129
|
+
if (typeof a.text !== "string" || a.text.length > MAX_TYPED_CHARS) throw bad(`"action.text" must be text of at most ${MAX_TYPED_CHARS} characters.`);
|
|
130
|
+
return { kind, text: a.text, pressEnter: bool(a, "pressEnter") };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function viewportSize(body) {
|
|
134
|
+
const v = body.size;
|
|
135
|
+
if (v === null) return null;
|
|
136
|
+
if (typeof v !== "object" || Array.isArray(v)) throw bad('"size" must be null or { width, height, mobile }.');
|
|
137
|
+
return { width: int(v, "width", VIEWPORT_MIN, VIEWPORT_MAX), height: int(v, "height", VIEWPORT_MIN, VIEWPORT_MAX), mobile: bool(v, "mobile") };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const serverKey = (body) => {
|
|
141
|
+
const key = str(body, "key", { max: 16 });
|
|
142
|
+
if (!/^[0-9a-f]{16}$/.test(key)) throw bad('"key" must be 16 hex digits.');
|
|
143
|
+
return key;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/** A dev server as Python resolved it from launch.json: argv only, an absolute cwd, allowed env names. */
|
|
147
|
+
function devServerSpec(value) {
|
|
148
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw bad('"spec" must be a dev server spec.');
|
|
149
|
+
const argv = value.argv;
|
|
150
|
+
if (!Array.isArray(argv) || argv.length === 0 || argv.length > MAX_ARGV || !argv.every((a) => typeof a === "string" && a !== "" && a.length <= 4096 && !a.includes("\0"))) {
|
|
151
|
+
throw bad(`"spec.argv" must be 1 to ${MAX_ARGV} non-empty strings.`);
|
|
152
|
+
}
|
|
153
|
+
const cwd = str(value, "cwd");
|
|
154
|
+
if (!path.isAbsolute(cwd)) throw bad('"spec.cwd" must be an absolute folder.');
|
|
155
|
+
const port = int(value, "port", 1024, 65535);
|
|
156
|
+
const env = value.env;
|
|
157
|
+
if (typeof env !== "object" || env === null || Array.isArray(env)) throw bad('"spec.env" must be an object.');
|
|
158
|
+
for (const [k, v] of Object.entries(env)) {
|
|
159
|
+
if (!envNameAllowed(k) || typeof v !== "string" || v.length > 4096) throw bad(`"spec.env" may not set ${JSON.stringify(k)}.`);
|
|
160
|
+
}
|
|
161
|
+
const url = str(value, "url");
|
|
162
|
+
let parsed = null;
|
|
163
|
+
try {
|
|
164
|
+
parsed = new URL(url);
|
|
165
|
+
} catch {
|
|
166
|
+
parsed = null;
|
|
167
|
+
}
|
|
168
|
+
if (!parsed || parsed.protocol !== "http:" || parsed.hostname !== "localhost" || Number(parsed.port) !== port) {
|
|
169
|
+
throw bad(`"spec.url" must be http://localhost:${port}/...`);
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
name: str(value, "name", { max: 64 }),
|
|
173
|
+
argv: argv.slice(),
|
|
174
|
+
cwd,
|
|
175
|
+
port,
|
|
176
|
+
env: { ...env },
|
|
177
|
+
url,
|
|
178
|
+
readyTimeoutMs: int(value, "readyTimeoutMs", 1000, MAX_READY_MS),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** One parser per op. A test asserts this table and the handler table have the same keys. */
|
|
183
|
+
const PARSERS = {
|
|
184
|
+
hello: () => ({}),
|
|
185
|
+
attach: (b) => ({ sessionId: str(b, "sessionId", { max: 200 }) }),
|
|
186
|
+
tabs: (b) => {
|
|
187
|
+
const sessionId = session(b);
|
|
188
|
+
const op = oneOf(b, "op", ["list", "open", "select"]);
|
|
189
|
+
if (op === "open") return { sessionId, op, url: str(b, "url"), allowedOrigins: origins(b) };
|
|
190
|
+
if (op === "select") return { sessionId, op, tabId: str(b, "tabId", { max: 100 }) };
|
|
191
|
+
return { sessionId, op };
|
|
192
|
+
},
|
|
193
|
+
navigate: (b) => ({ sessionId: session(b), tabId: tabIdOrActive(b), to: str(b, "to"), allowedOrigins: origins(b) }),
|
|
194
|
+
evaluate: (b) => {
|
|
195
|
+
if (!("args" in b)) throw bad('"args" is required (use null for none).');
|
|
196
|
+
return {
|
|
197
|
+
sessionId: session(b),
|
|
198
|
+
tabId: tabIdOrActive(b),
|
|
199
|
+
script: str(b, "script", { max: MAX_SCRIPT_CHARS }),
|
|
200
|
+
args: b.args,
|
|
201
|
+
frames: oneOf(b, "frames", ["main", "all"]),
|
|
202
|
+
allowedOrigins: origins(b),
|
|
203
|
+
};
|
|
204
|
+
},
|
|
205
|
+
origin: (b) => ({ sessionId: session(b), tabId: tabIdOrActive(b) }),
|
|
206
|
+
screenshot: (b) => {
|
|
207
|
+
const clip = b.clip === null || b.clip === undefined ? null : element(b.clip, "clip");
|
|
208
|
+
return { sessionId: session(b), tabId: tabIdOrActive(b), clip, maxWidth: int(b, "maxWidth", 100, MAX_SHOT_WIDTH), allowedOrigins: origins(b) };
|
|
209
|
+
},
|
|
210
|
+
logs: (b) => {
|
|
211
|
+
const pattern = b.pattern;
|
|
212
|
+
if (pattern !== null && pattern !== undefined && (typeof pattern !== "string" || pattern.length > 200)) {
|
|
213
|
+
throw bad('"pattern" must be null or text of at most 200 characters.');
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
sessionId: session(b),
|
|
217
|
+
tabId: tabIdOrActive(b),
|
|
218
|
+
kind: oneOf(b, "kind", ["console", "network"]),
|
|
219
|
+
afterSeq: int(b, "afterSeq", 0, Number.MAX_SAFE_INTEGER),
|
|
220
|
+
errorsOnly: bool(b, "errorsOnly"),
|
|
221
|
+
pattern: pattern || null,
|
|
222
|
+
limit: int(b, "limit", 1, MAX_LOG_LIMIT),
|
|
223
|
+
allowedOrigins: origins(b),
|
|
224
|
+
};
|
|
225
|
+
},
|
|
226
|
+
act: (b) => {
|
|
227
|
+
const act = action(b);
|
|
228
|
+
const target = b.target === null || b.target === undefined ? null : element(b.target, "target");
|
|
229
|
+
if (target === null && act.kind !== "press") throw bad(`A ${act.kind} needs a "target" element.`);
|
|
230
|
+
return { sessionId: session(b), tabId: tabIdOrActive(b), action: act, target, allowedOrigins: origins(b) };
|
|
231
|
+
},
|
|
232
|
+
devServers: (b) => {
|
|
233
|
+
const sessionId = session(b);
|
|
234
|
+
const op = oneOf(b, "op", ["ensure", "stop", "list", "logs"]);
|
|
235
|
+
if (op === "list") return { sessionId, op };
|
|
236
|
+
if (op === "stop") return { sessionId, op, key: serverKey(b) };
|
|
237
|
+
if (op === "ensure") {
|
|
238
|
+
const searchPath = b.searchPath;
|
|
239
|
+
if (searchPath !== null && (typeof searchPath !== "string" || searchPath.length > 32768)) {
|
|
240
|
+
throw bad('"searchPath" must be null or a PATH string of at most 32768 characters.');
|
|
241
|
+
}
|
|
242
|
+
return { sessionId, op, key: serverKey(b), spec: devServerSpec(b.spec), searchPath: searchPath || null };
|
|
243
|
+
}
|
|
244
|
+
const pattern = b.pattern;
|
|
245
|
+
if (pattern !== null && (typeof pattern !== "string" || pattern.length > 200)) throw bad('"pattern" must be null or text of at most 200 characters.');
|
|
246
|
+
return { sessionId, op, key: serverKey(b), errorsOnly: bool(b, "errorsOnly"), pattern: pattern || null, limit: int(b, "limit", 1, MAX_LOG_LIMIT) };
|
|
247
|
+
},
|
|
248
|
+
dialog: (b) => {
|
|
249
|
+
const sessionId = session(b);
|
|
250
|
+
const op = oneOf(b, "op", ["get", "answer", "release"]);
|
|
251
|
+
if (op === "release") return { sessionId, op };
|
|
252
|
+
if (op === "get") return { sessionId, op, tabId: tabIdOrActive(b) };
|
|
253
|
+
const text = b.text;
|
|
254
|
+
if (text !== null && (typeof text !== "string" || text.length > MAX_TYPED_CHARS)) throw bad(`"text" must be null or text of at most ${MAX_TYPED_CHARS} characters.`);
|
|
255
|
+
return { sessionId, op, tabId: tabIdOrActive(b), accept: bool(b, "accept"), text, allowedOrigins: origins(b) };
|
|
256
|
+
},
|
|
257
|
+
script: (b) => ({
|
|
258
|
+
sessionId: session(b),
|
|
259
|
+
tabId: tabIdOrActive(b),
|
|
260
|
+
expression: str(b, "expression", { max: MAX_EXPRESSION_CHARS }),
|
|
261
|
+
allowedOrigins: origins(b),
|
|
262
|
+
}),
|
|
263
|
+
viewport: (b) => ({
|
|
264
|
+
sessionId: session(b),
|
|
265
|
+
tabId: tabIdOrActive(b),
|
|
266
|
+
size: viewportSize(b),
|
|
267
|
+
colorScheme: b.colorScheme === null ? null : oneOf(b, "colorScheme", ["light", "dark"]),
|
|
268
|
+
}),
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* @param {string} op
|
|
273
|
+
* @param {unknown} body
|
|
274
|
+
* @returns {{ op: BridgeOp, req: any }}
|
|
275
|
+
*/
|
|
276
|
+
function parseRequest(op, body) {
|
|
277
|
+
if (!Object.prototype.hasOwnProperty.call(PARSERS, op)) {
|
|
278
|
+
throw new BridgeError("unknown_op", `Unknown bridge op "${op}". Known: ${Object.keys(PARSERS).join(", ")}.`);
|
|
279
|
+
}
|
|
280
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) throw bad("The request body must be a JSON object.");
|
|
281
|
+
return { op, req: PARSERS[op](body) };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// ── Handlers ────────────────────────────────────────────────────────────
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* @param {{
|
|
288
|
+
* getHost: () => import("./pane-host.cjs").PaneHost | null,
|
|
289
|
+
* devServers: import("./dev-servers.cjs").DevServerSupervisor,
|
|
290
|
+
* appVersion: string,
|
|
291
|
+
* }} deps
|
|
292
|
+
*/
|
|
293
|
+
// Dev servers in these states may still answer on their port.
|
|
294
|
+
const LIVE_SERVER = new Set(["starting", "ready"]);
|
|
295
|
+
|
|
296
|
+
/** Where a dev server GAIA started answers. Python's dev_server_origins is the same rule (bridge/dev_server_origins.json). */
|
|
297
|
+
function devServerOrigins(port) {
|
|
298
|
+
return ["localhost", "127.0.0.1", "[::1]"].map((host) => `http://${host}:${port}`);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function createHandlers({ getHost, devServers, appVersion }) {
|
|
302
|
+
// The chat's own running dev servers need no approval; any other page, localhost included, does.
|
|
303
|
+
const scope = (req) => [
|
|
304
|
+
...req.allowedOrigins,
|
|
305
|
+
...devServers.list(req.sessionId).filter((s) => LIVE_SERVER.has(s.status)).flatMap((s) => devServerOrigins(s.port)),
|
|
306
|
+
];
|
|
307
|
+
// Every op after attach is checked again: the user may have switched chats since.
|
|
308
|
+
const host = (sessionId) => {
|
|
309
|
+
const h = getHost();
|
|
310
|
+
if (!h) throw new BridgeError("no_page", "GAIA desktop's window is closed, so its browser pane is too. Ask the user to reopen it.");
|
|
311
|
+
h.requireSession(sessionId);
|
|
312
|
+
return h;
|
|
313
|
+
};
|
|
314
|
+
return {
|
|
315
|
+
hello: async () => ({ protocol: BRIDGE_PROTOCOL, appVersion, ops: Object.keys(PARSERS) }),
|
|
316
|
+
attach: async ({ sessionId }) => {
|
|
317
|
+
const h = getHost();
|
|
318
|
+
return h ? h.attachSession(sessionId) : { status: "not_in_desktop" };
|
|
319
|
+
},
|
|
320
|
+
tabs: async (req) => {
|
|
321
|
+
const h = host(req.sessionId);
|
|
322
|
+
if (req.op === "open") return h.agentOpen(req.sessionId, req.url, scope(req));
|
|
323
|
+
if (req.op === "select") return h.agentSelect(req.sessionId, req.tabId);
|
|
324
|
+
return h.listTabs(req.sessionId);
|
|
325
|
+
},
|
|
326
|
+
navigate: async (req) => host(req.sessionId).agentNavigate(req.sessionId, req.tabId, req.to, scope(req)),
|
|
327
|
+
evaluate: async (req) => host(req.sessionId).agentEvaluate(req.sessionId, req.tabId, req.script, req.args, req.frames, scope(req)),
|
|
328
|
+
origin: async (req) => host(req.sessionId).agentOrigin(req.sessionId, req.tabId),
|
|
329
|
+
screenshot: async (req) => host(req.sessionId).agentScreenshot(req.sessionId, req.tabId, req.clip, req.maxWidth, scope(req)),
|
|
330
|
+
logs: async (req) =>
|
|
331
|
+
host(req.sessionId).agentLogs(
|
|
332
|
+
req.sessionId,
|
|
333
|
+
req.tabId,
|
|
334
|
+
{ kind: req.kind, afterSeq: req.afterSeq, errorsOnly: req.errorsOnly, pattern: req.pattern, limit: req.limit },
|
|
335
|
+
scope(req)
|
|
336
|
+
),
|
|
337
|
+
act: async (req) => host(req.sessionId).agentAct(req.sessionId, req.tabId, req.action, req.target, scope(req)),
|
|
338
|
+
dialog: async (req) => {
|
|
339
|
+
const h = host(req.sessionId);
|
|
340
|
+
if (req.op === "release") return h.releaseDialogs(req.sessionId);
|
|
341
|
+
if (req.op === "get") return h.agentDialog(req.sessionId, req.tabId);
|
|
342
|
+
return h.agentAnswerDialog(req.sessionId, req.tabId, req.accept, req.text, scope(req));
|
|
343
|
+
},
|
|
344
|
+
script: async (req) => host(req.sessionId).agentScript(req.sessionId, req.tabId, req.expression, scope(req)),
|
|
345
|
+
viewport: async (req) => host(req.sessionId).agentViewport(req.sessionId, req.tabId, { size: req.size, colorScheme: req.colorScheme }),
|
|
346
|
+
devServers: async (req) => {
|
|
347
|
+
host(req.sessionId);
|
|
348
|
+
if (req.op === "list") return { servers: devServers.list(req.sessionId) };
|
|
349
|
+
if (req.op === "stop") return { server: await devServers.stop(req.key, req.sessionId) };
|
|
350
|
+
if (req.op === "logs") return devServers.logs(req.key, { errorsOnly: req.errorsOnly, pattern: req.pattern, limit: req.limit }, req.sessionId);
|
|
351
|
+
return devServers.ensure(req.key, req.spec, req.sessionId, req.searchPath);
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ── Server ──────────────────────────────────────────────────────────────
|
|
357
|
+
|
|
358
|
+
function send(res, status, payload) {
|
|
359
|
+
const body = JSON.stringify(payload);
|
|
360
|
+
res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
|
|
361
|
+
res.end(body);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function sendError(res, err) {
|
|
365
|
+
send(res, STATUS[err.code] || 409, { error: { code: err.code, message: err.message, data: err.data || {} } });
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function tokenMatches(header, token) {
|
|
369
|
+
const expected = Buffer.from(`Bearer ${token}`);
|
|
370
|
+
const given = Buffer.from(typeof header === "string" ? header : "");
|
|
371
|
+
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function readBody(req) {
|
|
375
|
+
return new Promise((resolve, reject) => {
|
|
376
|
+
const chunks = [];
|
|
377
|
+
let size = 0;
|
|
378
|
+
const collect = (chunk) => {
|
|
379
|
+
size += chunk.length;
|
|
380
|
+
if (size > MAX_BODY_BYTES) {
|
|
381
|
+
// Discard the rest unread, so the caller gets this error instead of a reset connection.
|
|
382
|
+
req.off("data", collect);
|
|
383
|
+
req.resume();
|
|
384
|
+
reject(bad(`The request body is over ${MAX_BODY_BYTES} bytes.`));
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
chunks.push(chunk);
|
|
388
|
+
};
|
|
389
|
+
req.on("data", collect);
|
|
390
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
391
|
+
req.on("error", reject);
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Write the file atomically at mode 0600, in a folder only the user can open. */
|
|
396
|
+
function writeDiscovery(file, discovery) {
|
|
397
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
398
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
399
|
+
fs.writeFileSync(tmp, JSON.stringify(discovery), { mode: 0o600 });
|
|
400
|
+
fs.chmodSync(tmp, 0o600);
|
|
401
|
+
fs.renameSync(tmp, file);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Remove the file, unless another app run has written its own since. */
|
|
405
|
+
function removeDiscovery(file, token) {
|
|
406
|
+
let current;
|
|
407
|
+
try {
|
|
408
|
+
current = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
409
|
+
} catch (err) {
|
|
410
|
+
if (err.code !== "ENOENT") console.error(`[browser-pane] Could not read ${file} to remove it: ${err.message}`);
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
if (current.token === token) fs.rmSync(file, { force: true });
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Start the bridge and announce it.
|
|
418
|
+
*
|
|
419
|
+
* @param {{
|
|
420
|
+
* discoveryFile: string,
|
|
421
|
+
* handlers: ReturnType<typeof createHandlers>,
|
|
422
|
+
* logger?: { log: Function, error: Function },
|
|
423
|
+
* }} opts
|
|
424
|
+
* @returns {Promise<{ port: number, discovery: BridgeDiscovery, close: () => Promise<void> }>}
|
|
425
|
+
*/
|
|
426
|
+
async function startBridge({ discoveryFile, handlers, logger = console }) {
|
|
427
|
+
const token = crypto.randomBytes(32).toString("hex");
|
|
428
|
+
let port = 0;
|
|
429
|
+
|
|
430
|
+
const server = http.createServer(async (req, res) => {
|
|
431
|
+
try {
|
|
432
|
+
// A browser always sends Origin on a cross-site POST: no page, pane tabs included, gets in.
|
|
433
|
+
if (req.headers.origin !== undefined) throw new BridgeError("forbidden", "Requests from web pages are refused.");
|
|
434
|
+
// A name rebound to 127.0.0.1 still carries its own Host.
|
|
435
|
+
const hostHeader = String(req.headers.host || "").toLowerCase();
|
|
436
|
+
if (hostHeader !== `127.0.0.1:${port}` && hostHeader !== `localhost:${port}`) {
|
|
437
|
+
throw new BridgeError("forbidden", `Host ${JSON.stringify(req.headers.host || "")} is not this bridge.`);
|
|
438
|
+
}
|
|
439
|
+
if (!tokenMatches(req.headers.authorization, token)) throw new BridgeError("unauthorized", "Missing or wrong bridge token.");
|
|
440
|
+
const match = /^\/v1\/([A-Za-z]+)$/.exec(req.url || "");
|
|
441
|
+
if (req.method !== "POST" || !match) throw new BridgeError("unknown_op", "Use POST /v1/<op>.");
|
|
442
|
+
let body;
|
|
443
|
+
try {
|
|
444
|
+
body = JSON.parse(await readBody(req));
|
|
445
|
+
} catch (err) {
|
|
446
|
+
throw err instanceof BridgeError ? err : bad(`The request body is not JSON: ${err.message}`);
|
|
447
|
+
}
|
|
448
|
+
const { op, req: parsed } = parseRequest(match[1], body);
|
|
449
|
+
send(res, 200, await handlers[op](parsed));
|
|
450
|
+
} catch (err) {
|
|
451
|
+
if (err instanceof BridgeError) {
|
|
452
|
+
sendError(res, err);
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
logger.error(`[browser-pane] Bridge ${req.url} failed: ${(err && err.stack) || err}`);
|
|
456
|
+
sendError(res, new BridgeError("internal", `The browser pane failed: ${err && err.message}`));
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
await new Promise((resolve, reject) => {
|
|
461
|
+
server.once("error", reject);
|
|
462
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
463
|
+
});
|
|
464
|
+
port = server.address().port;
|
|
465
|
+
/** @type {BridgeDiscovery} */
|
|
466
|
+
const discovery = { port, token, pid: process.pid, protocol: BRIDGE_PROTOCOL };
|
|
467
|
+
// Written only once listening, so a reader never finds a port nobody answers.
|
|
468
|
+
writeDiscovery(discoveryFile, discovery);
|
|
469
|
+
logger.log(`[browser-pane] Bridge listening on 127.0.0.1:${port}; discovery file ${discoveryFile}`);
|
|
470
|
+
|
|
471
|
+
let closed = false;
|
|
472
|
+
return {
|
|
473
|
+
port,
|
|
474
|
+
discovery,
|
|
475
|
+
close: async () => {
|
|
476
|
+
if (closed) return;
|
|
477
|
+
closed = true;
|
|
478
|
+
removeDiscovery(discoveryFile, token);
|
|
479
|
+
const stopped = new Promise((resolve) => server.close(() => resolve()));
|
|
480
|
+
server.closeAllConnections();
|
|
481
|
+
await stopped;
|
|
482
|
+
},
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
module.exports = {
|
|
487
|
+
BRIDGE_PROTOCOL,
|
|
488
|
+
DISCOVERY_ENV,
|
|
489
|
+
LIMITS: { MAX_BODY_BYTES, MAX_SCRIPT_CHARS, MAX_TYPED_CHARS, MAX_EXPRESSION_CHARS, MAX_ARGV },
|
|
490
|
+
PARSERS,
|
|
491
|
+
createHandlers,
|
|
492
|
+
devServerOrigins,
|
|
493
|
+
discoveryPath,
|
|
494
|
+
parseRequest,
|
|
495
|
+
startBridge,
|
|
496
|
+
};
|