Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

relay: let listed browser origins open /v1/phone

Bugfixer 2185a5e8c7712
diff --git a/docs/phone-relay-server.md b/docs/phone-relay-server.md
index a92f0c690a..d67f41ca39 100644
--- a/docs/phone-relay-server.md
+++ b/docs/phone-relay-server.md
@@ -185,6 +185,16 @@ from it), and cannot mint a relay token (the control plane holds the signing
key). A phone treats only the authenticated GoAway(3) inside the session as
"removed", so a forged 4001 cannot make it forget the server.
+**Browser pages.** The relay refuses every WebSocket upgrade that carries an
+`Origin` header, so a web page cannot dial it, unless the relay's operator
+lists that page's exact `https://` origin in `RELAY_PHONE_ORIGINS`
+(comma-separated, at most 8, no wildcards, paths or `http://`; a bad value
+stops the relay at start). A listed origin may open only `/v1/phone`, never
+`/v1/host` or `/v1/host/data`, and it gets no further than any other phone:
+the page still needs the pairing credential and the end-to-end handshake.
+Unset, which is the default, browsers stay refused. It is for the phone web
+app over the relay, which is not built yet.
+
**Pairing proves the owner.** The QR carries a 256-bit, single-use pairing
credential that only the owner can mint: `openmausbot pair --phone` on the
machine (the owner, or on a shared server the per-launch owner token `serve`
diff --git a/relay/src/config.ts b/relay/src/config.ts
index 60f00b79ec..06d901c682 100644
--- a/relay/src/config.ts
+++ b/relay/src/config.ts
@@ -81,11 +81,29 @@ export interface RelayConfig {
tokenKeys: ReadonlyMap<string, KeyObject>;
/** /metrics answers only with this bearer; without one /metrics is off. */
metricsToken: string | undefined;
+ /** Browser pages allowed to open /v1/phone, as exact `https://` origins. Empty: every upgrade with an Origin is refused. */
+ phoneOrigins: ReadonlySet<string>;
limits: Limits;
}
const NODE = /^relay[1-9][0-9]?$/;
const MIN_METRICS_TOKEN = 32;
+const MAX_PHONE_ORIGINS = 8;
+const PHONE_ORIGINS_RULE = `RELAY_PHONE_ORIGINS must list exact https:// origins, comma-separated, at most ${MAX_PHONE_ORIGINS}`;
+
+const HOSTNAME = /^[a-z0-9-]+(\.[a-z0-9-]+)*$/;
+
+/** Exactly what a browser sends as Origin: `https://host[:port]`, lower case, no default port, path or credentials. No wildcards. */
+function isExactHttpsOrigin(value: string): boolean {
+ const url = URL.parse(value);
+ return url !== null && url.protocol === "https:" && url.origin === value && HOSTNAME.test(url.hostname);
+}
+
+function parsePhoneOrigins(value: string | undefined): ReadonlySet<string> {
+ const origins = (value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
+ if (origins.length > MAX_PHONE_ORIGINS || !origins.every(isExactHttpsOrigin)) throw new Error(PHONE_ORIGINS_RULE);
+ return new Set(origins);
+}
/** Reads the deployment facts from the environment. Throws a message that never repeats a value it read. */
export function loadConfig(env: NodeJS.ProcessEnv): RelayConfig {
@@ -99,5 +117,6 @@ export function loadConfig(env: NodeJS.ProcessEnv): RelayConfig {
}
const port = Number(env.RELAY_PORT ?? 8080);
if (!Number.isInteger(port) || port < 0 || port > 65_535) throw new Error("RELAY_PORT must be a port number");
- return { node, host: env.RELAY_HOST ?? "127.0.0.1", port, tokenKeys, metricsToken, limits: { ...DEFAULT_LIMITS } };
+ const phoneOrigins = parsePhoneOrigins(env.RELAY_PHONE_ORIGINS);
+ return { node, host: env.RELAY_HOST ?? "127.0.0.1", port, tokenKeys, metricsToken, phoneOrigins, limits: { ...DEFAULT_LIMITS } };
}
diff --git a/relay/src/server.ts b/relay/src/server.ts
index 6e03769007..e69d121bf4 100644
--- a/relay/src/server.ts
+++ b/relay/src/server.ts
@@ -125,7 +125,8 @@ export async function startRelay(config: RelayConfig, options: RelayOptions = {}
metrics.inc("relay_refused_total", "path");
return refuse(socket, 404, "Not Found");
}
- if (req.headers.origin !== undefined) {
+ const origin = req.headers.origin;
+ if (origin !== undefined && !(route === "phone" && config.phoneOrigins.has(origin))) {
metrics.inc("relay_refused_total", "origin");
return refuse(socket, 403, "Forbidden");
}
diff --git a/relay/test/helpers.ts b/relay/test/helpers.ts
index 3ae6ad07ff..26f1921908 100644
--- a/relay/test/helpers.ts
+++ b/relay/test/helpers.ts
@@ -158,7 +158,7 @@ export interface TestRelay {
}
/** A relay in this process on a free port, with `limits` overriding the spec values. */
-export async function startTestRelay(limits: Partial<Limits> = {}, options: { wallSeconds?: () => number; key?: TestKey } = {}): Promise<TestRelay> {
+export async function startTestRelay(limits: Partial<Limits> = {}, options: { wallSeconds?: () => number; key?: TestKey; phoneOrigins?: string[] } = {}): Promise<TestRelay> {
const key = options.key ?? testKey();
const logs: LogEvent[] = [];
const config: RelayConfig = {
@@ -167,6 +167,7 @@ export async function startTestRelay(limits: Partial<Limits> = {}, options: { wa
port: 0,
tokenKeys: parseTokenKeys(keysJson(key)),
metricsToken: "m".repeat(40),
+ phoneOrigins: new Set(options.phoneOrigins),
limits: { ...DEFAULT_LIMITS, ...limits },
};
const relay = await startRelay(config, { log: (event) => logs.push(event), wallSeconds: options.wallSeconds });
diff --git a/relay/test/origins.test.ts b/relay/test/origins.test.ts
new file mode 100644
index 0000000000..76b36edad0
--- /dev/null
+++ b/relay/test/origins.test.ts
@@ -0,0 +1,78 @@
+import assert from "node:assert/strict";
+import { randomBytes } from "node:crypto";
+import { after, before, describe, test } from "node:test";
+import { loadConfig } from "../src/config.ts";
+import { Client, fakeHost, keysJson, phoneHello, startTestRelay, testKey, type TestRelay } from "./helpers.ts";
+
+const APP = "https://app.example.com";
+const base = { RELAY_NODE: "relay1", RELAY_TOKEN_KEYS: keysJson(testKey()) };
+
+describe("RELAY_PHONE_ORIGINS", () => {
+ test("unset or empty lets no browser page in", () => {
+ assert.deepEqual([...loadConfig(base).phoneOrigins], []);
+ assert.deepEqual([...loadConfig({ ...base, RELAY_PHONE_ORIGINS: " " }).phoneOrigins], []);
+ });
+
+ test("lists exact https:// origins, comma-separated", () => {
+ const { phoneOrigins } = loadConfig({ ...base, RELAY_PHONE_ORIGINS: ` ${APP} , https://web.example.org:8443,` });
+ assert.deepEqual([...phoneOrigins], [APP, "https://web.example.org:8443"]);
+ });
+
+ test("refuses anything that is not an exact https:// origin, and never repeats it", () => {
+ const bad = [
+ "http://app.example.com",
+ "https://app.example.com/",
+ "https://app.example.com/pair",
+ "https://app.example.com?x=1",
+ "https://app.example.com#x",
+ "https://[email protected]",
+ "https://App.example.com",
+ "https://app.example.com:443",
+ "https://*.example.com",
+ "app.example.com",
+ "null",
+ `${APP},ftp://files.example.com`,
+ ];
+ for (const value of bad) {
+ assert.throws(
+ () => loadConfig({ ...base, RELAY_PHONE_ORIGINS: value }),
+ (error: Error) => error.message.startsWith("RELAY_PHONE_ORIGINS") && !error.message.includes(value),
+ value,
+ );
+ }
+ });
+
+ test("at most 8", () => {
+ const nine = Array.from({ length: 9 }, (_, i) => `https://app${i}.example.com`).join(",");
+ assert.throws(() => loadConfig({ ...base, RELAY_PHONE_ORIGINS: nine }), /RELAY_PHONE_ORIGINS/);
+ assert.equal(loadConfig({ ...base, RELAY_PHONE_ORIGINS: nine.split(",").slice(0, 8).join(",") }).phoneOrigins.size, 8);
+ });
+});
+
+describe("a relay with RELAY_PHONE_ORIGINS", () => {
+ let relay: TestRelay;
+ before(async () => {
+ relay = await startTestRelay({}, { phoneOrigins: [APP] });
+ });
+ after(() => relay.stop());
+
+ test("a listed origin may open /v1/phone and nothing else", async () => {
+ const origin = (value: string) => ({ headers: { origin: value } });
+ assert.equal(await Client.refusal(relay.url, "/v1/phone", origin(APP)), 101);
+ assert.equal(await Client.refusal(relay.url, "/v1/phone"), 101);
+ assert.equal(await Client.refusal(relay.url, "/v1/phone", origin("https://other.example.com")), 403);
+ assert.equal(await Client.refusal(relay.url, "/v1/phone", origin("http://app.example.com")), 403);
+ assert.equal(await Client.refusal(relay.url, "/v1/phone", origin("null")), 403);
+ assert.equal(await Client.refusal(relay.url, "/v1/host", origin(APP)), 403);
+ assert.equal(await Client.refusal(relay.url, "/v1/host/data", origin(APP)), 403);
+ });
+
+ test("a phone page from a listed origin reaches its host", async () => {
+ const adm = randomBytes(32);
+ const host = await fakeHost(relay.url, relay.key, [adm]);
+ const phone = await phoneHello(relay.url, host.hidText, adm, { headers: { origin: APP } });
+ assert.equal((await host.control.json()).t, "open");
+ phone.ws.terminate();
+ host.control.ws.close();
+ });
+});