@howaboua/pi-browser 0.0.16 → 0.0.17
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/CHANGELOG.md +4 -0
- package/README.md +3 -1
- package/dist/remote-worker.js +276 -24
- package/dist/src/browser/default-browser.d.ts +7 -0
- package/dist/src/browser/default-browser.js +181 -0
- package/dist/src/browser/launcher.js +137 -14
- package/package.json +9 -9
- package/src/browser/default-browser.ts +217 -0
- package/src/browser/launcher.ts +169 -13
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# @howaboua/pi-browser
|
|
2
2
|
|
|
3
|
+
## 0.0.17
|
|
4
|
+
|
|
5
|
+
- On Linux, `start` uses the graphical desktop's configured default browser instead of falling back to Chromium. `CDP_BROWSER` still overrides browser selection.
|
|
6
|
+
|
|
3
7
|
## 0.0.16
|
|
4
8
|
|
|
5
9
|
- Shortened browser timeout and tab-creation errors. They say what may have happened and what to check before retrying.
|
package/README.md
CHANGED
|
@@ -50,7 +50,9 @@ The browser tool is unavailable to the agent, while voice startup and `/browser`
|
|
|
50
50
|
|
|
51
51
|
The tool discovers CDP through `CDP_PORT`, port 9222, or `DevToolsActivePort`. Set `CDP_PORT_FILE` for a non-standard port file.
|
|
52
52
|
|
|
53
|
-
The `start` action
|
|
53
|
+
The `start` action reuses a browser already listening on the configured CDP port. On Linux with a systemd user session, it uses `xdg-settings` to find the graphical desktop's default browser on the selected host. Over SSH, the host's systemd user session must know the graphical desktop environment. The action uses the browser's desktop launch command without creating a separate profile. A browser that does not support CDP may open, but the action reports success only when CDP responds.
|
|
54
|
+
|
|
55
|
+
Set `CDP_BROWSER` to explicitly choose a compatible executable and `CDP_PROFILE_DIRECTORY` to select a profile. If automatic startup is unsupported or the browser does not expose CDP, start the browser normally and enable remote debugging.
|
|
54
56
|
|
|
55
57
|
## Boundaries
|
|
56
58
|
|
package/dist/remote-worker.js
CHANGED
|
@@ -12,7 +12,7 @@ import { spawn as spawn3 } from "node:child_process";
|
|
|
12
12
|
import { chmod, lstat as lstat2, mkdir as mkdir4, rm as rm4 } from "node:fs/promises";
|
|
13
13
|
import { createConnection, createServer } from "node:net";
|
|
14
14
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
15
|
-
import { dirname as dirname2, join as
|
|
15
|
+
import { dirname as dirname2, join as join7 } from "node:path";
|
|
16
16
|
import { StringDecoder as StringDecoder3 } from "node:string_decoder";
|
|
17
17
|
|
|
18
18
|
// src/cdp/actions/key.ts
|
|
@@ -635,7 +635,7 @@ function loadBrowserRoutes(path, currentHostname = hostname()) {
|
|
|
635
635
|
|
|
636
636
|
// src/browser/runtime.ts
|
|
637
637
|
import { randomUUID } from "node:crypto";
|
|
638
|
-
import { join as
|
|
638
|
+
import { join as join6 } from "node:path";
|
|
639
639
|
|
|
640
640
|
// src/cdp/serial.ts
|
|
641
641
|
function waitForTurn(promise, signal) {
|
|
@@ -3036,18 +3036,172 @@ function boundSnapshot(page) {
|
|
|
3036
3036
|
|
|
3037
3037
|
// src/browser/launcher.ts
|
|
3038
3038
|
import { spawn } from "node:child_process";
|
|
3039
|
+
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
3040
|
+
|
|
3041
|
+
// src/browser/default-browser.ts
|
|
3042
|
+
import { constants } from "node:fs";
|
|
3043
|
+
import { access, readdir as readdir3, readFile as readFile2, stat as stat2 } from "node:fs/promises";
|
|
3044
|
+
import { homedir as homedir3 } from "node:os";
|
|
3045
|
+
import { isAbsolute, join as join4 } from "node:path";
|
|
3046
|
+
var RECOVERY = "Set CDP_BROWSER to a compatible executable, or start a browser with CDP enabled yourself.";
|
|
3047
|
+
async function missingIsUndefined(operation) {
|
|
3048
|
+
try {
|
|
3049
|
+
return await operation;
|
|
3050
|
+
} catch (error) {
|
|
3051
|
+
if (error && typeof error === "object" && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
|
|
3052
|
+
return;
|
|
3053
|
+
}
|
|
3054
|
+
throw error;
|
|
3055
|
+
}
|
|
3056
|
+
}
|
|
3057
|
+
async function desktopFiles(directory, id) {
|
|
3058
|
+
const entries = await missingIsUndefined(readdir3(directory, { withFileTypes: true }));
|
|
3059
|
+
const paths = [];
|
|
3060
|
+
for (const entry of entries ?? []) {
|
|
3061
|
+
const path = join4(directory, entry.name);
|
|
3062
|
+
if (entry.name === id && !entry.isDirectory()) {
|
|
3063
|
+
paths.push(path);
|
|
3064
|
+
} else if (entry.isDirectory() && id.startsWith(entry.name + "-")) {
|
|
3065
|
+
paths.push(...await desktopFiles(path, id.slice(entry.name.length + 1)));
|
|
3066
|
+
}
|
|
3067
|
+
}
|
|
3068
|
+
return paths;
|
|
3069
|
+
}
|
|
3070
|
+
async function findDesktopFile(id, env) {
|
|
3071
|
+
const userData = env["XDG_DATA_HOME"];
|
|
3072
|
+
const home = env["HOME"];
|
|
3073
|
+
const systemData = (env["XDG_DATA_DIRS"] || "/usr/local/share:/usr/share").split(":").filter(isAbsolute);
|
|
3074
|
+
const roots = [
|
|
3075
|
+
userData && isAbsolute(userData) ? userData : join4(home && isAbsolute(home) ? home : homedir3(), ".local/share"),
|
|
3076
|
+
...systemData
|
|
3077
|
+
];
|
|
3078
|
+
for (const root of roots) {
|
|
3079
|
+
const [path, ambiguous] = await desktopFiles(join4(root, "applications"), id);
|
|
3080
|
+
if (ambiguous)
|
|
3081
|
+
throw new Error("the desktop ID is ambiguous");
|
|
3082
|
+
if (path)
|
|
3083
|
+
return path;
|
|
3084
|
+
}
|
|
3085
|
+
throw new Error("the desktop entry was not found");
|
|
3086
|
+
}
|
|
3087
|
+
function desktopEntry(source) {
|
|
3088
|
+
const entry = new Map;
|
|
3089
|
+
let inDesktopEntry = false;
|
|
3090
|
+
for (const line of source.split(/\r?\n/)) {
|
|
3091
|
+
const trimmed = line.trim();
|
|
3092
|
+
if (trimmed.startsWith("[")) {
|
|
3093
|
+
if (inDesktopEntry)
|
|
3094
|
+
break;
|
|
3095
|
+
inDesktopEntry = trimmed === "[Desktop Entry]";
|
|
3096
|
+
} else if (inDesktopEntry && trimmed && !trimmed.startsWith("#")) {
|
|
3097
|
+
const equals = trimmed.indexOf("=");
|
|
3098
|
+
if (equals < 1)
|
|
3099
|
+
throw new Error("invalid desktop entry");
|
|
3100
|
+
const key = trimmed.slice(0, equals).trimEnd();
|
|
3101
|
+
if (entry.has(key))
|
|
3102
|
+
throw new Error("duplicate desktop entry key");
|
|
3103
|
+
entry.set(key, trimmed.slice(equals + 1).trimStart());
|
|
3104
|
+
}
|
|
3105
|
+
}
|
|
3106
|
+
return entry;
|
|
3107
|
+
}
|
|
3108
|
+
function desktopString(value) {
|
|
3109
|
+
const escapes = {
|
|
3110
|
+
s: " ",
|
|
3111
|
+
n: `
|
|
3112
|
+
`,
|
|
3113
|
+
t: "\t",
|
|
3114
|
+
r: "\r",
|
|
3115
|
+
"\\": "\\"
|
|
3116
|
+
};
|
|
3117
|
+
return value.replace(/\\(.|$)/g, (_match, char) => {
|
|
3118
|
+
const replacement = escapes[char];
|
|
3119
|
+
if (replacement === undefined)
|
|
3120
|
+
throw new Error("invalid desktop entry escape");
|
|
3121
|
+
return replacement;
|
|
3122
|
+
});
|
|
3123
|
+
}
|
|
3124
|
+
function execArguments(line) {
|
|
3125
|
+
const word = /(?:"(?:[^"\\]|\\["`$\\])*"|[^ \t\n\r"'\\><~|&;$*?#()`]+)(?=[ \t]|$)/y;
|
|
3126
|
+
const args = [];
|
|
3127
|
+
let hasInputField = false;
|
|
3128
|
+
for (let remaining = desktopString(line).trim();remaining; ) {
|
|
3129
|
+
const match = word.exec(remaining)?.[0];
|
|
3130
|
+
if (match === undefined)
|
|
3131
|
+
throw new Error("unsupported desktop Exec quoting");
|
|
3132
|
+
remaining = remaining.slice(match.length).trimStart();
|
|
3133
|
+
word.lastIndex = 0;
|
|
3134
|
+
if (args.length !== 0 && /^%[fFuU]$/.test(match)) {
|
|
3135
|
+
if (hasInputField)
|
|
3136
|
+
throw new Error("multiple desktop Exec input fields");
|
|
3137
|
+
hasInputField = true;
|
|
3138
|
+
continue;
|
|
3139
|
+
}
|
|
3140
|
+
const unquoted = match.startsWith('"') ? match.slice(1, -1).replace(/\\(.)/gs, "$1") : match;
|
|
3141
|
+
args.push(unquoted.replace(/%%|%/g, (percent) => {
|
|
3142
|
+
if (percent === "%%")
|
|
3143
|
+
return "%";
|
|
3144
|
+
throw new Error("unsupported desktop Exec field code");
|
|
3145
|
+
}));
|
|
3146
|
+
}
|
|
3147
|
+
return args;
|
|
3148
|
+
}
|
|
3149
|
+
async function executablePath(executable, env) {
|
|
3150
|
+
const candidates = isAbsolute(executable) ? [executable] : executable.includes("/") ? [] : (env["PATH"] ?? "/usr/bin:/bin").split(":").filter(isAbsolute).map((directory) => join4(directory, executable));
|
|
3151
|
+
for (const path of candidates) {
|
|
3152
|
+
try {
|
|
3153
|
+
await access(path, constants.X_OK);
|
|
3154
|
+
if ((await stat2(path)).isFile())
|
|
3155
|
+
return path;
|
|
3156
|
+
} catch {}
|
|
3157
|
+
}
|
|
3158
|
+
return;
|
|
3159
|
+
}
|
|
3160
|
+
async function resolveDefaultBrowser(id, env) {
|
|
3161
|
+
if (!/^[A-Za-z0-9_.-]+\.desktop$/.test(id)) {
|
|
3162
|
+
throw new Error("Could not determine the configured default browser. " + RECOVERY);
|
|
3163
|
+
}
|
|
3164
|
+
try {
|
|
3165
|
+
const path = await findDesktopFile(id, env);
|
|
3166
|
+
if (!(await stat2(path)).isFile())
|
|
3167
|
+
throw new Error("invalid desktop entry file");
|
|
3168
|
+
const entry = desktopEntry(await readFile2(path, "utf8"));
|
|
3169
|
+
if (entry.get("Type") !== "Application" || entry.get("Hidden") === "true" || entry.get("Terminal") === "true" || entry.get("DBusActivatable") === "true") {
|
|
3170
|
+
throw new Error("the desktop entry does not use direct application startup");
|
|
3171
|
+
}
|
|
3172
|
+
const [command, ...args] = execArguments(entry.get("Exec") ?? "");
|
|
3173
|
+
if (!command || command.includes("=")) {
|
|
3174
|
+
throw new Error("the desktop entry has no valid executable");
|
|
3175
|
+
}
|
|
3176
|
+
const executable = await executablePath(command, env);
|
|
3177
|
+
const tryExec = desktopString(entry.get("TryExec") ?? "");
|
|
3178
|
+
if (!executable || tryExec && !await executablePath(tryExec, env)) {
|
|
3179
|
+
throw new Error("the desktop executable is unavailable");
|
|
3180
|
+
}
|
|
3181
|
+
const workingDirectory = desktopString(entry.get("Path") ?? "") || undefined;
|
|
3182
|
+
if (workingDirectory && !isAbsolute(workingDirectory)) {
|
|
3183
|
+
throw new Error("the desktop working directory is not absolute");
|
|
3184
|
+
}
|
|
3185
|
+
return { executable, args, workingDirectory };
|
|
3186
|
+
} catch (error) {
|
|
3187
|
+
throw new Error('Cannot start the default browser "' + id + '": ' + (error instanceof Error ? error.message : String(error)) + ". " + RECOVERY, { cause: error });
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
|
|
3191
|
+
// src/browser/launcher.ts
|
|
3039
3192
|
var BROWSER_START_TIMEOUT_MS = 1e4;
|
|
3040
3193
|
var BROWSER_UNIT = "chrome-cdp-browser.service";
|
|
3041
3194
|
var PROCESS_OUTPUT_LIMIT = 1 * 1024 * 1024;
|
|
3042
3195
|
function abortReason(signal) {
|
|
3043
3196
|
return signal.reason instanceof Error ? signal.reason : new Error("Browser launch aborted");
|
|
3044
3197
|
}
|
|
3045
|
-
function runProcess(command, args, signal) {
|
|
3198
|
+
function runProcess(command, args, signal, env) {
|
|
3046
3199
|
if (signal?.aborted)
|
|
3047
3200
|
return Promise.reject(abortReason(signal));
|
|
3048
3201
|
return new Promise((resolveValue, reject) => {
|
|
3049
3202
|
const child = spawn(command, args, {
|
|
3050
|
-
stdio: ["ignore", "pipe", "pipe"]
|
|
3203
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
3204
|
+
env
|
|
3051
3205
|
});
|
|
3052
3206
|
let stdout = "";
|
|
3053
3207
|
let stderr = "";
|
|
@@ -3125,7 +3279,114 @@ async function waitForDebugEndpoint(signal, timeout = BROWSER_START_TIMEOUT_MS)
|
|
|
3125
3279
|
}
|
|
3126
3280
|
await sleep(100, signal);
|
|
3127
3281
|
}
|
|
3128
|
-
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}
|
|
3282
|
+
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}. The browser may not support CDP startup flags or may have refused remote debugging for this profile. Enable remote debugging in the existing browser or set CDP_BROWSER to a compatible executable.`);
|
|
3283
|
+
}
|
|
3284
|
+
function hasGraphicalDesktop(env) {
|
|
3285
|
+
return Boolean(env["WAYLAND_DISPLAY"]?.trim() || env["DISPLAY"]?.trim());
|
|
3286
|
+
}
|
|
3287
|
+
async function graphicalEnvironment(signal) {
|
|
3288
|
+
if (!process.env["SSH_CONNECTION"] && hasGraphicalDesktop(process.env)) {
|
|
3289
|
+
return { ...process.env };
|
|
3290
|
+
}
|
|
3291
|
+
const result = await runProcess("busctl", [
|
|
3292
|
+
"--user",
|
|
3293
|
+
"--json=short",
|
|
3294
|
+
"get-property",
|
|
3295
|
+
"org.freedesktop.systemd1",
|
|
3296
|
+
"/org/freedesktop/systemd1",
|
|
3297
|
+
"org.freedesktop.systemd1.Manager",
|
|
3298
|
+
"Environment"
|
|
3299
|
+
], signal);
|
|
3300
|
+
if (result.code !== 0)
|
|
3301
|
+
throw new Error("systemd user environment unavailable");
|
|
3302
|
+
const reply = asRecord(JSON.parse(result.stdout), "systemd user environment");
|
|
3303
|
+
if (reply["type"] !== "as" || !Array.isArray(reply["data"])) {
|
|
3304
|
+
throw new Error("Invalid systemd user environment");
|
|
3305
|
+
}
|
|
3306
|
+
const entries = [];
|
|
3307
|
+
for (const assignment of reply["data"]) {
|
|
3308
|
+
if (typeof assignment !== "string")
|
|
3309
|
+
throw new Error("Invalid systemd environment variable");
|
|
3310
|
+
const equals = assignment.indexOf("=");
|
|
3311
|
+
if (equals <= 0)
|
|
3312
|
+
throw new Error("Invalid systemd environment variable");
|
|
3313
|
+
entries.push([assignment.slice(0, equals), assignment.slice(equals + 1)]);
|
|
3314
|
+
}
|
|
3315
|
+
const env = Object.fromEntries(entries);
|
|
3316
|
+
if (!hasGraphicalDesktop(env))
|
|
3317
|
+
throw new Error("systemd has no graphical desktop environment");
|
|
3318
|
+
return env;
|
|
3319
|
+
}
|
|
3320
|
+
async function configuredDefaultBrowser(signal) {
|
|
3321
|
+
const timeout = AbortSignal.timeout(5000);
|
|
3322
|
+
const lookupSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
3323
|
+
let env;
|
|
3324
|
+
try {
|
|
3325
|
+
env = await graphicalEnvironment(lookupSignal);
|
|
3326
|
+
} catch (error) {
|
|
3327
|
+
signal?.throwIfAborted();
|
|
3328
|
+
throw new Error("Could not determine the graphical desktop environment. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
|
|
3329
|
+
}
|
|
3330
|
+
delete env["BROWSER"];
|
|
3331
|
+
let id;
|
|
3332
|
+
try {
|
|
3333
|
+
const result = await runProcess("xdg-settings", ["get", "default-web-browser"], lookupSignal, env);
|
|
3334
|
+
if (result.code !== 0)
|
|
3335
|
+
throw new Error(result.stderr || `exit ${result.code}`);
|
|
3336
|
+
id = result.stdout;
|
|
3337
|
+
} catch (error) {
|
|
3338
|
+
signal?.throwIfAborted();
|
|
3339
|
+
throw new Error("Could not query the configured default browser with xdg-settings. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
|
|
3340
|
+
}
|
|
3341
|
+
return resolveDefaultBrowser(id, env);
|
|
3342
|
+
}
|
|
3343
|
+
async function browserLaunchCommand(host, port, signal) {
|
|
3344
|
+
const switches = new Map([
|
|
3345
|
+
["--remote-debugging-address", host],
|
|
3346
|
+
["--remote-debugging-port", port]
|
|
3347
|
+
]);
|
|
3348
|
+
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
3349
|
+
if (profile)
|
|
3350
|
+
switches.set("--profile-directory", profile);
|
|
3351
|
+
const override = process.env["CDP_BROWSER"];
|
|
3352
|
+
if (override === "") {
|
|
3353
|
+
throw new Error("CDP_BROWSER must name a compatible executable.");
|
|
3354
|
+
}
|
|
3355
|
+
const desktop = override ? {
|
|
3356
|
+
executable: override,
|
|
3357
|
+
args: ["about:blank"],
|
|
3358
|
+
workingDirectory: undefined
|
|
3359
|
+
} : await configuredDefaultBrowser(signal);
|
|
3360
|
+
const fromDesktop = new Set;
|
|
3361
|
+
for (const arg of desktop.args) {
|
|
3362
|
+
if (arg === "--") {
|
|
3363
|
+
throw new Error("The default browser's desktop command has an option separator, so CDP arguments cannot be appended safely. Set CDP_BROWSER or start the browser yourself with CDP enabled.");
|
|
3364
|
+
}
|
|
3365
|
+
const [name = ""] = arg.split("=", 1);
|
|
3366
|
+
const key = name.startsWith("-") && !name.startsWith("--") ? `-${name}` : name;
|
|
3367
|
+
const value = arg.startsWith(name + "=") ? arg.slice(name.length + 1) : "";
|
|
3368
|
+
const configured = switches.get(key);
|
|
3369
|
+
if (key === "--remote-debugging-pipe" || configured !== undefined && configured !== value) {
|
|
3370
|
+
throw new Error(`The default browser's desktop arguments conflict with ${key}. Adjust the CDP configuration or start the browser yourself.`);
|
|
3371
|
+
}
|
|
3372
|
+
if (key === "--user-data-dir" && !isAbsolute2(value) && !desktop.workingDirectory) {
|
|
3373
|
+
throw new Error("The default browser uses a relative --user-data-dir without a desktop working directory. Start the browser yourself with CDP enabled.");
|
|
3374
|
+
}
|
|
3375
|
+
fromDesktop.add(key);
|
|
3376
|
+
}
|
|
3377
|
+
const args = [
|
|
3378
|
+
...override ? [] : desktop.args,
|
|
3379
|
+
...[...switches].filter(([key]) => !fromDesktop.has(key)).map(([key, value]) => `${key}=${value}`),
|
|
3380
|
+
...override ? desktop.args : []
|
|
3381
|
+
];
|
|
3382
|
+
const literalExecutable = desktop.executable.includes("$");
|
|
3383
|
+
return [
|
|
3384
|
+
...desktop.workingDirectory ? [`--property=WorkingDirectory=${desktop.workingDirectory}`] : [],
|
|
3385
|
+
...literalExecutable ? ["--expand-environment=no"] : [],
|
|
3386
|
+
"--",
|
|
3387
|
+
desktop.executable,
|
|
3388
|
+
...literalExecutable ? args : args.map((arg) => arg.replaceAll("$", () => "$$"))
|
|
3389
|
+
];
|
|
3129
3390
|
}
|
|
3130
3391
|
async function unitExists(systemctl, signal) {
|
|
3131
3392
|
const result = await runProcess(systemctl, ["--user", "show", BROWSER_UNIT, "--property=LoadState", "--value"], signal);
|
|
@@ -3156,7 +3417,7 @@ async function startBrowser(signal) {
|
|
|
3156
3417
|
}
|
|
3157
3418
|
const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
|
|
3158
3419
|
const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
|
|
3159
|
-
|
|
3420
|
+
let launchCommand;
|
|
3160
3421
|
let lastLaunchError = "";
|
|
3161
3422
|
for (let attempt = 0;attempt < 3; attempt++) {
|
|
3162
3423
|
const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
|
|
@@ -3166,24 +3427,15 @@ async function startBrowser(signal) {
|
|
|
3166
3427
|
if (state === "timeout") {
|
|
3167
3428
|
throw new Error(`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`);
|
|
3168
3429
|
}
|
|
3430
|
+
launchCommand ??= await browserLaunchCommand(host, port, signal);
|
|
3169
3431
|
await runProcess(systemctl, ["--user", "reset-failed", BROWSER_UNIT], signal);
|
|
3170
|
-
const browserArgs = [
|
|
3171
|
-
`--remote-debugging-address=${host}`,
|
|
3172
|
-
`--remote-debugging-port=${port}`
|
|
3173
|
-
];
|
|
3174
|
-
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
3175
|
-
if (profile) {
|
|
3176
|
-
browserArgs.push(`--profile-directory=${profile}`);
|
|
3177
|
-
}
|
|
3178
|
-
browserArgs.push("about:blank");
|
|
3179
3432
|
const launched = await runProcess(systemdRun, [
|
|
3180
3433
|
"--user",
|
|
3181
3434
|
"--unit=chrome-cdp-browser",
|
|
3182
3435
|
"--collect",
|
|
3183
3436
|
"--property=Type=exec",
|
|
3184
3437
|
"--property=Restart=no",
|
|
3185
|
-
|
|
3186
|
-
...browserArgs
|
|
3438
|
+
...launchCommand
|
|
3187
3439
|
], signal);
|
|
3188
3440
|
if (launched.code === 0) {
|
|
3189
3441
|
await waitForDebugEndpoint(signal);
|
|
@@ -3303,10 +3555,10 @@ class BrowserOperationExecutor {
|
|
|
3303
3555
|
|
|
3304
3556
|
// src/browser/remote.ts
|
|
3305
3557
|
import { mkdir as mkdir3, rm as rm3 } from "node:fs/promises";
|
|
3306
|
-
import { basename as basename2, join as
|
|
3558
|
+
import { basename as basename2, join as join5 } from "node:path";
|
|
3307
3559
|
|
|
3308
3560
|
// src/browser/remote-helper.ts
|
|
3309
|
-
import { readFile as
|
|
3561
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
3310
3562
|
import { fileURLToPath } from "node:url";
|
|
3311
3563
|
|
|
3312
3564
|
// src/browser/remote-process.ts
|
|
@@ -3458,7 +3710,7 @@ async function readHelperSource() {
|
|
|
3458
3710
|
let lastError;
|
|
3459
3711
|
for (const path of candidates) {
|
|
3460
3712
|
try {
|
|
3461
|
-
return await
|
|
3713
|
+
return await readFile3(path, "utf8");
|
|
3462
3714
|
} catch (error) {
|
|
3463
3715
|
lastError = error;
|
|
3464
3716
|
}
|
|
@@ -3506,7 +3758,7 @@ async function copyRemoteArtifact(host, remoteFile, signal) {
|
|
|
3506
3758
|
throw new Error(`remote browser returned an unsafe artifact path: ${remoteFile}`);
|
|
3507
3759
|
}
|
|
3508
3760
|
await mkdir3(artifactDirectory(), { recursive: true, mode: 448 });
|
|
3509
|
-
const localFile =
|
|
3761
|
+
const localFile = join5(artifactDirectory(), `${host}-${basename2(remoteFile)}`);
|
|
3510
3762
|
const copied = await runProgram("scp", ["-q", `${host}:${remoteFile}`, localFile], undefined, signal);
|
|
3511
3763
|
if (copied.code !== 0) {
|
|
3512
3764
|
throw new Error(copied.stderr || copied.stdout || "could not copy remote screenshot");
|
|
@@ -3645,7 +3897,7 @@ class BrowserRuntime {
|
|
|
3645
3897
|
let session = this.localSessions.get(ownerId);
|
|
3646
3898
|
if (session)
|
|
3647
3899
|
return session;
|
|
3648
|
-
const cdp = new BrowserCdpSession(ownerId,
|
|
3900
|
+
const cdp = new BrowserCdpSession(ownerId, join6(artifactDirectory(), "tabs"));
|
|
3649
3901
|
session = {
|
|
3650
3902
|
activeCalls: 0,
|
|
3651
3903
|
cdp,
|
|
@@ -3680,8 +3932,8 @@ var IS_WINDOWS2 = process.platform === "win32";
|
|
|
3680
3932
|
function workerSocketPath(workerId) {
|
|
3681
3933
|
if (IS_WINDOWS2)
|
|
3682
3934
|
return `\\\\.\\pipe\\pi-browser-worker-${workerId}`;
|
|
3683
|
-
const directory = process.env["XDG_RUNTIME_DIR"] ?
|
|
3684
|
-
return
|
|
3935
|
+
const directory = process.env["XDG_RUNTIME_DIR"] ? join7(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join7(tmpdir2(), `browser-tool-${process.getuid?.() ?? "user"}`);
|
|
3936
|
+
return join7(directory, `worker-${workerId}.sock`);
|
|
3685
3937
|
}
|
|
3686
3938
|
async function ensureWorkerSocketDirectory(workerId) {
|
|
3687
3939
|
if (IS_WINDOWS2)
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access, readdir, readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { isAbsolute, join } from "node:path";
|
|
5
|
+
const RECOVERY = "Set CDP_BROWSER to a compatible executable, or start a browser with CDP enabled yourself.";
|
|
6
|
+
async function missingIsUndefined(operation) {
|
|
7
|
+
try {
|
|
8
|
+
return await operation;
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
if (error &&
|
|
12
|
+
typeof error === "object" &&
|
|
13
|
+
"code" in error &&
|
|
14
|
+
(error.code === "ENOENT" || error.code === "ENOTDIR")) {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function desktopFiles(directory, id) {
|
|
21
|
+
const entries = await missingIsUndefined(readdir(directory, { withFileTypes: true }));
|
|
22
|
+
const paths = [];
|
|
23
|
+
for (const entry of entries ?? []) {
|
|
24
|
+
const path = join(directory, entry.name);
|
|
25
|
+
if (entry.name === id && !entry.isDirectory()) {
|
|
26
|
+
paths.push(path);
|
|
27
|
+
}
|
|
28
|
+
else if (entry.isDirectory() && id.startsWith(entry.name + "-")) {
|
|
29
|
+
// Nested entries derive their IDs by replacing '/' with '-'.
|
|
30
|
+
paths.push(...(await desktopFiles(path, id.slice(entry.name.length + 1))));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return paths;
|
|
34
|
+
}
|
|
35
|
+
async function findDesktopFile(id, env) {
|
|
36
|
+
const userData = env["XDG_DATA_HOME"];
|
|
37
|
+
const home = env["HOME"];
|
|
38
|
+
const systemData = (env["XDG_DATA_DIRS"] || "/usr/local/share:/usr/share")
|
|
39
|
+
.split(":")
|
|
40
|
+
.filter(isAbsolute);
|
|
41
|
+
const roots = [
|
|
42
|
+
userData && isAbsolute(userData)
|
|
43
|
+
? userData
|
|
44
|
+
: join(home && isAbsolute(home) ? home : homedir(), ".local/share"),
|
|
45
|
+
...systemData,
|
|
46
|
+
];
|
|
47
|
+
for (const root of roots) {
|
|
48
|
+
const [path, ambiguous] = await desktopFiles(join(root, "applications"), id);
|
|
49
|
+
if (ambiguous)
|
|
50
|
+
throw new Error("the desktop ID is ambiguous");
|
|
51
|
+
if (path)
|
|
52
|
+
return path;
|
|
53
|
+
}
|
|
54
|
+
throw new Error("the desktop entry was not found");
|
|
55
|
+
}
|
|
56
|
+
function desktopEntry(source) {
|
|
57
|
+
const entry = new Map();
|
|
58
|
+
let inDesktopEntry = false;
|
|
59
|
+
for (const line of source.split(/\r?\n/)) {
|
|
60
|
+
const trimmed = line.trim();
|
|
61
|
+
if (trimmed.startsWith("[")) {
|
|
62
|
+
if (inDesktopEntry)
|
|
63
|
+
break;
|
|
64
|
+
inDesktopEntry = trimmed === "[Desktop Entry]";
|
|
65
|
+
}
|
|
66
|
+
else if (inDesktopEntry && trimmed && !trimmed.startsWith("#")) {
|
|
67
|
+
const equals = trimmed.indexOf("=");
|
|
68
|
+
if (equals < 1)
|
|
69
|
+
throw new Error("invalid desktop entry");
|
|
70
|
+
const key = trimmed.slice(0, equals).trimEnd();
|
|
71
|
+
if (entry.has(key))
|
|
72
|
+
throw new Error("duplicate desktop entry key");
|
|
73
|
+
entry.set(key, trimmed.slice(equals + 1).trimStart());
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return entry;
|
|
77
|
+
}
|
|
78
|
+
function desktopString(value) {
|
|
79
|
+
const escapes = {
|
|
80
|
+
s: " ",
|
|
81
|
+
n: "\n",
|
|
82
|
+
t: "\t",
|
|
83
|
+
r: "\r",
|
|
84
|
+
"\\": "\\",
|
|
85
|
+
};
|
|
86
|
+
return value.replace(/\\(.|$)/g, (_match, char) => {
|
|
87
|
+
const replacement = escapes[char];
|
|
88
|
+
if (replacement === undefined)
|
|
89
|
+
throw new Error("invalid desktop entry escape");
|
|
90
|
+
return replacement;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
function execArguments(line) {
|
|
94
|
+
// Desktop Entry quoting is not shell quoting. Accept literal words and
|
|
95
|
+
// whole double-quoted arguments only; leave nonliteral launchers unsupported.
|
|
96
|
+
const word = /(?:"(?:[^"\\]|\\["`$\\])*"|[^ \t\n\r"'\\><~|&;$*?#()`]+)(?=[ \t]|$)/y;
|
|
97
|
+
const args = [];
|
|
98
|
+
let hasInputField = false;
|
|
99
|
+
for (let remaining = desktopString(line).trim(); remaining;) {
|
|
100
|
+
const match = word.exec(remaining)?.[0];
|
|
101
|
+
if (match === undefined)
|
|
102
|
+
throw new Error("unsupported desktop Exec quoting");
|
|
103
|
+
remaining = remaining.slice(match.length).trimStart();
|
|
104
|
+
word.lastIndex = 0;
|
|
105
|
+
if (args.length !== 0 && /^%[fFuU]$/.test(match)) {
|
|
106
|
+
if (hasInputField)
|
|
107
|
+
throw new Error("multiple desktop Exec input fields");
|
|
108
|
+
hasInputField = true;
|
|
109
|
+
continue; // No URL or file was requested.
|
|
110
|
+
}
|
|
111
|
+
const unquoted = match.startsWith('"')
|
|
112
|
+
? match.slice(1, -1).replace(/\\(.)/gs, "$1")
|
|
113
|
+
: match;
|
|
114
|
+
args.push(unquoted.replace(/%%|%/g, (percent) => {
|
|
115
|
+
if (percent === "%%")
|
|
116
|
+
return "%";
|
|
117
|
+
throw new Error("unsupported desktop Exec field code");
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
return args;
|
|
121
|
+
}
|
|
122
|
+
async function executablePath(executable, env) {
|
|
123
|
+
const candidates = isAbsolute(executable)
|
|
124
|
+
? [executable]
|
|
125
|
+
: executable.includes("/")
|
|
126
|
+
? []
|
|
127
|
+
: (env["PATH"] ?? "/usr/bin:/bin")
|
|
128
|
+
.split(":")
|
|
129
|
+
.filter(isAbsolute)
|
|
130
|
+
.map((directory) => join(directory, executable));
|
|
131
|
+
for (const path of candidates) {
|
|
132
|
+
try {
|
|
133
|
+
await access(path, constants.X_OK);
|
|
134
|
+
if ((await stat(path)).isFile())
|
|
135
|
+
return path;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// Keep looking on PATH when a candidate isn't executable.
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
export async function resolveDefaultBrowser(id, env) {
|
|
144
|
+
if (!/^[A-Za-z0-9_.-]+\.desktop$/.test(id)) {
|
|
145
|
+
throw new Error("Could not determine the configured default browser. " + RECOVERY);
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
const path = await findDesktopFile(id, env);
|
|
149
|
+
if (!(await stat(path)).isFile())
|
|
150
|
+
throw new Error("invalid desktop entry file");
|
|
151
|
+
const entry = desktopEntry(await readFile(path, "utf8"));
|
|
152
|
+
if (entry.get("Type") !== "Application" ||
|
|
153
|
+
entry.get("Hidden") === "true" ||
|
|
154
|
+
entry.get("Terminal") === "true" ||
|
|
155
|
+
entry.get("DBusActivatable") === "true") {
|
|
156
|
+
throw new Error("the desktop entry does not use direct application startup");
|
|
157
|
+
}
|
|
158
|
+
const [command, ...args] = execArguments(entry.get("Exec") ?? "");
|
|
159
|
+
if (!command || command.includes("=")) {
|
|
160
|
+
throw new Error("the desktop entry has no valid executable");
|
|
161
|
+
}
|
|
162
|
+
const executable = await executablePath(command, env);
|
|
163
|
+
const tryExec = desktopString(entry.get("TryExec") ?? "");
|
|
164
|
+
if (!executable || (tryExec && !(await executablePath(tryExec, env)))) {
|
|
165
|
+
throw new Error("the desktop executable is unavailable");
|
|
166
|
+
}
|
|
167
|
+
const workingDirectory = desktopString(entry.get("Path") ?? "") || undefined;
|
|
168
|
+
if (workingDirectory && !isAbsolute(workingDirectory)) {
|
|
169
|
+
throw new Error("the desktop working directory is not absolute");
|
|
170
|
+
}
|
|
171
|
+
return { executable, args, workingDirectory };
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
throw new Error('Cannot start the default browser "' +
|
|
175
|
+
id +
|
|
176
|
+
'": ' +
|
|
177
|
+
(error instanceof Error ? error.message : String(error)) +
|
|
178
|
+
". " +
|
|
179
|
+
RECOVERY, { cause: error });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
2
3
|
import { probeDebugPort, sleep } from "../cdp/discovery.js";
|
|
4
|
+
import { asRecord } from "../cdp/types.js";
|
|
5
|
+
import { resolveDefaultBrowser } from "./default-browser.js";
|
|
3
6
|
const BROWSER_START_TIMEOUT_MS = 10_000;
|
|
4
7
|
const BROWSER_UNIT = "chrome-cdp-browser.service";
|
|
5
8
|
const PROCESS_OUTPUT_LIMIT = 1 * 1_024 * 1_024;
|
|
@@ -8,12 +11,13 @@ function abortReason(signal) {
|
|
|
8
11
|
? signal.reason
|
|
9
12
|
: new Error("Browser launch aborted");
|
|
10
13
|
}
|
|
11
|
-
function runProcess(command, args, signal) {
|
|
14
|
+
function runProcess(command, args, signal, env) {
|
|
12
15
|
if (signal?.aborted)
|
|
13
16
|
return Promise.reject(abortReason(signal));
|
|
14
17
|
return new Promise((resolveValue, reject) => {
|
|
15
18
|
const child = spawn(command, args, {
|
|
16
19
|
stdio: ["ignore", "pipe", "pipe"],
|
|
20
|
+
env,
|
|
17
21
|
});
|
|
18
22
|
let stdout = "";
|
|
19
23
|
let stderr = "";
|
|
@@ -92,7 +96,135 @@ async function waitForDebugEndpoint(signal, timeout = BROWSER_START_TIMEOUT_MS)
|
|
|
92
96
|
}
|
|
93
97
|
await sleep(100, signal);
|
|
94
98
|
}
|
|
95
|
-
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}
|
|
99
|
+
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}. The browser may not support CDP startup flags or may have refused remote debugging for this profile. Enable remote debugging in the existing browser or set CDP_BROWSER to a compatible executable.`);
|
|
100
|
+
}
|
|
101
|
+
function hasGraphicalDesktop(env) {
|
|
102
|
+
return Boolean(env["WAYLAND_DISPLAY"]?.trim() || env["DISPLAY"]?.trim());
|
|
103
|
+
}
|
|
104
|
+
async function graphicalEnvironment(signal) {
|
|
105
|
+
if (!process.env["SSH_CONNECTION"] && hasGraphicalDesktop(process.env)) {
|
|
106
|
+
return { ...process.env };
|
|
107
|
+
}
|
|
108
|
+
// The remote worker inherits SSH's environment, which can select a
|
|
109
|
+
// different MIME association from the graphical systemd user session.
|
|
110
|
+
const result = await runProcess("busctl", [
|
|
111
|
+
"--user",
|
|
112
|
+
"--json=short",
|
|
113
|
+
"get-property",
|
|
114
|
+
"org.freedesktop.systemd1",
|
|
115
|
+
"/org/freedesktop/systemd1",
|
|
116
|
+
"org.freedesktop.systemd1.Manager",
|
|
117
|
+
"Environment",
|
|
118
|
+
], signal);
|
|
119
|
+
if (result.code !== 0)
|
|
120
|
+
throw new Error("systemd user environment unavailable");
|
|
121
|
+
const reply = asRecord(JSON.parse(result.stdout), "systemd user environment");
|
|
122
|
+
if (reply["type"] !== "as" || !Array.isArray(reply["data"])) {
|
|
123
|
+
throw new Error("Invalid systemd user environment");
|
|
124
|
+
}
|
|
125
|
+
const entries = [];
|
|
126
|
+
for (const assignment of reply["data"]) {
|
|
127
|
+
if (typeof assignment !== "string")
|
|
128
|
+
throw new Error("Invalid systemd environment variable");
|
|
129
|
+
const equals = assignment.indexOf("=");
|
|
130
|
+
if (equals <= 0)
|
|
131
|
+
throw new Error("Invalid systemd environment variable");
|
|
132
|
+
entries.push([assignment.slice(0, equals), assignment.slice(equals + 1)]);
|
|
133
|
+
}
|
|
134
|
+
const env = Object.fromEntries(entries);
|
|
135
|
+
if (!hasGraphicalDesktop(env))
|
|
136
|
+
throw new Error("systemd has no graphical desktop environment");
|
|
137
|
+
return env;
|
|
138
|
+
}
|
|
139
|
+
async function configuredDefaultBrowser(signal) {
|
|
140
|
+
const timeout = AbortSignal.timeout(5_000);
|
|
141
|
+
const lookupSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
142
|
+
let env;
|
|
143
|
+
try {
|
|
144
|
+
env = await graphicalEnvironment(lookupSignal);
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
signal?.throwIfAborted();
|
|
148
|
+
throw new Error("Could not determine the graphical desktop environment. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
|
|
149
|
+
}
|
|
150
|
+
// xdg-settings uses the shell's BROWSER setting ahead of desktop
|
|
151
|
+
// associations on generic desktops.
|
|
152
|
+
delete env["BROWSER"];
|
|
153
|
+
let id;
|
|
154
|
+
try {
|
|
155
|
+
const result = await runProcess("xdg-settings", ["get", "default-web-browser"], lookupSignal, env);
|
|
156
|
+
if (result.code !== 0)
|
|
157
|
+
throw new Error(result.stderr || `exit ${result.code}`);
|
|
158
|
+
id = result.stdout;
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
signal?.throwIfAborted();
|
|
162
|
+
throw new Error("Could not query the configured default browser with xdg-settings. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
|
|
163
|
+
}
|
|
164
|
+
return resolveDefaultBrowser(id, env);
|
|
165
|
+
}
|
|
166
|
+
async function browserLaunchCommand(host, port, signal) {
|
|
167
|
+
const switches = new Map([
|
|
168
|
+
["--remote-debugging-address", host],
|
|
169
|
+
["--remote-debugging-port", port],
|
|
170
|
+
]);
|
|
171
|
+
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
172
|
+
if (profile)
|
|
173
|
+
switches.set("--profile-directory", profile);
|
|
174
|
+
const override = process.env["CDP_BROWSER"];
|
|
175
|
+
if (override === "") {
|
|
176
|
+
throw new Error("CDP_BROWSER must name a compatible executable.");
|
|
177
|
+
}
|
|
178
|
+
const desktop = override
|
|
179
|
+
? {
|
|
180
|
+
executable: override,
|
|
181
|
+
args: ["about:blank"],
|
|
182
|
+
workingDirectory: undefined,
|
|
183
|
+
}
|
|
184
|
+
: await configuredDefaultBrowser(signal);
|
|
185
|
+
const fromDesktop = new Set();
|
|
186
|
+
for (const arg of desktop.args) {
|
|
187
|
+
if (arg === "--") {
|
|
188
|
+
throw new Error("The default browser's desktop command has an option separator, so CDP arguments cannot be appended safely. Set CDP_BROWSER or start the browser yourself with CDP enabled.");
|
|
189
|
+
}
|
|
190
|
+
const [name = ""] = arg.split("=", 1);
|
|
191
|
+
const key = name.startsWith("-") && !name.startsWith("--") ? `-${name}` : name;
|
|
192
|
+
const value = arg.startsWith(name + "=") ? arg.slice(name.length + 1) : "";
|
|
193
|
+
const configured = switches.get(key);
|
|
194
|
+
if (key === "--remote-debugging-pipe" ||
|
|
195
|
+
(configured !== undefined && configured !== value)) {
|
|
196
|
+
throw new Error(`The default browser's desktop arguments conflict with ${key}. Adjust the CDP configuration or start the browser yourself.`);
|
|
197
|
+
}
|
|
198
|
+
if (key === "--user-data-dir" &&
|
|
199
|
+
!isAbsolute(value) &&
|
|
200
|
+
!desktop.workingDirectory) {
|
|
201
|
+
throw new Error("The default browser uses a relative --user-data-dir without a desktop working directory. Start the browser yourself with CDP enabled.");
|
|
202
|
+
}
|
|
203
|
+
fromDesktop.add(key);
|
|
204
|
+
}
|
|
205
|
+
const args = [
|
|
206
|
+
// Only the selected entry knows its launcher's argument structure.
|
|
207
|
+
// Keep its complete argument prefix and attempt CDP, then probe the port.
|
|
208
|
+
...(override ? [] : desktop.args),
|
|
209
|
+
...[...switches]
|
|
210
|
+
.filter(([key]) => !fromDesktop.has(key))
|
|
211
|
+
.map(([key, value]) => `${key}=${value}`),
|
|
212
|
+
...(override ? desktop.args : []),
|
|
213
|
+
];
|
|
214
|
+
// systemd expands variables in ExecStart even without a shell. Preserve
|
|
215
|
+
// dollar signs in the executable path itself without changing which file runs.
|
|
216
|
+
const literalExecutable = desktop.executable.includes("$");
|
|
217
|
+
return [
|
|
218
|
+
...(desktop.workingDirectory
|
|
219
|
+
? [`--property=WorkingDirectory=${desktop.workingDirectory}`]
|
|
220
|
+
: []),
|
|
221
|
+
...(literalExecutable ? ["--expand-environment=no"] : []),
|
|
222
|
+
"--",
|
|
223
|
+
desktop.executable,
|
|
224
|
+
...(literalExecutable
|
|
225
|
+
? args
|
|
226
|
+
: args.map((arg) => arg.replaceAll("$", () => "$$"))),
|
|
227
|
+
];
|
|
96
228
|
}
|
|
97
229
|
async function unitExists(systemctl, signal) {
|
|
98
230
|
const result = await runProcess(systemctl, ["--user", "show", BROWSER_UNIT, "--property=LoadState", "--value"], signal);
|
|
@@ -129,7 +261,7 @@ export async function startBrowser(signal) {
|
|
|
129
261
|
}
|
|
130
262
|
const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
|
|
131
263
|
const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
|
|
132
|
-
|
|
264
|
+
let launchCommand;
|
|
133
265
|
let lastLaunchError = "";
|
|
134
266
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
135
267
|
const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
|
|
@@ -139,24 +271,15 @@ export async function startBrowser(signal) {
|
|
|
139
271
|
if (state === "timeout") {
|
|
140
272
|
throw new Error(`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`);
|
|
141
273
|
}
|
|
274
|
+
launchCommand ??= await browserLaunchCommand(host, port, signal);
|
|
142
275
|
await runProcess(systemctl, ["--user", "reset-failed", BROWSER_UNIT], signal);
|
|
143
|
-
const browserArgs = [
|
|
144
|
-
`--remote-debugging-address=${host}`,
|
|
145
|
-
`--remote-debugging-port=${port}`,
|
|
146
|
-
];
|
|
147
|
-
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
148
|
-
if (profile) {
|
|
149
|
-
browserArgs.push(`--profile-directory=${profile}`);
|
|
150
|
-
}
|
|
151
|
-
browserArgs.push("about:blank");
|
|
152
276
|
const launched = await runProcess(systemdRun, [
|
|
153
277
|
"--user",
|
|
154
278
|
"--unit=chrome-cdp-browser",
|
|
155
279
|
"--collect",
|
|
156
280
|
"--property=Type=exec",
|
|
157
281
|
"--property=Restart=no",
|
|
158
|
-
|
|
159
|
-
...browserArgs,
|
|
282
|
+
...launchCommand,
|
|
160
283
|
], signal);
|
|
161
284
|
if (launched.code === 0) {
|
|
162
285
|
await waitForDebugEndpoint(signal);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@howaboua/pi-browser",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.17",
|
|
4
4
|
"description": "Logged-in browser inspection and control for Pi, Code Mode and Notebook Mode.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -45,10 +45,10 @@
|
|
|
45
45
|
"format:check": "oxfmt --check '**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx,json,jsonc,json5,css}'"
|
|
46
46
|
},
|
|
47
47
|
"peerDependencies": {
|
|
48
|
-
"@howaboua/pi-codex-conversion": ">=5.1.
|
|
49
|
-
"@earendil-works/pi-ai": ">=1.
|
|
50
|
-
"@earendil-works/pi-coding-agent": ">=1.
|
|
51
|
-
"@earendil-works/pi-tui": ">=1.
|
|
48
|
+
"@howaboua/pi-codex-conversion": ">=5.1.3",
|
|
49
|
+
"@earendil-works/pi-ai": ">=1.7.0",
|
|
50
|
+
"@earendil-works/pi-coding-agent": ">=1.7.0",
|
|
51
|
+
"@earendil-works/pi-tui": ">=1.7.0"
|
|
52
52
|
},
|
|
53
53
|
"peerDependenciesMeta": {
|
|
54
54
|
"@howaboua/pi-codex-conversion": {
|
|
@@ -56,9 +56,9 @@
|
|
|
56
56
|
}
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"@howaboua/pi-codex-conversion": "5.1.
|
|
60
|
-
"@earendil-works/pi-ai": "1.
|
|
61
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
59
|
+
"@howaboua/pi-codex-conversion": "5.1.3",
|
|
60
|
+
"@earendil-works/pi-ai": "1.7.0",
|
|
61
|
+
"@earendil-works/pi-coding-agent": "1.7.0",
|
|
62
62
|
"@types/node": "26.6.6",
|
|
63
63
|
"typescript": "7.0.2",
|
|
64
64
|
"oxfmt": "0.79.0"
|
|
@@ -90,6 +90,6 @@
|
|
|
90
90
|
"access": "public"
|
|
91
91
|
},
|
|
92
92
|
"dependencies": {
|
|
93
|
-
"@earendil-works/pi-schema": "1.
|
|
93
|
+
"@earendil-works/pi-schema": "1.7.0"
|
|
94
94
|
}
|
|
95
95
|
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access, readdir, readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { isAbsolute, join } from "node:path";
|
|
5
|
+
|
|
6
|
+
interface DesktopBrowser {
|
|
7
|
+
executable: string;
|
|
8
|
+
args: string[];
|
|
9
|
+
workingDirectory: string | undefined;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const RECOVERY =
|
|
13
|
+
"Set CDP_BROWSER to a compatible executable, or start a browser with CDP enabled yourself.";
|
|
14
|
+
|
|
15
|
+
async function missingIsUndefined<T>(
|
|
16
|
+
operation: Promise<T>,
|
|
17
|
+
): Promise<T | undefined> {
|
|
18
|
+
try {
|
|
19
|
+
return await operation;
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (
|
|
22
|
+
error &&
|
|
23
|
+
typeof error === "object" &&
|
|
24
|
+
"code" in error &&
|
|
25
|
+
(error.code === "ENOENT" || error.code === "ENOTDIR")
|
|
26
|
+
) {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function desktopFiles(directory: string, id: string): Promise<string[]> {
|
|
34
|
+
const entries = await missingIsUndefined(
|
|
35
|
+
readdir(directory, { withFileTypes: true }),
|
|
36
|
+
);
|
|
37
|
+
const paths: string[] = [];
|
|
38
|
+
for (const entry of entries ?? []) {
|
|
39
|
+
const path = join(directory, entry.name);
|
|
40
|
+
if (entry.name === id && !entry.isDirectory()) {
|
|
41
|
+
paths.push(path);
|
|
42
|
+
} else if (entry.isDirectory() && id.startsWith(entry.name + "-")) {
|
|
43
|
+
// Nested entries derive their IDs by replacing '/' with '-'.
|
|
44
|
+
paths.push(
|
|
45
|
+
...(await desktopFiles(path, id.slice(entry.name.length + 1))),
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return paths;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function findDesktopFile(
|
|
53
|
+
id: string,
|
|
54
|
+
env: NodeJS.ProcessEnv,
|
|
55
|
+
): Promise<string> {
|
|
56
|
+
const userData = env["XDG_DATA_HOME"];
|
|
57
|
+
const home = env["HOME"];
|
|
58
|
+
const systemData = (env["XDG_DATA_DIRS"] || "/usr/local/share:/usr/share")
|
|
59
|
+
.split(":")
|
|
60
|
+
.filter(isAbsolute);
|
|
61
|
+
const roots = [
|
|
62
|
+
userData && isAbsolute(userData)
|
|
63
|
+
? userData
|
|
64
|
+
: join(home && isAbsolute(home) ? home : homedir(), ".local/share"),
|
|
65
|
+
...systemData,
|
|
66
|
+
];
|
|
67
|
+
for (const root of roots) {
|
|
68
|
+
const [path, ambiguous] = await desktopFiles(
|
|
69
|
+
join(root, "applications"),
|
|
70
|
+
id,
|
|
71
|
+
);
|
|
72
|
+
if (ambiguous) throw new Error("the desktop ID is ambiguous");
|
|
73
|
+
if (path) return path;
|
|
74
|
+
}
|
|
75
|
+
throw new Error("the desktop entry was not found");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function desktopEntry(source: string): Map<string, string> {
|
|
79
|
+
const entry = new Map<string, string>();
|
|
80
|
+
let inDesktopEntry = false;
|
|
81
|
+
for (const line of source.split(/\r?\n/)) {
|
|
82
|
+
const trimmed = line.trim();
|
|
83
|
+
if (trimmed.startsWith("[")) {
|
|
84
|
+
if (inDesktopEntry) break;
|
|
85
|
+
inDesktopEntry = trimmed === "[Desktop Entry]";
|
|
86
|
+
} else if (inDesktopEntry && trimmed && !trimmed.startsWith("#")) {
|
|
87
|
+
const equals = trimmed.indexOf("=");
|
|
88
|
+
if (equals < 1) throw new Error("invalid desktop entry");
|
|
89
|
+
const key = trimmed.slice(0, equals).trimEnd();
|
|
90
|
+
if (entry.has(key)) throw new Error("duplicate desktop entry key");
|
|
91
|
+
entry.set(key, trimmed.slice(equals + 1).trimStart());
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return entry;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function desktopString(value: string): string {
|
|
98
|
+
const escapes: Record<string, string> = {
|
|
99
|
+
s: " ",
|
|
100
|
+
n: "\n",
|
|
101
|
+
t: "\t",
|
|
102
|
+
r: "\r",
|
|
103
|
+
"\\": "\\",
|
|
104
|
+
};
|
|
105
|
+
return value.replace(/\\(.|$)/g, (_match, char: string) => {
|
|
106
|
+
const replacement = escapes[char];
|
|
107
|
+
if (replacement === undefined)
|
|
108
|
+
throw new Error("invalid desktop entry escape");
|
|
109
|
+
return replacement;
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function execArguments(line: string): string[] {
|
|
114
|
+
// Desktop Entry quoting is not shell quoting. Accept literal words and
|
|
115
|
+
// whole double-quoted arguments only; leave nonliteral launchers unsupported.
|
|
116
|
+
const word =
|
|
117
|
+
/(?:"(?:[^"\\]|\\["`$\\])*"|[^ \t\n\r"'\\><~|&;$*?#()`]+)(?=[ \t]|$)/y;
|
|
118
|
+
const args: string[] = [];
|
|
119
|
+
let hasInputField = false;
|
|
120
|
+
for (let remaining = desktopString(line).trim(); remaining;) {
|
|
121
|
+
const match = word.exec(remaining)?.[0];
|
|
122
|
+
if (match === undefined)
|
|
123
|
+
throw new Error("unsupported desktop Exec quoting");
|
|
124
|
+
remaining = remaining.slice(match.length).trimStart();
|
|
125
|
+
word.lastIndex = 0;
|
|
126
|
+
if (args.length !== 0 && /^%[fFuU]$/.test(match)) {
|
|
127
|
+
if (hasInputField) throw new Error("multiple desktop Exec input fields");
|
|
128
|
+
hasInputField = true;
|
|
129
|
+
continue; // No URL or file was requested.
|
|
130
|
+
}
|
|
131
|
+
const unquoted = match.startsWith('"')
|
|
132
|
+
? match.slice(1, -1).replace(/\\(.)/gs, "$1")
|
|
133
|
+
: match;
|
|
134
|
+
args.push(
|
|
135
|
+
unquoted.replace(/%%|%/g, (percent) => {
|
|
136
|
+
if (percent === "%%") return "%";
|
|
137
|
+
throw new Error("unsupported desktop Exec field code");
|
|
138
|
+
}),
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
return args;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function executablePath(
|
|
145
|
+
executable: string,
|
|
146
|
+
env: NodeJS.ProcessEnv,
|
|
147
|
+
): Promise<string | undefined> {
|
|
148
|
+
const candidates = isAbsolute(executable)
|
|
149
|
+
? [executable]
|
|
150
|
+
: executable.includes("/")
|
|
151
|
+
? []
|
|
152
|
+
: (env["PATH"] ?? "/usr/bin:/bin")
|
|
153
|
+
.split(":")
|
|
154
|
+
.filter(isAbsolute)
|
|
155
|
+
.map((directory) => join(directory, executable));
|
|
156
|
+
for (const path of candidates) {
|
|
157
|
+
try {
|
|
158
|
+
await access(path, constants.X_OK);
|
|
159
|
+
if ((await stat(path)).isFile()) return path;
|
|
160
|
+
} catch {
|
|
161
|
+
// Keep looking on PATH when a candidate isn't executable.
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function resolveDefaultBrowser(
|
|
168
|
+
id: string,
|
|
169
|
+
env: NodeJS.ProcessEnv,
|
|
170
|
+
): Promise<DesktopBrowser> {
|
|
171
|
+
if (!/^[A-Za-z0-9_.-]+\.desktop$/.test(id)) {
|
|
172
|
+
throw new Error(
|
|
173
|
+
"Could not determine the configured default browser. " + RECOVERY,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const path = await findDesktopFile(id, env);
|
|
178
|
+
if (!(await stat(path)).isFile())
|
|
179
|
+
throw new Error("invalid desktop entry file");
|
|
180
|
+
const entry = desktopEntry(await readFile(path, "utf8"));
|
|
181
|
+
if (
|
|
182
|
+
entry.get("Type") !== "Application" ||
|
|
183
|
+
entry.get("Hidden") === "true" ||
|
|
184
|
+
entry.get("Terminal") === "true" ||
|
|
185
|
+
entry.get("DBusActivatable") === "true"
|
|
186
|
+
) {
|
|
187
|
+
throw new Error(
|
|
188
|
+
"the desktop entry does not use direct application startup",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
const [command, ...args] = execArguments(entry.get("Exec") ?? "");
|
|
192
|
+
if (!command || command.includes("=")) {
|
|
193
|
+
throw new Error("the desktop entry has no valid executable");
|
|
194
|
+
}
|
|
195
|
+
const executable = await executablePath(command, env);
|
|
196
|
+
const tryExec = desktopString(entry.get("TryExec") ?? "");
|
|
197
|
+
if (!executable || (tryExec && !(await executablePath(tryExec, env)))) {
|
|
198
|
+
throw new Error("the desktop executable is unavailable");
|
|
199
|
+
}
|
|
200
|
+
const workingDirectory =
|
|
201
|
+
desktopString(entry.get("Path") ?? "") || undefined;
|
|
202
|
+
if (workingDirectory && !isAbsolute(workingDirectory)) {
|
|
203
|
+
throw new Error("the desktop working directory is not absolute");
|
|
204
|
+
}
|
|
205
|
+
return { executable, args, workingDirectory };
|
|
206
|
+
} catch (error) {
|
|
207
|
+
throw new Error(
|
|
208
|
+
'Cannot start the default browser "' +
|
|
209
|
+
id +
|
|
210
|
+
'": ' +
|
|
211
|
+
(error instanceof Error ? error.message : String(error)) +
|
|
212
|
+
". " +
|
|
213
|
+
RECOVERY,
|
|
214
|
+
{ cause: error },
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
}
|
package/src/browser/launcher.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
2
3
|
import { probeDebugPort, sleep } from "../cdp/discovery.js";
|
|
4
|
+
import { asRecord } from "../cdp/types.js";
|
|
5
|
+
import { resolveDefaultBrowser } from "./default-browser.js";
|
|
3
6
|
|
|
4
7
|
const BROWSER_START_TIMEOUT_MS = 10_000;
|
|
5
8
|
const BROWSER_UNIT = "chrome-cdp-browser.service";
|
|
@@ -21,11 +24,13 @@ function runProcess(
|
|
|
21
24
|
command: string,
|
|
22
25
|
args: string[],
|
|
23
26
|
signal?: AbortSignal,
|
|
27
|
+
env?: NodeJS.ProcessEnv,
|
|
24
28
|
): Promise<ProcessResult> {
|
|
25
29
|
if (signal?.aborted) return Promise.reject(abortReason(signal));
|
|
26
30
|
return new Promise((resolveValue, reject) => {
|
|
27
31
|
const child = spawn(command, args, {
|
|
28
32
|
stdio: ["ignore", "pipe", "pipe"],
|
|
33
|
+
env,
|
|
29
34
|
});
|
|
30
35
|
let stdout = "";
|
|
31
36
|
let stderr = "";
|
|
@@ -106,10 +111,170 @@ async function waitForDebugEndpoint(
|
|
|
106
111
|
throw new Error(
|
|
107
112
|
`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${
|
|
108
113
|
lastError instanceof Error ? ` (${lastError.message})` : ""
|
|
109
|
-
}
|
|
114
|
+
}. The browser may not support CDP startup flags or may have refused remote debugging for this profile. Enable remote debugging in the existing browser or set CDP_BROWSER to a compatible executable.`,
|
|
110
115
|
);
|
|
111
116
|
}
|
|
112
117
|
|
|
118
|
+
function hasGraphicalDesktop(env: NodeJS.ProcessEnv): boolean {
|
|
119
|
+
return Boolean(env["WAYLAND_DISPLAY"]?.trim() || env["DISPLAY"]?.trim());
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function graphicalEnvironment(
|
|
123
|
+
signal: AbortSignal,
|
|
124
|
+
): Promise<NodeJS.ProcessEnv> {
|
|
125
|
+
if (!process.env["SSH_CONNECTION"] && hasGraphicalDesktop(process.env)) {
|
|
126
|
+
return { ...process.env };
|
|
127
|
+
}
|
|
128
|
+
// The remote worker inherits SSH's environment, which can select a
|
|
129
|
+
// different MIME association from the graphical systemd user session.
|
|
130
|
+
const result = await runProcess(
|
|
131
|
+
"busctl",
|
|
132
|
+
[
|
|
133
|
+
"--user",
|
|
134
|
+
"--json=short",
|
|
135
|
+
"get-property",
|
|
136
|
+
"org.freedesktop.systemd1",
|
|
137
|
+
"/org/freedesktop/systemd1",
|
|
138
|
+
"org.freedesktop.systemd1.Manager",
|
|
139
|
+
"Environment",
|
|
140
|
+
],
|
|
141
|
+
signal,
|
|
142
|
+
);
|
|
143
|
+
if (result.code !== 0)
|
|
144
|
+
throw new Error("systemd user environment unavailable");
|
|
145
|
+
const reply = asRecord(JSON.parse(result.stdout), "systemd user environment");
|
|
146
|
+
if (reply["type"] !== "as" || !Array.isArray(reply["data"])) {
|
|
147
|
+
throw new Error("Invalid systemd user environment");
|
|
148
|
+
}
|
|
149
|
+
const entries: [string, string][] = [];
|
|
150
|
+
for (const assignment of reply["data"]) {
|
|
151
|
+
if (typeof assignment !== "string")
|
|
152
|
+
throw new Error("Invalid systemd environment variable");
|
|
153
|
+
const equals = assignment.indexOf("=");
|
|
154
|
+
if (equals <= 0) throw new Error("Invalid systemd environment variable");
|
|
155
|
+
entries.push([assignment.slice(0, equals), assignment.slice(equals + 1)]);
|
|
156
|
+
}
|
|
157
|
+
const env = Object.fromEntries(entries);
|
|
158
|
+
if (!hasGraphicalDesktop(env))
|
|
159
|
+
throw new Error("systemd has no graphical desktop environment");
|
|
160
|
+
return env;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function configuredDefaultBrowser(signal?: AbortSignal) {
|
|
164
|
+
const timeout = AbortSignal.timeout(5_000);
|
|
165
|
+
const lookupSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
166
|
+
let env: NodeJS.ProcessEnv;
|
|
167
|
+
try {
|
|
168
|
+
env = await graphicalEnvironment(lookupSignal);
|
|
169
|
+
} catch (error) {
|
|
170
|
+
signal?.throwIfAborted();
|
|
171
|
+
throw new Error(
|
|
172
|
+
"Could not determine the graphical desktop environment. Set CDP_BROWSER or start a browser with CDP enabled yourself.",
|
|
173
|
+
{ cause: error },
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
// xdg-settings uses the shell's BROWSER setting ahead of desktop
|
|
177
|
+
// associations on generic desktops.
|
|
178
|
+
delete env["BROWSER"];
|
|
179
|
+
let id: string;
|
|
180
|
+
try {
|
|
181
|
+
const result = await runProcess(
|
|
182
|
+
"xdg-settings",
|
|
183
|
+
["get", "default-web-browser"],
|
|
184
|
+
lookupSignal,
|
|
185
|
+
env,
|
|
186
|
+
);
|
|
187
|
+
if (result.code !== 0)
|
|
188
|
+
throw new Error(result.stderr || `exit ${result.code}`);
|
|
189
|
+
id = result.stdout;
|
|
190
|
+
} catch (error) {
|
|
191
|
+
signal?.throwIfAborted();
|
|
192
|
+
throw new Error(
|
|
193
|
+
"Could not query the configured default browser with xdg-settings. Set CDP_BROWSER or start a browser with CDP enabled yourself.",
|
|
194
|
+
{ cause: error },
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return resolveDefaultBrowser(id, env);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function browserLaunchCommand(
|
|
201
|
+
host: string,
|
|
202
|
+
port: string,
|
|
203
|
+
signal?: AbortSignal,
|
|
204
|
+
): Promise<string[]> {
|
|
205
|
+
const switches = new Map([
|
|
206
|
+
["--remote-debugging-address", host],
|
|
207
|
+
["--remote-debugging-port", port],
|
|
208
|
+
]);
|
|
209
|
+
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
210
|
+
if (profile) switches.set("--profile-directory", profile);
|
|
211
|
+
const override = process.env["CDP_BROWSER"];
|
|
212
|
+
if (override === "") {
|
|
213
|
+
throw new Error("CDP_BROWSER must name a compatible executable.");
|
|
214
|
+
}
|
|
215
|
+
const desktop = override
|
|
216
|
+
? {
|
|
217
|
+
executable: override,
|
|
218
|
+
args: ["about:blank"],
|
|
219
|
+
workingDirectory: undefined,
|
|
220
|
+
}
|
|
221
|
+
: await configuredDefaultBrowser(signal);
|
|
222
|
+
const fromDesktop = new Set<string>();
|
|
223
|
+
for (const arg of desktop.args) {
|
|
224
|
+
if (arg === "--") {
|
|
225
|
+
throw new Error(
|
|
226
|
+
"The default browser's desktop command has an option separator, so CDP arguments cannot be appended safely. Set CDP_BROWSER or start the browser yourself with CDP enabled.",
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
const [name = ""] = arg.split("=", 1);
|
|
230
|
+
const key =
|
|
231
|
+
name.startsWith("-") && !name.startsWith("--") ? `-${name}` : name;
|
|
232
|
+
const value = arg.startsWith(name + "=") ? arg.slice(name.length + 1) : "";
|
|
233
|
+
const configured = switches.get(key);
|
|
234
|
+
if (
|
|
235
|
+
key === "--remote-debugging-pipe" ||
|
|
236
|
+
(configured !== undefined && configured !== value)
|
|
237
|
+
) {
|
|
238
|
+
throw new Error(
|
|
239
|
+
`The default browser's desktop arguments conflict with ${key}. Adjust the CDP configuration or start the browser yourself.`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
if (
|
|
243
|
+
key === "--user-data-dir" &&
|
|
244
|
+
!isAbsolute(value) &&
|
|
245
|
+
!desktop.workingDirectory
|
|
246
|
+
) {
|
|
247
|
+
throw new Error(
|
|
248
|
+
"The default browser uses a relative --user-data-dir without a desktop working directory. Start the browser yourself with CDP enabled.",
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
fromDesktop.add(key);
|
|
252
|
+
}
|
|
253
|
+
const args = [
|
|
254
|
+
// Only the selected entry knows its launcher's argument structure.
|
|
255
|
+
// Keep its complete argument prefix and attempt CDP, then probe the port.
|
|
256
|
+
...(override ? [] : desktop.args),
|
|
257
|
+
...[...switches]
|
|
258
|
+
.filter(([key]) => !fromDesktop.has(key))
|
|
259
|
+
.map(([key, value]) => `${key}=${value}`),
|
|
260
|
+
...(override ? desktop.args : []),
|
|
261
|
+
];
|
|
262
|
+
// systemd expands variables in ExecStart even without a shell. Preserve
|
|
263
|
+
// dollar signs in the executable path itself without changing which file runs.
|
|
264
|
+
const literalExecutable = desktop.executable.includes("$");
|
|
265
|
+
return [
|
|
266
|
+
...(desktop.workingDirectory
|
|
267
|
+
? [`--property=WorkingDirectory=${desktop.workingDirectory}`]
|
|
268
|
+
: []),
|
|
269
|
+
...(literalExecutable ? ["--expand-environment=no"] : []),
|
|
270
|
+
"--",
|
|
271
|
+
desktop.executable,
|
|
272
|
+
...(literalExecutable
|
|
273
|
+
? args
|
|
274
|
+
: args.map((arg) => arg.replaceAll("$", () => "$$"))),
|
|
275
|
+
];
|
|
276
|
+
}
|
|
277
|
+
|
|
113
278
|
async function unitExists(
|
|
114
279
|
systemctl: string,
|
|
115
280
|
signal?: AbortSignal,
|
|
@@ -156,7 +321,7 @@ export async function startBrowser(signal?: AbortSignal): Promise<string> {
|
|
|
156
321
|
}
|
|
157
322
|
const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
|
|
158
323
|
const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
|
|
159
|
-
|
|
324
|
+
let launchCommand: string[] | undefined;
|
|
160
325
|
let lastLaunchError = "";
|
|
161
326
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
162
327
|
const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
|
|
@@ -168,20 +333,12 @@ export async function startBrowser(signal?: AbortSignal): Promise<string> {
|
|
|
168
333
|
`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`,
|
|
169
334
|
);
|
|
170
335
|
}
|
|
336
|
+
launchCommand ??= await browserLaunchCommand(host, port, signal);
|
|
171
337
|
await runProcess(
|
|
172
338
|
systemctl,
|
|
173
339
|
["--user", "reset-failed", BROWSER_UNIT],
|
|
174
340
|
signal,
|
|
175
341
|
);
|
|
176
|
-
const browserArgs = [
|
|
177
|
-
`--remote-debugging-address=${host}`,
|
|
178
|
-
`--remote-debugging-port=${port}`,
|
|
179
|
-
];
|
|
180
|
-
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
181
|
-
if (profile) {
|
|
182
|
-
browserArgs.push(`--profile-directory=${profile}`);
|
|
183
|
-
}
|
|
184
|
-
browserArgs.push("about:blank");
|
|
185
342
|
const launched = await runProcess(
|
|
186
343
|
systemdRun,
|
|
187
344
|
[
|
|
@@ -190,8 +347,7 @@ export async function startBrowser(signal?: AbortSignal): Promise<string> {
|
|
|
190
347
|
"--collect",
|
|
191
348
|
"--property=Type=exec",
|
|
192
349
|
"--property=Restart=no",
|
|
193
|
-
|
|
194
|
-
...browserArgs,
|
|
350
|
+
...launchCommand,
|
|
195
351
|
],
|
|
196
352
|
signal,
|
|
197
353
|
);
|