Skip to content

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

Web app relay link: pair through MausBot Relay and reach the full web server of a serve --relay computer

Bugfixer 24620bf6ad7ba
diff --git a/companion/test/e2e/rig.ts b/companion/test/e2e/rig.ts
index 015b8a0cb7..fa4c3807d9 100644
--- a/companion/test/e2e/rig.ts
+++ b/companion/test/e2e/rig.ts
@@ -13,6 +13,7 @@ import { admission, b64u, credentialHash, ed25519RawPublicKey, fromB64u, keyId,
import { TRANSPORT_DIRECT, TRANSPORT_RELAY } from "../../src/e2e/noise.ts";
import { dial } from "../../src/e2e/phone.ts";
import type { E2ESession } from "../../src/e2e/session.ts";
+import { waitFor } from "./wait.ts";
import { startFakeHarness, type FakeHarness } from "./fake-harness.ts";
const ENTRY = fileURLToPath(new URL("../../src/index.ts", import.meta.url));
@@ -31,15 +32,7 @@ export async function freePorts(count: number): Promise<number[]> {
export const freePort = async () => (await freePorts(1))[0];
-export const waitFor = async <T>(check: () => Promise<T | null | undefined | false> | T | null | undefined | false, ms = 5_000): Promise<T> => {
- const deadline = Date.now() + ms;
- for (;;) {
- const value = await check();
- if (value) return value;
- if (Date.now() > deadline) throw new Error("timed out waiting");
- await new Promise((resolve) => setTimeout(resolve, 25));
- }
-};
+export { waitFor };
export interface RelayProcess {
url: string;
diff --git a/companion/test/e2e/wait.ts b/companion/test/e2e/wait.ts
new file mode 100644
index 0000000000..9a76710264
--- /dev/null
+++ b/companion/test/e2e/wait.ts
@@ -0,0 +1,10 @@
+/** Polls `check` every 25 ms until it gives a truthy value, or throws after `ms`. */
+export const waitFor = async <T>(check: () => Promise<T | null | undefined | false> | T | null | undefined | false, ms = 5_000): Promise<T> => {
+ const deadline = Date.now() + ms;
+ for (;;) {
+ const value = await check();
+ if (value) return value;
+ if (Date.now() > deadline) throw new Error("timed out waiting");
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+};
diff --git a/server/phone-relay.e2e.test.ts b/server/phone-relay.e2e.test.ts
index e96f7398fa..d26c3d9a83 100644
--- a/server/phone-relay.e2e.test.ts
+++ b/server/phone-relay.e2e.test.ts
@@ -1,89 +1,37 @@
// The real server with OMB_PHONE_RELAY=1, a fake control plane and the fake relay, driven by the reference phone: the
// pairing code the owner makes on the server is redeemed through the relay, and the phone is then a session like any.
-import { spawn, type ChildProcess } from "node:child_process";
-import { generateKeyPairSync, randomBytes } from "node:crypto";
-import { mkdirSync, mkdtempSync, openSync, closeSync, readFileSync, rmSync, writeFileSync } from "node:fs";
-import { createServer, type Server } from "node:http";
-import type { AddressInfo } from "node:net";
+import { readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it, onTestFinished } from "vitest";
-import { verificationServerArgs, verificationServerEnvironment } from "../scripts/control-omb.ts";
-import { admission, b64u, credentialHash, ed25519RawPublicKey, fromB64u, keyId, mintRelayToken, psk } from "../companion/src/e2e/credentials.ts";
+import { admission, b64u, credentialHash, fromB64u, keyId, psk } from "../companion/src/e2e/credentials.ts";
import { TRANSPORT_RELAY } from "../companion/src/e2e/noise.ts";
import { dial } from "../companion/src/e2e/phone.ts";
-import { startFakeRelay, type FakeRelay } from "../companion/test/e2e/fake-relay.ts";
+import type { FakeRelay } from "../companion/test/e2e/fake-relay.ts";
import { http, json, waitFor } from "../companion/test/e2e/rig.ts";
-import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
-import { freePortBlock } from "./testing/ports.ts";
-
-const signingKey = generateKeyPairSync("ed25519").privateKey;
-const hostId = randomBytes(16);
-const credential = `omb_install_${randomBytes(16).toString("base64url")}.${randomBytes(32).toString("base64url")}`;
-const tokenRequests: unknown[] = [];
+import { startPhoneRelayRig, type PhoneRelayRig } from "./testing/phone-relay-rig.ts";
+let rig: PhoneRelayRig;
let relay: FakeRelay;
-let controlPlane: Server;
-let child: ChildProcess;
-let dataDir: string;
+let hostId: Buffer;
+let credential: string;
+let tokenRequests: unknown[];
let logPath: string;
let base: string;
-const others: Array<{ child: ChildProcess; dataDir: string }> = [];
const dockerSocket = join(tmpdir(), `omb-relay-e2e-docker-${process.pid}.sock`);
-
-/** A real server in a new data dir, signed in for the relay as `login --relay` leaves it: a credential, no tunnel address. */
-async function boot(extra: Record<string, string> = {}) {
- const port = await freePortBlock([0, 1]);
- const dir = mkdtempSync(join(tmpdir(), "omb-phone-relay-e2e-"));
- mkdirSync(join(dir, "tmp"), { recursive: true });
- writeFileSync(join(dir, "tunnel-account.json"), JSON.stringify({ companionInstallationCredential: credential }), { mode: 0o600 });
- const env = {
- ...verificationServerEnvironment(process.env, dir, port),
- OMB_PHONE_RELAY: "1",
- OMB_PHONE_RELAY_URL: relay.url,
- OMB_CONTROL_PLANE_URL: `http://127.0.0.1:${(controlPlane.address() as AddressInfo).port}`,
- ...extra,
- };
- const log = join(dir, "server.log");
- const fd = openSync(log, "a", 0o600);
- const started = spawn(process.execPath, verificationServerArgs(env), { env, stdio: ["ignore", fd, fd] });
- closeSync(fd);
- const url = `http://127.0.0.1:${port}`;
- await waitFor(async () => (await fetch(`${url}/api/health`).then((r) => r.json(), () => null) as { app?: string } | null)?.app === "openmausbot", 30_000);
- return { child: started, dataDir: dir, logPath: log, base: url };
-}
+const boot = (extra?: Record<string, string>) => rig.boot(extra);
beforeAll(async () => {
- relay = await startFakeRelay({ keys: new Map([["k1", ed25519RawPublicKey(signingKey)]]) });
- controlPlane = createServer(async (req, res) => {
- let raw = "";
- for await (const chunk of req) raw += chunk;
- if (req.method !== "POST" || req.url !== "/v1/installations/self/relay-token" || req.headers.authorization !== `Bearer ${credential}`) {
- return void res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "unauthorized" }));
- }
- tokenRequests.push(JSON.parse(raw));
- const iat = Math.floor(Date.now() / 1000);
- const token = mintRelayToken({ v: 1, kid: "k1", hid: b64u(hostId), iid: "test-install", iat, exp: iat + 43_200 }, signingKey);
- res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({
- token, hostId: b64u(hostId), nodes: ["relay1.openmausbot.com"], expiresAt: (iat + 43_200) * 1000, refreshAfter: (iat + 3_600) * 1000,
- }));
- });
- await new Promise<void>((resolve) => controlPlane.listen(0, "127.0.0.1", resolve));
+ rig = await startPhoneRelayRig();
+ ({ relay, hostId, credential, tokenRequests } = rig);
// As Docker runs it: its Caddy reaches the server over this socket, which is no tunnel.
- ({ child, dataDir, logPath, base } = await boot({ OMB_TUNNEL_SOCKET: dockerSocket }));
+ ({ logPath, base } = await boot({ OMB_TUNNEL_SOCKET: dockerSocket }));
}, 60_000);
afterAll(async () => {
- await waitForExit(child, { signal: "SIGTERM", graceMs: 15_000 });
+ await rig?.close();
rmSync(dockerSocket, { force: true });
- for (const other of others) {
- await waitForExit(other.child, { signal: "SIGTERM", graceMs: 15_000 });
- await removeTempDir(other.dataDir);
- }
- await relay?.close();
- await new Promise((resolve) => controlPlane?.close(resolve));
- if (dataDir) await removeTempDir(dataDir);
});
const owner = async (path: string, init: RequestInit = {}) => {
@@ -138,10 +86,8 @@ describe("serve --relay", () => {
const asked = tokenRequests.length;
const socket = join(tmpdir(), `omb-relay-e2e-${process.pid}-${Date.now()}.sock`);
const tunnel = await boot({ OMB_SERVES_TUNNEL: "1", OMB_TUNNEL_SOCKET: socket });
- others.push(tunnel);
onTestFinished(() => rmSync(socket, { force: true }));
const fleet = await boot({ OMB_INSTALLATION_CREDENTIAL: credential });
- others.push(fleet);
for (const server of [tunnel, fleet]) {
const status = await (await fetch(`${server.base}/api/auth/pairing`)).json() as { relay?: { grant: string; reason?: string } };
expect(status.relay).toMatchObject({ grant: "tunnel", reason: expect.any(String) });
diff --git a/server/testing/phone-relay-rig.ts b/server/testing/phone-relay-rig.ts
new file mode 100644
index 0000000000..2688944bf6
--- /dev/null
+++ b/server/testing/phone-relay-rig.ts
@@ -0,0 +1,92 @@
+// The real server with OMB_PHONE_RELAY=1 for tests, beside a fake control plane that grants relay tokens and the fake
+// relay those tokens open.
+import { spawn, type ChildProcess } from "node:child_process";
+import { generateKeyPairSync, randomBytes } from "node:crypto";
+import { mkdirSync, mkdtempSync, openSync, closeSync, writeFileSync } from "node:fs";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { verificationServerArgs, verificationServerEnvironment } from "../../scripts/control-omb.ts";
+import { b64u, ed25519RawPublicKey, mintRelayToken } from "../../companion/src/e2e/credentials.ts";
+import { startFakeRelay, type FakeRelay } from "../../companion/test/e2e/fake-relay.ts";
+import { waitFor } from "../../companion/test/e2e/wait.ts";
+import { removeTempDir, waitForExit } from "./cleanup.ts";
+import { freePortBlock } from "./ports.ts";
+
+export interface RelayServer {
+ child: ChildProcess;
+ dataDir: string;
+ logPath: string;
+ base: string;
+}
+
+export interface PhoneRelayRig {
+ relay: FakeRelay;
+ hostId: Buffer;
+ /** The installation credential every booted server is signed in with. */
+ credential: string;
+ /** Each relay-token request body, in order. */
+ tokenRequests: unknown[];
+ /** A real server in a new data dir, signed in for the relay as `login --relay` leaves it: a credential, no tunnel address. */
+ boot(extra?: Record<string, string>): Promise<RelayServer>;
+ /** Stops every booted server, then the relay and the control plane. */
+ close(): Promise<void>;
+}
+
+export async function startPhoneRelayRig(): Promise<PhoneRelayRig> {
+ const signingKey = generateKeyPairSync("ed25519").privateKey;
+ const hostId = randomBytes(16);
+ const credential = `omb_install_${randomBytes(16).toString("base64url")}.${randomBytes(32).toString("base64url")}`;
+ const tokenRequests: unknown[] = [];
+ const servers: RelayServer[] = [];
+ const relay = await startFakeRelay({ keys: new Map([["k1", ed25519RawPublicKey(signingKey)]]) });
+ const controlPlane = createServer(async (req, res) => {
+ let raw = "";
+ for await (const chunk of req) raw += chunk;
+ if (req.method !== "POST" || req.url !== "/v1/installations/self/relay-token" || req.headers.authorization !== `Bearer ${credential}`) {
+ return void res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "unauthorized" }));
+ }
+ tokenRequests.push(JSON.parse(raw));
+ const iat = Math.floor(Date.now() / 1000);
+ const token = mintRelayToken({ v: 1, kid: "k1", hid: b64u(hostId), iid: "test-install", iat, exp: iat + 43_200 }, signingKey);
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({
+ token, hostId: b64u(hostId), nodes: ["relay1.openmausbot.com"], expiresAt: (iat + 43_200) * 1000, refreshAfter: (iat + 3_600) * 1000,
+ }));
+ });
+ await new Promise<void>((resolve) => controlPlane.listen(0, "127.0.0.1", resolve));
+
+ return {
+ relay, hostId, credential, tokenRequests,
+ async boot(extra = {}) {
+ const port = await freePortBlock([0, 1]);
+ const dir = mkdtempSync(join(tmpdir(), "omb-phone-relay-e2e-"));
+ mkdirSync(join(dir, "tmp"), { recursive: true });
+ writeFileSync(join(dir, "tunnel-account.json"), JSON.stringify({ companionInstallationCredential: credential }), { mode: 0o600 });
+ const env = {
+ ...verificationServerEnvironment(process.env, dir, port),
+ OMB_PHONE_RELAY: "1",
+ OMB_PHONE_RELAY_URL: relay.url,
+ OMB_CONTROL_PLANE_URL: `http://127.0.0.1:${(controlPlane.address() as AddressInfo).port}`,
+ ...extra,
+ };
+ const log = join(dir, "server.log");
+ const fd = openSync(log, "a", 0o600);
+ const child = spawn(process.execPath, verificationServerArgs(env), { env, stdio: ["ignore", fd, fd] });
+ closeSync(fd);
+ const server = { child, dataDir: dir, logPath: log, base: `http://127.0.0.1:${port}` };
+ servers.push(server);
+ await waitFor(async () => (await fetch(`${server.base}/api/health`).then((r) => r.json(), () => null) as { app?: string } | null)?.app === "openmausbot", 30_000);
+ return server;
+ },
+ async close() {
+ for (const server of servers) {
+ await waitForExit(server.child, { signal: "SIGTERM", graceMs: 15_000 });
+ await removeTempDir(server.dataDir);
+ }
+ await relay.close();
+ await new Promise((resolve) => controlPlane.close(resolve));
+ },
+ };
+}
diff --git a/src/lib/e2e/relay-link.e2e.test.ts b/src/lib/e2e/relay-link.e2e.test.ts
new file mode 100644
index 0000000000..72fe389433
--- /dev/null
+++ b/src/lib/e2e/relay-link.e2e.test.ts
@@ -0,0 +1,65 @@
+// The browser's relay client against the real `serve --relay` server: it pairs with the server's own pairing code, then
+// reaches the server's whole request handler, live events included, as a session of its own.
+import { afterAll, beforeAll, describe, expect, it, onTestFinished } from "vitest";
+
+import { waitFor } from "../../../companion/test/e2e/wait.ts";
+import { startPhoneRelayRig, type PhoneRelayRig } from "../../../server/testing/phone-relay-rig.ts";
+import { fromB64u } from "./bytes.ts";
+import { pairThroughRelay, RelayLink, relayRoute } from "./relay-link.ts";
+
+let rig: PhoneRelayRig;
+let base: string;
+
+beforeAll(async () => {
+ rig = await startPhoneRelayRig();
+ ({ base } = await rig.boot());
+}, 60_000);
+
+afterAll(async () => {
+ await rig?.close();
+});
+
+const owner = async (path: string, init: RequestInit = {}) => {
+ const res = await fetch(`${base}${path}`, { ...init, headers: { "content-type": "application/json", ...init.headers } });
+ return { status: res.status, body: (await res.json()) as Record<string, any> };
+};
+
+const session = (link: RelayLink) => link.fetch("/api/auth/session").then((res) => (res.ok ? (res.json() as Promise<{ id: string }>) : null), () => null);
+
+describe("a web page on MausBot Relay", () => {
+ it("pairs through the relay, then reaches the full web server and its live events, and dials again after a drop", async () => {
+ await waitFor(async () => (await owner("/api/auth/pairing")).body.relay?.relay === "connected", 15_000);
+ const minted = await owner("/api/auth/pairing", { method: "POST", body: JSON.stringify({ scopes: ["client"], label: "Web" }) });
+ const descriptor = JSON.parse(new TextDecoder().decode(fromB64u(new URL(minted.body.inviteUrl).searchParams.get("e2e")!)!));
+ const nodeUrl = () => `${rig.relay.url}/v1/phone`;
+ const route = relayRoute(descriptor, { nodeUrl });
+ expect(route).not.toBeNull();
+
+ const paired = await waitFor(() => pairThroughRelay(route!, minted.body.credential, "Phone browser").catch(() => null), 8_000);
+ expect(paired.descriptor).toEqual(descriptor);
+ expect(paired.token).toMatch(/^omb_sess_/);
+ const link = new RelayLink(relayRoute(paired.descriptor, { nodeUrl })!, paired.token);
+ onTestFinished(() => link.close());
+
+ const who = await waitFor(() => session(link), 8_000);
+ expect(who).toMatchObject({ kind: "session", scopes: ["client"] });
+ // The server's own handler answers, its scope rule included: no companion route list in between.
+ expect((await link.fetch("/api/bots")).status).toBe(200);
+ expect((await link.fetch("/api/auth/pairing", { method: "POST", body: "{}", headers: { "content-type": "application/json" } })).status).toBe(403);
+
+ const stop = new AbortController();
+ const events = await link.fetch("/api/events", { signal: stop.signal });
+ expect(events.status).toBe(200);
+ expect(events.headers.get("content-type")).toMatch(/^text\/event-stream/);
+ expect((await events.body!.getReader().read()).done).toBe(false);
+ stop.abort();
+
+ // The relay drops the session: the next request dials a new one.
+ rig.relay.forgeClose(1011);
+ expect(await waitFor(() => session(link), 8_000)).toMatchObject({ kind: "session", id: who.id });
+
+ link.close();
+ await expect(link.fetch("/api/auth/session")).rejects.toThrow("relay link closed");
+ expect((await owner(`/api/auth/sessions/${who.id}`, { method: "DELETE" })).status).toBe(200);
+ }, 60_000);
+});
diff --git a/src/lib/e2e/relay-link.test.ts b/src/lib/e2e/relay-link.test.ts
new file mode 100644
index 0000000000..85bbbeac0a
--- /dev/null
+++ b/src/lib/e2e/relay-link.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+
+import { b64u } from "./bytes.ts";
+import { relayRoute } from "./relay-link.ts";
+
+const k = b64u(new Uint8Array(65).fill(4));
+const h = b64u(new Uint8Array(16).fill(1));
+
+describe("relayRoute", () => {
+ it("takes a descriptor's relay half: the key, the host and each node's phone URL in order", () => {
+ const route = relayRoute({ v: 1, k, h, r: ["relay2.openmausbot.com", "relay1.openmausbot.com"] });
+ expect(route?.remoteStatic).toEqual(new Uint8Array(65).fill(4));
+ expect(route?.hostId).toEqual(new Uint8Array(16).fill(1));
+ expect(route?.urls).toEqual(["wss://relay2.openmausbot.com/v1/phone", "wss://relay1.openmausbot.com/v1/phone"]);
+ expect(relayRoute({ v: 1, k, h, r: ["relay1.openmausbot.com"] }, { nodeUrl: (node) => `ws://127.0.0.1:9/${node}` })?.urls)
+ .toEqual(["ws://127.0.0.1:9/relay1.openmausbot.com"]);
+ });
+
+ it("is null for a descriptor with no relay, and for any malformed part", () => {
+ for (const bad of [
+ null, "text", [], { v: 1, k }, { v: 2, k, h, r: ["relay1.openmausbot.com"] },
+ { v: 1, k: b64u(new Uint8Array(64)), h, r: ["relay1.openmausbot.com"] },
+ { v: 1, k, h: b64u(new Uint8Array(15)), r: ["relay1.openmausbot.com"] },
+ { v: 1, k, h, r: [] },
+ { v: 1, k, h, r: ["relay1.openmausbot.com.evil.example"] },
+ { v: 1, k, h, r: ["evil.example"] },
+ { v: 1, k, h, r: Array.from({ length: 5 }, (_, i) => `relay${i + 1}.openmausbot.com`) },
+ ]) expect(relayRoute(bad), JSON.stringify(bad)).toBeNull();
+ });
+});
diff --git a/src/lib/e2e/relay-link.ts b/src/lib/e2e/relay-link.ts
new file mode 100644
index 0000000000..50d91ae123
--- /dev/null
+++ b/src/lib/e2e/relay-link.ts
@@ -0,0 +1,124 @@
+// A web page's way to a `serve --relay` computer from anywhere: an end-to-end encrypted session through MausBot Relay
+// that carries plain HTTP to the server's own request handler (server/phone-relay.ts), as a session of its own.
+import { fromB64u, type Bytes } from "./bytes.ts";
+import { admission, credentialHash, keyId, psk } from "./credentials.ts";
+import { streamFetch, type StreamRequest } from "./http.ts";
+import { dialRelay, type PhoneSession } from "./session.ts";
+
+/** As companion/src/e2e/descriptor.ts. */
+const RELAY_HOST = /^relay[1-9][0-9]?\.openmausbot\.com$/;
+const MAX_RELAY_NODES = 4;
+const PUBLIC_KEY_BYTES = 65;
+const HOST_ID_BYTES = 16;
+const APP = "openmausbot-web/1";
+
+export interface RelayRoute {
+ remoteStatic: Bytes;
+ hostId: Bytes;
+ /** The relay nodes' phone URLs, best first. */
+ urls: string[];
+}
+
+export interface RelayRouteOptions {
+ /** Test-only: dial a node through this URL instead of `wss://<node>/v1/phone`. */
+ nodeUrl?: (node: string) => string;
+}
+
+/** The relay half of an `e2e` descriptor (the pairing link's, decoded, or the pair reply's), or null when it names no
+ * relay or any part is malformed. The key's point is checked by the handshake itself. */
+export function relayRoute(descriptor: unknown, options: RelayRouteOptions = {}): RelayRoute | null {
+ if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor)) return null;
+ const { v, k, h, r } = descriptor as Record<string, unknown>;
+ if (v !== 1 || typeof k !== "string" || typeof h !== "string" || !Array.isArray(r)) return null;
+ const remoteStatic = fromB64u(k);
+ const hostId = fromB64u(h);
+ if (remoteStatic?.length !== PUBLIC_KEY_BYTES || hostId?.length !== HOST_ID_BYTES) return null;
+ if (r.length < 1 || r.length > MAX_RELAY_NODES || !r.every((node) => typeof node === "string" && RELAY_HOST.test(node))) return null;
+ const nodeUrl = options.nodeUrl ?? ((node: string) => `wss://${node}/v1/phone`);
+ return { remoteStatic, hostId, urls: r.map(nodeUrl) };
+}
+
+/** A session keyed by `token`: the pairing credential while pairing, the device's own session token after. */
+async function open(route: RelayRoute, token: string): Promise<PhoneSession> {
+ const hash = await credentialHash(token);
+ return dialRelay({
+ urls: route.urls, hostId: route.hostId, remoteStatic: route.remoteStatic, app: APP,
+ psk: await psk(hash, await keyId(route.remoteStatic)), adm: await admission(hash, route.hostId),
+ });
+}
+
+export class RelayPairError extends Error {
+ readonly status: number;
+ constructor(status: number, message: string) {
+ super(message);
+ this.name = "RelayPairError";
+ this.status = status;
+ }
+}
+
+export interface RelayPairing {
+ /** The device's own session token: it keys the relay session and signs every request. */
+ token: string;
+ serverName: string;
+ /** The computer's descriptor for this device, to keep instead of the pairing link's. */
+ descriptor: unknown;
+}
+
+/** Redeems a pairing link's credential through the relay, as the MausBot phone app does. */
+export async function pairThroughRelay(route: RelayRoute, credential: string, deviceName: string): Promise<RelayPairing> {
+ const session = await open(route, credential);
+ try {
+ const reply = await streamFetch(() => session.open(), {
+ method: "POST", path: "/api/pair", headers: { "content-type": "application/json" }, body: JSON.stringify({ credential, deviceName }),
+ });
+ const body = (await reply.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!reply.ok || typeof body?.token !== "string") {
+ throw new RelayPairError(reply.status, typeof body?.error === "string" ? body.error : `pairing failed (${reply.status})`);
+ }
+ return { token: body.token, serverName: typeof body.serverName === "string" ? body.serverName : "", descriptor: body.e2e };
+ } finally {
+ session.shutdown();
+ }
+}
+
+export type RelayRequest = Omit<StreamRequest, "path">;
+
+/** One paired device's requests, each on its own stream of one shared session. The session is dialed on the first
+ * request and again on the first request after it closes; requests made while it dials share that dial. */
+export class RelayLink {
+ readonly #route: RelayRoute;
+ readonly #token: string;
+ #session: Promise<PhoneSession> | null = null;
+ #closed = false;
+
+ constructor(route: RelayRoute, token: string) {
+ this.#route = route;
+ this.#token = token;
+ }
+
+ async fetch(path: string, request: RelayRequest = {}): Promise<Response> {
+ const session = await this.#live();
+ const headers = new Headers(request.headers);
+ headers.set("authorization", `Bearer ${this.#token}`);
+ return streamFetch(() => session.open(), { ...request, path, headers });
+ }
+
+ /** Ends the session; later requests are refused. */
+ close(): void {
+ this.#closed = true;
+ void this.#session?.then((session) => session.shutdown(), () => {});
+ this.#session = null;
+ }
+
+ #live(): Promise<PhoneSession> {
+ if (this.#closed) return Promise.reject(new Error("relay link closed"));
+ if (this.#session) return this.#session;
+ const dialing = open(this.#route, this.#token);
+ const forget = () => {
+ if (this.#session === dialing) this.#session = null;
+ };
+ this.#session = dialing;
+ dialing.then((session) => void session.closed.then(forget), forget);
+ return dialing;
+ }
+}