aboutsummaryrefslogtreecommitdiff
path: root/src/cdp
diff options
context:
space:
mode:
Diffstat (limited to 'src/cdp')
-rw-r--r--src/cdp/discovery.ts3
-rw-r--r--src/cdp/endpoint.ts76
-rw-r--r--src/cdp/target-store.ts87
3 files changed, 145 insertions, 21 deletions
diff --git a/src/cdp/discovery.ts b/src/cdp/discovery.ts
index 53d4ad2..84da5f9 100644
--- a/src/cdp/discovery.ts
+++ b/src/cdp/discovery.ts
@@ -7,6 +7,7 @@ import { userDataDirCandidates } from "../profile/paths";
import { type CdpError, cdpError } from "./errors";
import { asString, errnoCode, isRecord } from "../util/guards";
import { describeCdpTarget, resolveCdpTarget } from "./endpoint";
+import { readTarget } from "./target-store";
const PORT_PROBE_DEADLINE_MS = 30_000;
const PORT_PROBE_INTERVAL_MS = 1_000;
@@ -127,7 +128,7 @@ export const discoverEndpoint = async (): Promise<Result<CdpEndpoint, CdpError>>
// No userDataDir is returned: the profile registry lives on the remote host,
// so profile enumeration degrades to the pre-profile behaviour rather than
// reading the wrong machine's Local State.
- const target = resolveCdpTarget();
+ const target = resolveCdpTarget(process.env, await readTarget());
if (target.kind === "invalid") {
return err(cdpError("discovery_failed", describeCdpTarget(target)));
}
diff --git a/src/cdp/endpoint.ts b/src/cdp/endpoint.ts
index 1be5322..96cf2ea 100644
--- a/src/cdp/endpoint.ts
+++ b/src/cdp/endpoint.ts
@@ -15,31 +15,53 @@ export const DEFAULT_REMOTE_CDP = "10.88.0.25:9223";
/** Values of BU_CDP_HTTP that mean "ignore the default, use this machine". */
const LOCAL_ALIASES = new Set(["local", "localhost", "off", "none", "0", "no"]);
+/**
+ * Where a target came from. "env" is BU_CDP_HTTP, "stored" is /browser-target,
+ * "default" is this fork's built-in. Only "default" is allowed to fall back.
+ */
+export type CdpTargetSource = "env" | "stored" | "default";
+
export type CdpTarget =
| {
readonly kind: "remote";
readonly host: string;
readonly port: number;
- /** "env" was asked for explicitly; "default" is this fork's built-in. */
- readonly source: "env" | "default";
+ readonly source: CdpTargetSource;
}
- | { readonly kind: "local"; readonly source: "env" }
- | { readonly kind: "invalid"; readonly raw: string; readonly reason: string };
+ | { readonly kind: "local"; readonly source: Exclude<CdpTargetSource, "default"> }
+ | { readonly kind: "invalid"; readonly raw: string; readonly reason: string; readonly source: CdpTargetSource };
/**
- * Precedence:
- * BU_CDP_HTTP="host:port" -> that remote, and a failure to reach it is fatal
- * BU_CDP_HTTP=local|off|… -> upstream behaviour, this machine's own browser
- * unset -> DEFAULT_REMOTE_CDP, falling back to local when
- * it isn't reachable
+ * Precedence: BU_CDP_HTTP, then the /browser-target choice, then the built-in
+ * default.
+ *
+ * "host:port" -> that remote, and a failure to reach it is fatal
+ * local|off|… -> upstream behaviour, this machine's own browser
+ * neither set -> DEFAULT_REMOTE_CDP, falling back to local when unreachable
+ *
+ * The environment wins over the stored choice so that a one-off
+ * `BU_CDP_HTTP=… pi` is never silently overridden by a setting made days ago.
+ *
+ * The fallback asymmetry is deliberate. An explicit endpoint — from either
+ * source — is an instruction, so silently driving a different browser instead
+ * would be wrong: it would automate the operator's own signed-in Chrome rather
+ * than the shared one. The built-in default is only a preference, so a laptop
+ * away from the wire network still gets the local browser the extension was
+ * originally written for.
*
- * The asymmetry is deliberate. An explicit endpoint is an instruction, so
- * silently driving a different browser instead would be wrong. The built-in
- * default is only a preference, so a laptop away from the wire network still
- * gets the local browser the extension was originally written for.
+ * `stored` is passed in rather than read here so this stays pure and
+ * synchronous: /browser-status can describe the target without I/O, and the
+ * daemon can resolve identically in its own process.
*/
-export const resolveCdpTarget = (env: NodeJS.ProcessEnv = process.env): CdpTarget => {
- const raw = env["BU_CDP_HTTP"]?.trim();
+export const resolveCdpTarget = (
+ env: NodeJS.ProcessEnv = process.env,
+ stored: string | null = null,
+): CdpTarget => {
+ const fromEnv = env["BU_CDP_HTTP"]?.trim();
+ const fromStore = stored?.trim();
+
+ const raw = fromEnv !== undefined && fromEnv !== "" ? fromEnv : fromStore;
+ const source: CdpTargetSource = fromEnv !== undefined && fromEnv !== "" ? "env" : "stored";
if (raw === undefined || raw === "") {
const parsed = parseHostPort(DEFAULT_REMOTE_CDP);
@@ -48,17 +70,28 @@ export const resolveCdpTarget = (env: NodeJS.ProcessEnv = process.env): CdpTarge
return { kind: "remote", host: parsed.host, port: parsed.port, source: "default" };
}
- if (LOCAL_ALIASES.has(raw.toLowerCase())) return { kind: "local", source: "env" };
+ if (LOCAL_ALIASES.has(raw.toLowerCase())) return { kind: "local", source };
const parsed = parseHostPort(raw);
if (!parsed) {
return {
kind: "invalid",
raw,
+ source,
reason: `expected "host:port" or one of ${[...LOCAL_ALIASES].join(", ")}`,
};
}
- return { kind: "remote", host: parsed.host, port: parsed.port, source: "env" };
+ return { kind: "remote", host: parsed.host, port: parsed.port, source };
+};
+
+/** The vocabulary /browser-target accepts, for help text and validation. */
+export const localAliases = (): ReadonlyArray<string> => [...LOCAL_ALIASES];
+
+/** True when `value` is something resolveCdpTarget can make sense of. */
+export const isValidTargetValue = (value: string): boolean => {
+ const v = value.trim();
+ if (v === "") return false;
+ return LOCAL_ALIASES.has(v.toLowerCase()) || parseHostPort(v) !== null;
};
const parseHostPort = (value: string): { host: string; port: number } | null => {
@@ -71,14 +104,17 @@ const parseHostPort = (value: string): { host: string; port: number } | null =>
return { host, port };
};
+const sourceLabel = (source: CdpTargetSource): string =>
+ source === "env" ? "BU_CDP_HTTP" : source === "stored" ? "/browser-target" : "built-in default";
+
/** One-line description for /browser-status and error messages. */
export const describeCdpTarget = (target: CdpTarget): string => {
switch (target.kind) {
case "remote":
- return `${target.host}:${target.port}` + (target.source === "default" ? " (built-in default)" : " (BU_CDP_HTTP)");
+ return `${target.host}:${target.port} (${sourceLabel(target.source)})`;
case "local":
- return "this machine's own browser (BU_CDP_HTTP=local)";
+ return `this machine's own browser (${sourceLabel(target.source)})`;
case "invalid":
- return `invalid BU_CDP_HTTP "${target.raw}" — ${target.reason}`;
+ return `invalid target "${target.raw}" from ${sourceLabel(target.source)} — ${target.reason}`;
}
};
diff --git a/src/cdp/target-store.ts b/src/cdp/target-store.ts
new file mode 100644
index 0000000..3a35f0a
--- /dev/null
+++ b/src/cdp/target-store.ts
@@ -0,0 +1,87 @@
+/**
+ * FORK: durable persistence for the chosen CDP target.
+ *
+ * `/browser-target` has to outlive the pi session that ran it, because the
+ * browser daemon is machine-wide and shared by every session — so the choice
+ * cannot live in pi's session entries. Same reasoning, and the same atomic
+ * write, as the profile pin in src/profile/store.ts; a separate file so a
+ * corrupt target cannot cost you your profile selection.
+ *
+ * The stored value is the raw string a user would have put in BU_CDP_HTTP
+ * ("local", "10.88.0.25:9223", …). It is deliberately NOT pre-parsed: keeping
+ * it in the same vocabulary as the environment variable means one resolution
+ * path in src/cdp/endpoint.ts, and a stored value can never mean something the
+ * variable could not.
+ *
+ * Every read failure degrades to "nothing stored" rather than throwing — a
+ * corrupt file must never break browser control, it should just fall back to
+ * the built-in default.
+ */
+
+import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
+import { randomUUID } from "node:crypto";
+import { dirname } from "node:path";
+import { type Result, err, ok } from "../util/result";
+import { isRecord } from "../util/guards";
+import { targetFilePath } from "../profile/paths";
+
+const CURRENT_VERSION = 1;
+
+type TargetFile = {
+ readonly version: 1;
+ /** Raw BU_CDP_HTTP-style value, or null when cleared. */
+ readonly target: string | null;
+ readonly savedAt: string;
+};
+
+/**
+ * The persisted target, or null when nothing is stored, the file is missing, or
+ * it cannot be parsed. A file written by a newer version is treated as "nothing
+ * stored" rather than guessed at.
+ */
+export const readTarget = async (): Promise<string | null> => {
+ let raw: string;
+ try {
+ raw = await readFile(targetFilePath(), "utf8");
+ } catch {
+ return null;
+ }
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!isRecord(parsed)) return null;
+ const file = parsed;
+ if (file["version"] !== CURRENT_VERSION) return null;
+ const target = file["target"];
+ if (typeof target !== "string") return null;
+ const trimmed = target.trim();
+ return trimmed.length > 0 ? trimmed : null;
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * Replace the target atomically: a sibling temp file plus rename, so a crash
+ * mid-write cannot leave a half-written target behind — which would otherwise
+ * silently point the agent at the wrong browser.
+ */
+const writeTargetFile = async (target: string | null): Promise<Result<void, string>> => {
+ const path = targetFilePath();
+ const tmp = `${path}.${randomUUID()}.tmp`;
+ const payload: TargetFile = { version: CURRENT_VERSION, target, savedAt: new Date().toISOString() };
+ try {
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
+ await rename(tmp, path);
+ return ok(undefined);
+ } catch (e) {
+ await unlink(tmp).catch(() => {});
+ return err(`could not save browser target to ${path}: ${e instanceof Error ? e.message : String(e)}`);
+ }
+};
+
+/** Persist the chosen target. */
+export const writeTarget = (target: string): Promise<Result<void, string>> => writeTargetFile(target);
+
+/** Clear the choice, restoring the built-in default. */
+export const clearTarget = (): Promise<Result<void, string>> => writeTargetFile(null);