openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
174 lines (173 loc) • 6.14 kB
JavaScript
import { a as extractErrorCode } from "../../error-coercion-hDrHOSGy.mjs";
import { t as createSubsystemLogger } from "../../subsystem-BHJiy01V.mjs";
import { t as captureRuntimeConfigAsyncReader } from "../../io.runtime-DsJ2dLCQ.mjs";
import "../../runtime-config-snapshot-Dy0VFqWf.mjs";
import { t as readBrowserHostConfig } from "../../extension-host-config-6_kpZWRa.mjs";
import { a as createDeferred } from "../../extension-shared-CJ4teJ7p.mjs";
import "../../logging-core-DxpUImpb.mjs";
import "../../security-runtime-C-zE_Zy_.mjs";
import { i as resolveBrowserConfig, s as resolveProfile } from "../../config-ccOD-Wrr.mjs";
import { n as readExtensionRelayToken } from "../../relay-auth-C1jzy9Sz.mjs";
import { n as startExtensionRelayServer } from "../../relay-server-Dwyc1R3f.mjs";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
//#region extensions/browser/src/browser/relay-daemon.ts
const log = createSubsystemLogger("browser").child("relay-daemon");
/** Default grace before a daemon with no extension and no CDP clients exits. */
const RELAY_DAEMON_IDLE_EXIT_MS = 6e5;
const IDLE_POLL_MS = 3e4;
/**
* On-disk identity of the file the daemon was launched from. An in-place app or
* package update keeps the path but installs new files, so the path alone
* cannot tell this installation from its replacement. Null when the file is
* gone; undefined when it cannot be read, which is not proof of replacement.
*/
function readInstallationIdentity(e) {
try {
const t = fs.statSync(e, {
bigint: true,
throwIfNoEntry: false
});
return t ? `${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}` : null;
} catch {
return;
}
}
/**
* Run the standalone extension relay daemon: one loopback relay server with no
* Gateway. The daemon stays alive while the paired extension holds its relay
* connection or a CDP client is attached, and exits once both sides have been
* gone for the idle grace so an idle daemon never outlives Chrome. It also
* exits, peers or not, once the installation it was launched from is replaced
* or removed: the extension's reconnect then wakes the native host of the
* current installation instead of adopting a relay from a retired one.
* The caller awaits done and owns process.exit.
* The returned port is null when startup was refused.
*/
async function runExtensionRelayDaemon(e) {
const t = e.allowLegacyAuth ?? false;
const n = Date.now;
const r = e.installationPath;
const i = r ? readInstallationIdentity(r) : null;
if (r && !i) log.warn(`relay daemon cannot read its installation at ${r}; update detection is off`);
const a = createDeferred();
const o = readExtensionRelayToken();
if (!o) {
log.warn("relay daemon refused to start: no extension relay credential");
a.resolve("no-credential");
return {
done: a.promise,
port: null,
stop: () => {}
};
}
let s;
try {
const n = await captureRuntimeConfigAsyncReader()();
const r = resolveBrowserConfig(n.browser, n);
const i = Object.keys(r.profiles).filter((t) => {
const n = resolveProfile(r, t);
return n?.driver === "extension" && n.cdpPort === e.port;
});
const a = i.length === 1 ? i[0] : void 0;
s = await startExtensionRelayServer({
port: e.port,
token: o,
allowLegacyAuth: t,
profileName: a
});
} catch (t) {
if (extractErrorCode(t) === "EADDRINUSE") {
log.info(`relay port ${e.port} is already served; standalone daemon not needed`);
a.resolve("port-in-use");
return {
done: a.promise,
port: null,
stop: () => {}
};
}
throw t;
}
log.info(`standalone extension relay listening on 127.0.0.1:${s.port}`);
let c = n();
let l = false;
const finish = (e) => {
if (l) return;
l = true;
clearInterval(u);
s.close().then(() => a.resolve(e), a.reject);
};
const u = setInterval(() => {
if (r && i) {
const e = readInstallationIdentity(r);
if (e !== void 0 && e !== i) {
log.info("relay daemon installation was replaced or removed; exiting");
finish("superseded");
return;
}
}
if (s.bridge.extensionConnected || s.bridge.cdpClientCount > 0) {
c = n();
return;
}
if (n() - c >= RELAY_DAEMON_IDLE_EXIT_MS) {
log.info("relay daemon idle (no extension, no CDP clients); exiting");
finish("idle");
}
}, IDLE_POLL_MS);
u.unref?.();
return {
done: a.promise,
port: s.port,
stop: () => finish("stopped")
};
}
//#endregion
//#region extensions/browser/relay-daemon-entry.ts
/**
* Standalone extension relay daemon. Hosts the loopback relay the OpenClaw
* Chrome extension dials, with no Gateway required — CDP clients (mcporter,
* Playwright, chrome-devtools-mcp) attach through the same relay port. Spawned
* on demand by the native messaging host, or run manually.
*/
const DEFAULT_RELAY_PORT = 18799;
/**
* The standalone daemon is v2-only by default. Honor an explicit
* `browser.extensionRelay.allowLegacyAuth=true` opt-in, but never fall back to
* legacy on a read/parse failure — fail closed to the stricter mode. Read the
* raw config value (not the resolved `?? true` default) so an unset key stays
* v2-only rather than inheriting the gateway's permissive default.
*/
async function resolveAllowLegacyAuth() {
try {
return (await readBrowserHostConfig()).browser?.extensionRelay?.allowLegacyAuth === true;
} catch {
return false;
}
}
function resolvePortArgument(e) {
const t = e.indexOf("--port");
const n = t >= 0 ? e[t + 1] : void 0;
if (n === void 0) return DEFAULT_RELAY_PORT;
const r = Number(n);
if (!Number.isSafeInteger(r) || r < 1 || r > 65535) throw new Error(`invalid --port value: ${n}`);
return r;
}
async function main() {
const e = await runExtensionRelayDaemon({
port: resolvePortArgument(process.argv.slice(2)),
allowLegacyAuth: await resolveAllowLegacyAuth(),
installationPath: fileURLToPath(import.meta.url)
});
const stop = () => e.stop();
process.once("SIGINT", stop);
process.once("SIGTERM", stop);
const t = await e.done;
process.exitCode = t === "no-credential" ? 1 : 0;
}
main().catch((e) => {
process.stderr.write(`openclaw relay daemon failed: ${String(e)}\n`);
process.exitCode = 1;
});
//#endregion
export {};