Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
relay: control, data and phone sockets, splice with backpressure, server and entry point
milind-soniff3727ba8216
diff --git a/relay/pnpm-lock.yaml b/relay/pnpm-lock.yamlnew file mode 100644index 0000000000..913b71d1e3--- /dev/null+++ b/relay/pnpm-lock.yaml@@ -0,0 +1,67 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ dependencies:+ ws:+ specifier: 8.22.0+ version: 8.22.0+ devDependencies:+ '@types/node':+ specifier: 24.19.2+ version: 24.19.2+ '@types/ws':+ specifier: 8.18.2+ version: 8.18.2+ typescript:+ specifier: 5.9.3+ version: 5.9.3++packages:++ '@types/[email protected]':+ resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==}++ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}+ engines: {node: '>=14.17'}+ hasBin: true++ resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}++ resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==}+ engines: {node: '>=10.0.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: '>=5.0.2'+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true++snapshots:++ '@types/[email protected]':+ dependencies:+ undici-types: 7.24.6++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.19.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}diff --git a/relay/src/context.ts b/relay/src/context.tsnew file mode 100644index 0000000000..e5f86bc39f--- /dev/null+++ b/relay/src/context.ts@@ -0,0 +1,22 @@+import type { KeyObject } from "node:crypto";+import type { Limits } from "./config.ts";+import type { HostBudgets, Hosts } from "./hosts.ts";+import type { Logger } from "./log.ts";+import type { Metrics } from "./metrics.ts";+import type { Heartbeat } from "./socket.ts";++/** What every connection handler shares on one node. */+export interface Context {+ node: string;+ limits: Limits;+ tokenKeys: ReadonlyMap<string, KeyObject>;+ hosts: Hosts;+ budgets: HostBudgets;+ heartbeat: Heartbeat;+ metrics: Metrics;+ log: Logger;+ /** Monotonic milliseconds, for every duration the relay measures. */+ now: () => number;+ /** Wall-clock seconds, only for token `iat`/`exp` and the daily byte budget. */+ wallSeconds: () => number;+}diff --git a/relay/src/hosts.ts b/relay/src/hosts.tsnew file mode 100644index 0000000000..356a60adc3--- /dev/null+++ b/relay/src/hosts.ts@@ -0,0 +1,215 @@+import { timingSafeEqual } from "node:crypto";+import type { WebSocket } from "ws";+import type { Context } from "./context.ts";+import { hid8 } from "./log.ts";+import { afterFirstMessage, closeWith, sendJson, type MessageHandler } from "./socket.ts";+import type { Session } from "./splice.ts";+import { TokenBucket } from "./limits.ts";+import { verifyToken, type TokenResult } from "./token.ts";+import { Close, parseAdmit, parseAuth, parseData, parseObject } from "./wire.ts";++const NO_MATCH = Buffer.alloc(32);++/**+ * One host on this node. It lives while it has a control socket or a session, and goes with the last of them, so no+ * routing state can outlive the sockets it describes.+ */+export class HostEntry {+ readonly hid: Buffer;+ readonly hidText: string;+ readonly hid8: string;+ control: WebSocket | undefined;+ /** SHA256(adm) of every phone the current control socket admits; empty without a control socket. */+ admission: Buffer[] = [];+ readonly sessions = new Map<string, Session>();++ constructor(hid: Buffer, hidText: string) {+ this.hid = hid;+ this.hidText = hidText;+ this.hid8 = hid8(hid);+ }+}++export class Hosts {+ private readonly entries = new Map<string, HostEntry>();+ private readonly slots: number;+ connected = 0;++ constructor(admissionMax: number) {+ this.slots = admissionMax;+ }++ get(hidText: string): HostEntry | undefined {+ return this.entries.get(hidText);+ }++ entry(hid: Buffer, hidText: string): HostEntry {+ let entry = this.entries.get(hidText);+ if (!entry) {+ entry = new HostEntry(hid, hidText);+ this.entries.set(hidText, entry);+ }+ return entry;+ }++ release(entry: HostEntry): void {+ if (!entry.control && entry.sessions.size === 0 && this.entries.get(entry.hidText) === entry) this.entries.delete(entry.hidText);+ }++ /**+ * Whether a connected host admits `admHash`. Every slot is compared in full and in constant time whether or not the+ * host exists, so neither the answer's timing nor the close code tells a phone that a host is online.+ */+ admitted(entry: HostEntry | undefined, admHash: Buffer): boolean {+ const set = entry?.control ? entry.admission : [];+ let found = 0;+ for (let i = 0; i < this.slots; i++) found |= timingSafeEqual(set[i] ?? NO_MATCH, admHash) ? 1 : 0;+ return found === 1;+ }++ get size(): number {+ return this.entries.size;+ }++ *all(): IterableIterator<HostEntry> {+ yield* this.entries.values();+ }+}++interface Budget {+ day: number;+ bytes: number;+}++/** Bytes each host relayed today (UTC). Kept apart from HostEntry so reconnecting does not reset a host's count. */+export class HostBudgets {+ private readonly budgets = new Map<string, Budget>();+ private readonly limit: number;+ private readonly today: () => number;++ constructor(limit: number, wallSeconds: () => number) {+ this.limit = limit;+ this.today = () => Math.floor(wallSeconds() / 86_400);+ }++ /** Adds `bytes` to the host's day and says whether this addition took it over the limit. */+ add(hidText: string, bytes: number): boolean {+ const day = this.today();+ let budget = this.budgets.get(hidText);+ if (!budget || budget.day !== day) {+ budget = { day, bytes: 0 };+ this.budgets.set(hidText, budget);+ }+ const before = budget.bytes;+ budget.bytes += bytes;+ return before <= this.limit && budget.bytes > this.limit;+ }++ over(hidText: string): boolean {+ const budget = this.budgets.get(hidText);+ return budget !== undefined && budget.day === this.today() && budget.bytes > this.limit;+ }++ sweep(): void {+ const day = this.today();+ for (const [hidText, budget] of this.budgets) if (budget.day !== day) this.budgets.delete(hidText);+ }+}++function checkToken(ctx: Context, token: string): TokenResult {+ const result = verifyToken(token, ctx.tokenKeys, ctx.wallSeconds());+ if (!result.ok) ctx.metrics.inc("relay_token_rejected_total", result.reason);+ return result;+}++/** Closes every session of `entry` whose phone the current admission set no longer holds. */+function enforceAdmission(ctx: Context, entry: HostEntry): void {+ for (const session of [...entry.sessions.values()]) {+ if (!ctx.hosts.admitted(entry, session.admHash)) session.end(Close.NotFound);+ }+}++/** `GET /v1/host`: auth, `hello`, the admission set, `open` for each waiting phone, token refresh and expiry. */+export function handleControl(ctx: Context, ws: WebSocket): void {+ afterFirstMessage(ctx, ws, (message) => {+ const token = parseAuth(message);+ if (token === undefined) return void closeWith(ctx, ws, Close.Malformed);+ const verified = checkToken(ctx, token);+ if (!verified.ok) return void closeWith(ctx, ws, Close.TokenInvalid);++ const entry = ctx.hosts.entry(verified.claims.hid, verified.claims.hidText);+ const previous = entry.control;+ entry.control = ws;+ entry.admission = [];+ if (previous) closeWith(ctx, previous, Close.Replaced);+ else ctx.hosts.connected += 1;++ const since = ctx.now();+ const rate = new TokenBucket(ctx.limits.controlBurst, ctx.limits.controlPerSecond / 1000, ctx.now);+ let expires = verified.claims.exp;+ let admitted = false;+ let expiry: NodeJS.Timeout | undefined;+ const armExpiry = () => {+ clearTimeout(expiry);+ expiry = setTimeout(() => {+ if (ctx.wallSeconds() >= expires) closeWith(ctx, ws, Close.TokenInvalid);+ else armExpiry();+ }, Math.max(0, expires * 1000 - ctx.wallSeconds() * 1000));+ };+ armExpiry();+ const admitDeadline = setTimeout(() => {+ if (!admitted) closeWith(ctx, ws, Close.Malformed);+ }, ctx.limits.admitDeadlineMs);++ ctx.heartbeat.track(ws);+ ws.once("close", (code) => {+ clearTimeout(expiry);+ clearTimeout(admitDeadline);+ if (entry.control === ws) {+ entry.control = undefined;+ entry.admission = [];+ ctx.hosts.connected -= 1;+ }+ ctx.hosts.release(entry);+ ctx.log({ ev: "host", hid8: entry.hid8, dur_s: Math.round((ctx.now() - since) / 1000), close: code });+ });+ sendJson(ws, { t: "hello", v: 1, node: ctx.node, sessionsMax: ctx.limits.hostSessionsMax });++ const handler: MessageHandler = (data, isBinary) => {+ ctx.heartbeat.mark(ws);+ if (entry.control !== ws) return;+ if (!rate.take()) return closeWith(ctx, ws, Close.Limited);+ const next = !isBinary && data.length <= ctx.limits.authMessageBytes ? parseObject(data.toString("utf8")) : undefined;+ if (next?.t === "auth") {+ const refresh = parseAuth(next);+ if (refresh === undefined) return closeWith(ctx, ws, Close.Malformed);+ const renewed = checkToken(ctx, refresh);+ if (!renewed.ok || !renewed.claims.hid.equals(entry.hid)) return closeWith(ctx, ws, Close.TokenInvalid);+ expires = renewed.claims.exp;+ armExpiry();+ return sendJson(ws, { t: "hello", v: 1, node: ctx.node, sessionsMax: ctx.limits.hostSessionsMax });+ }+ const set = next ? parseAdmit(next, ctx.limits.admissionMax) : undefined;+ if (!set) return closeWith(ctx, ws, Close.Malformed);+ entry.admission = set;+ admitted = true;+ clearTimeout(admitDeadline);+ enforceAdmission(ctx, entry);+ };+ return handler;+ });+}++/** `GET /v1/host/data`: claims one waiting phone's `sid` for the token's host and splices the two sockets. */+export function handleData(ctx: Context, ws: WebSocket): void {+ afterFirstMessage(ctx, ws, (message) => {+ const claim = parseData(message);+ if (!claim) return void closeWith(ctx, ws, Close.Malformed);+ const verified = checkToken(ctx, claim.token);+ if (!verified.ok) return void closeWith(ctx, ws, Close.TokenInvalid);+ const session = ctx.hosts.get(verified.claims.hidText)?.sessions.get(claim.sid);+ if (!session || session.state !== "pending") return void closeWith(ctx, ws, Close.NotFound);+ session.splice(ws);+ return (data, isBinary) => session.fromHost(data, isBinary);+ });+}diff --git a/relay/src/main.ts b/relay/src/main.tsnew file mode 100644index 0000000000..18083e197d--- /dev/null+++ b/relay/src/main.ts@@ -0,0 +1,29 @@+import { loadConfig } from "./config.ts";+import { jsonLogger } from "./log.ts";+import { startRelay } from "./server.ts";++let config;+try {+ config = loadConfig(process.env);+} catch (error) {+ process.stderr.write(`relay: ${(error as Error).message}\n`);+ process.exit(1);+}+const log = jsonLogger(config.node);+const relay = await startRelay(config, { log });++let stopping = false;+const stop = () => {+ if (stopping) return;+ stopping = true;+ setTimeout(() => process.exit(0), config.limits.shutdownMs).unref();+ relay+ .drain()+ .then(() => relay.close())+ .finally(() => {+ log({ ev: "stop" });+ process.exit(0);+ });+};+process.on("SIGTERM", stop);+process.on("SIGINT", stop);diff --git a/relay/src/phone.ts b/relay/src/phone.tsnew file mode 100644index 0000000000..ace7863a9f--- /dev/null+++ b/relay/src/phone.ts@@ -0,0 +1,25 @@+import type { WebSocket } from "ws";+import type { Context } from "./context.ts";+import { afterFirstMessage, closeWith, sendJson } from "./socket.ts";+import { Session } from "./splice.ts";+import { Close, parsePhoneHello, sha256 } from "./wire.ts";++/**+ * `GET /v1/phone`: a phone names a host and proves admission. An absent host and an unadmitted phone get the same 4404,+ * so a phone without a pairing cannot learn whether a computer is online.+ */+export function handlePhone(ctx: Context, ws: WebSocket): void {+ afterFirstMessage(ctx, ws, (message) => {+ const hello = parsePhoneHello(message);+ if (!hello) return void closeWith(ctx, ws, Close.Malformed);+ const admHash = sha256(hello.adm);+ const entry = ctx.hosts.get(hello.hidText);+ if (!ctx.hosts.admitted(entry, admHash) || !entry?.control) return void closeWith(ctx, ws, Close.NotFound);+ if (entry.sessions.size >= ctx.limits.hostSessionsMax || ctx.budgets.over(entry.hidText)) {+ return void closeWith(ctx, ws, Close.Limited);+ }+ const session = new Session(ctx, entry, admHash, ws);+ sendJson(entry.control, { t: "open", sid: session.sid });+ return (data, isBinary) => session.fromPhone(data, isBinary);+ });+}diff --git a/relay/src/server.ts b/relay/src/server.tsnew file mode 100644index 0000000000..a54494f878--- /dev/null+++ b/relay/src/server.ts@@ -0,0 +1,222 @@+import { createServer, type IncomingMessage, type ServerResponse } from "node:http";+import type { AddressInfo, Socket } from "node:net";+import { performance } from "node:perf_hooks";+import { WebSocket, WebSocketServer } from "ws";+import type { RelayConfig } from "./config.ts";+import type { Context } from "./context.ts";+import { handleControl, handleData, HostBudgets, Hosts } from "./hosts.ts";+import { clientKey, IpLimiter } from "./limits.ts";+import { jsonLogger, type Logger } from "./log.ts";+import { bearerMatches, Metrics } from "./metrics.ts";+import { handlePhone } from "./phone.ts";+import { closeWith, Heartbeat, sendJson } from "./socket.ts";+import { Close, SUBPROTOCOL } from "./wire.ts";++type Route = "host" | "data" | "phone";++const ROUTES: Record<string, Route> = { "/v1/host": "host", "/v1/host/data": "data", "/v1/phone": "phone" };+const HANDLERS: Record<Route, (ctx: Context, ws: WebSocket) => void> = { host: handleControl, data: handleData, phone: handlePhone };+const SWEEP_MS = 60_000;+/** TCP connections Node accepts beyond the socket cap, so a refusal with a close code can still be delivered. */+const CONNECTION_HEADROOM = 1_024;++export interface Relay {+ port: number;+ ctx: Context;+ /** Sockets the relay holds, by route. */+ sockets: () => Map<WebSocket, Route>;+ /** SIGTERM: tell hosts the node is restarting, close phones with 4503, and resolve once every socket is gone. */+ drain: () => Promise<void>;+ close: () => Promise<void>;+}++export interface RelayOptions {+ log?: Logger;+ now?: () => number;+ wallSeconds?: () => number;+}++function refuse(socket: Socket, status: number, text: string): void {+ socket.end(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);+}++function offersSubprotocol(header: string | undefined): boolean {+ return header !== undefined && header.split(",").some((value) => value.trim() === SUBPROTOCOL);+}++export async function startRelay(config: RelayConfig, options: RelayOptions = {}): Promise<Relay> {+ const { limits } = config;+ const now = options.now ?? (() => performance.now());+ const wallSeconds = options.wallSeconds ?? (() => Date.now() / 1000);+ const metrics = new Metrics();+ const ctx = {+ node: config.node,+ limits,+ tokenKeys: config.tokenKeys,+ hosts: new Hosts(limits.admissionMax),+ budgets: new HostBudgets(limits.hostBytesPerDay, wallSeconds),+ metrics,+ log: options.log ?? jsonLogger(config.node),+ now,+ wallSeconds,+ } as Context;+ ctx.heartbeat = new Heartbeat(ctx);+ const ipLimiter = new IpLimiter(limits.ipNewPerMinute, limits.ipOpenMax, now);+ const sockets = new Map<WebSocket, Route>();+ let draining = false;++ const wss = new WebSocketServer({+ noServer: true,+ maxPayload: limits.maxPayloadBytes,+ perMessageDeflate: false,+ clientTracking: false,+ closeTimeout: limits.closeGraceMs,+ handleProtocols: () => SUBPROTOCOL,+ } as ConstructorParameters<typeof WebSocketServer>[0]);++ const gauges = () => {+ let pending = 0;+ let spliced = 0;+ for (const entry of ctx.hosts.all()) {+ for (const session of entry.sessions.values()) {+ if (session.state === "pending") pending += 1;+ else if (session.state === "spliced") spliced += 1;+ }+ }+ return [+ { name: "relay_hosts_connected", help: "Hosts with a control socket on this node", value: ctx.hosts.connected },+ { name: "relay_sessions_pending", help: "Phones waiting for their host's data socket", value: pending },+ { name: "relay_sessions_spliced", help: "Phone sessions spliced to a host", value: spliced },+ { name: "relay_sockets_open", help: "WebSockets held, every route", value: sockets.size },+ { name: "relay_sockets_max", help: "WebSockets this node holds before answering 4503", value: limits.socketsMax },+ { name: "relay_ip_entries", help: "Client keys with limiter state", value: ipLimiter.size },+ { name: "relay_draining", help: "1 while the node is shutting down", value: draining ? 1 : 0 },+ ];+ };++ const onRequest = (req: IncomingMessage, res: ServerResponse) => {+ const headers = { "cache-control": "no-store", "x-content-type-options": "nosniff" };+ if (req.method === "GET" && req.url === "/healthz") {+ res.writeHead(draining ? 503 : 200, { ...headers, "content-type": "application/json" });+ return void res.end(JSON.stringify({ ok: !draining, node: config.node }));+ }+ if (req.method === "GET" && req.url === "/metrics" && config.metricsToken) {+ if (!bearerMatches(req.headers.authorization, config.metricsToken)) {+ res.writeHead(401, { ...headers, "www-authenticate": "Bearer" });+ return void res.end();+ }+ res.writeHead(200, { ...headers, "content-type": "text/plain; version=0.0.4" });+ return void res.end(metrics.render(gauges()));+ }+ res.writeHead(404, headers);+ res.end();+ };++ const server = createServer({ maxHeaderSize: 16 * 1024, headersTimeout: 5_000, requestTimeout: 10_000, keepAliveTimeout: 5_000 }, onRequest);+ server.maxConnections = limits.socketsMax + CONNECTION_HEADROOM;++ server.on("upgrade", (req: IncomingMessage, socket: Socket, head: Buffer) => {+ socket.on("error", () => {});+ const route = ROUTES[req.url ?? ""];+ if (!route) {+ metrics.inc("relay_refused_total", "path");+ return refuse(socket, 404, "Not Found");+ }+ if (req.headers.origin !== undefined) {+ metrics.inc("relay_refused_total", "origin");+ return refuse(socket, 403, "Forbidden");+ }+ if (!offersSubprotocol(req.headers["sec-websocket-protocol"])) {+ metrics.inc("relay_refused_total", "subprotocol");+ return refuse(socket, 400, "Bad Request");+ }+ const key = clientKey(req.socket.remoteAddress, req.headers["x-forwarded-for"]);+ if (!key) {+ metrics.inc("relay_refused_total", "forwarded_for");+ return refuse(socket, 400, "Bad Request");+ }+ wss.handleUpgrade(req, socket, head, (ws) => {+ ws.on("error", () => {});+ if (draining) {+ metrics.inc("relay_refused_total", "draining");+ return closeWith(ctx, ws, Close.Unavailable, JSON.stringify({ retryInMs: limits.restartPhoneRetryMs }));+ }+ if (sockets.size >= limits.socketsMax) {+ metrics.inc("relay_refused_total", "full");+ return closeWith(ctx, ws, Close.Unavailable, JSON.stringify({ retryInMs: limits.fullRetryMs }));+ }+ const verdict = ipLimiter.admit(key);+ if (verdict !== "ok") {+ metrics.inc("relay_refused_total", `ip_${verdict}`);+ return closeWith(ctx, ws, Close.Limited);+ }+ metrics.inc("relay_upgrades_total", route);+ sockets.set(ws, route);+ ws.once("close", () => {+ sockets.delete(ws);+ ipLimiter.release(key);+ });+ HANDLERS[route](ctx, ws);+ });+ });++ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(config.port, config.host, () => {+ server.off("error", reject);+ resolve();+ });+ });+ const port = (server.address() as AddressInfo).port;+ ctx.heartbeat.start();+ const sweeper = setInterval(() => {+ ipLimiter.sweep();+ ctx.budgets.sweep();+ }, SWEEP_MS);+ ctx.log({ ev: "start", port });++ const allClosed = (deadlineMs: number) =>+ new Promise<void>((resolve) => {+ const started = now();+ const poll = setInterval(() => {+ if (sockets.size > 0 && now() - started < deadlineMs) return;+ clearInterval(poll);+ for (const ws of sockets.keys()) ws.terminate();+ resolve();+ }, 50);+ });++ const drain = async () => {+ if (draining) return;+ draining = true;+ let sessions = 0;+ const hosts = ctx.hosts.connected;+ server.close();+ server.closeIdleConnections();+ const retry = JSON.stringify({ retryInMs: limits.restartPhoneRetryMs });+ for (const entry of [...ctx.hosts.all()]) {+ for (const session of [...entry.sessions.values()]) {+ sessions += 1;+ session.end(Close.Unavailable, retry);+ }+ if (entry.control) {+ sendJson(entry.control, { t: "restarting", reconnectInMs: limits.restartReconnectInMs, tryForMs: limits.restartTryForMs });+ closeWith(ctx, entry.control, 1001);+ }+ }+ for (const ws of sockets.keys()) closeWith(ctx, ws, Close.Unavailable, retry);+ ctx.log({ ev: "drain", hosts, sessions });+ await allClosed(Math.max(0, limits.shutdownMs - 1_000));+ };++ const close = async () => {+ clearInterval(sweeper);+ ctx.heartbeat.stop();+ for (const ws of sockets.keys()) ws.terminate();+ server.closeAllConnections();+ await new Promise<void>((resolve) => (server.listening ? server.close(() => resolve()) : resolve()));+ metrics.close();+ };++ return { port, ctx, sockets: () => sockets, drain, close };+}diff --git a/relay/src/socket.ts b/relay/src/socket.tsnew file mode 100644index 0000000000..19384339d6--- /dev/null+++ b/relay/src/socket.ts@@ -0,0 +1,97 @@+import { WebSocket, type RawData } from "ws";+import type { Context } from "./context.ts";+import { Close, parseObject } from "./wire.ts";++export type MessageHandler = (data: Buffer, isBinary: boolean) => void;++/** Closes with `code` when the socket is open; the server's closeTimeout cuts a peer that never answers the close. */+export function closeWith(ctx: Context, ws: WebSocket, code: number, reason?: string): void {+ if (ws.readyState === WebSocket.OPEN) {+ ctx.metrics.inc("relay_closes_total", code);+ ws.close(code, reason);+ } else if (ws.readyState === WebSocket.CONNECTING) {+ ws.terminate();+ }+}++export function sendJson(ws: WebSocket, value: unknown): void {+ if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(value));+}++/**+ * The pre-auth rule for every path: exactly one text message of at most `authMessageBytes`, holding a JSON object,+ * within `authDeadlineMs`; anything else closes with 4400. `first` gets that object and returns the handler for every+ * later message, or nothing when it closed the socket.+ */+export function afterFirstMessage(ctx: Context, ws: WebSocket, first: (message: Record<string, unknown>) => MessageHandler | undefined): void {+ const { authDeadlineMs, authMessageBytes } = ctx.limits;+ let next: MessageHandler | undefined;+ let seen = false;+ const deadline = setTimeout(() => closeWith(ctx, ws, Close.Malformed), authDeadlineMs);+ ws.once("close", () => clearTimeout(deadline));+ ws.on("message", (raw: RawData, isBinary: boolean) => {+ if (ws.readyState !== WebSocket.OPEN) return;+ const data = raw as Buffer;+ if (next) return next(data, isBinary);+ if (seen) return;+ seen = true;+ clearTimeout(deadline);+ const message = !isBinary && data.length <= authMessageBytes ? parseObject(data.toString("utf8")) : undefined;+ if (!message) return closeWith(ctx, ws, Close.Malformed);+ next = first(message);+ });+}++/**+ * Pings every tracked socket each `pingIntervalMs` and cuts the ones that showed no sign of life `pongTimeoutMs` later.+ * A pong, a message, or a write to the socket completing all count as life. A socket the relay itself paused is skipped:+ * its pong sits unread behind the pause, and the splice's wedge timer covers it.+ */+export class Heartbeat {+ private readonly alive = new Map<WebSocket, boolean>();+ private readonly ctx: Context;+ private pinger: NodeJS.Timeout | undefined;+ private checker: NodeJS.Timeout | undefined;++ constructor(ctx: Context) {+ this.ctx = ctx;+ }++ start(): void {+ this.pinger = setInterval(() => this.ping(), this.ctx.limits.pingIntervalMs);+ }++ stop(): void {+ clearInterval(this.pinger);+ clearTimeout(this.checker);+ }++ track(ws: WebSocket): void {+ if (this.alive.has(ws)) return;+ this.alive.set(ws, true);+ ws.on("pong", () => this.mark(ws));+ ws.once("close", () => this.alive.delete(ws));+ }++ mark(ws: WebSocket): void {+ if (this.alive.has(ws)) this.alive.set(ws, true);+ }++ private ping(): void {+ for (const ws of this.alive.keys()) {+ if (ws.readyState !== WebSocket.OPEN) continue;+ this.alive.set(ws, false);+ ws.ping();+ }+ clearTimeout(this.checker);+ this.checker = setTimeout(() => this.check(), this.ctx.limits.pongTimeoutMs);+ }++ private check(): void {+ for (const [ws, alive] of this.alive) {+ if (alive || ws.isPaused || ws.readyState !== WebSocket.OPEN) continue;+ this.ctx.metrics.inc("relay_pong_timeouts_total");+ ws.terminate();+ }+ }+}diff --git a/relay/src/splice.ts b/relay/src/splice.tsnew file mode 100644index 0000000000..2c76ec205c--- /dev/null+++ b/relay/src/splice.ts@@ -0,0 +1,228 @@+import { randomBytes } from "node:crypto";+import { WebSocket } from "ws";+import type { Context } from "./context.ts";+import type { HostEntry } from "./hosts.ts";+import { TokenBucket } from "./limits.ts";+import { closeWith, sendJson } from "./socket.ts";+import { Close, PASS_THROUGH_CODES } from "./wire.ts";++const BACKPRESSURE = 1;+const THROTTLE = 2;+const HEAVY_SLOTS = 30;++/**+ * Bytes a session moved in each of the last HEAVY_SLOTS slices of the heavy window. `add` says when a session that is at+ * least one window old has averaged more than the heavy rate across the whole window.+ */+export class HeavyMeter {+ private readonly slots = new Float64Array(HEAVY_SLOTS);+ private readonly slotMs: number;+ private readonly limitBytes: number;+ private readonly started: number;+ private slot: number;+ private sum = 0;++ constructor(windowMs: number, heavyBitsPerSecond: number, now: number) {+ this.slotMs = windowMs / HEAVY_SLOTS;+ this.limitBytes = (heavyBitsPerSecond / 8) * (windowMs / 1000);+ this.started = now;+ this.slot = Math.floor(now / this.slotMs);+ }++ add(bytes: number, now: number): boolean {+ const slot = Math.floor(now / this.slotMs);+ if (slot !== this.slot) {+ for (let s = this.slot + 1; s <= Math.min(slot, this.slot + HEAVY_SLOTS); s++) {+ this.sum -= this.slots[s % HEAVY_SLOTS]!;+ this.slots[s % HEAVY_SLOTS] = 0;+ }+ this.slot = slot;+ }+ this.slots[slot % HEAVY_SLOTS]! += bytes;+ this.sum += bytes;+ return now - this.started >= this.slotMs * HEAVY_SLOTS && this.sum > this.limitBytes;+ }+}++/** One way through a splice. The source is read only while `paused` is 0. */+interface Direction {+ src: WebSocket;+ dst: WebSocket;+ paused: number;+ lastProgress: number;+ wedge: NodeJS.Timeout | undefined;+ sent: (error?: Error) => void;+}++export type SessionState = "pending" | "spliced" | "closed";++/**+ * A phone waiting for its host's data socket, then the two sockets spliced. The relay forwards whole binary messages+ * and never drops one: when the destination falls behind it stops reading the source.+ */+export class Session {+ readonly sid = randomBytes(16).toString("base64url");+ readonly admHash: Buffer;+ state: SessionState = "pending";+ up = 0;+ down = 0;+ private readonly ctx: Context;+ private readonly entry: HostEntry;+ private readonly phone: WebSocket;+ private data: WebSocket | undefined;+ private readonly started: number;+ private readonly openTimer: NodeJS.Timeout;+ private toHost: Direction | undefined;+ private toPhone: Direction | undefined;+ private meter: HeavyMeter | undefined;+ private throttle: TokenBucket | undefined;+ private readonly throttleTimers = new Set<NodeJS.Timeout>();++ constructor(ctx: Context, entry: HostEntry, admHash: Buffer, phone: WebSocket) {+ this.ctx = ctx;+ this.entry = entry;+ this.admHash = admHash;+ this.phone = phone;+ this.started = ctx.now();+ entry.sessions.set(this.sid, this);+ this.openTimer = setTimeout(() => this.end(Close.NoDataSocket), ctx.limits.openDeadlineMs);+ phone.once("close", (code) => this.closed(phone, code));+ }++ /** The host's data socket arrived for this `sid`: splice, then tell the phone it may start its handshake. */+ splice(data: WebSocket): void {+ this.state = "spliced";+ this.data = data;+ clearTimeout(this.openTimer);+ const now = this.ctx.now();+ this.meter = new HeavyMeter(this.ctx.limits.heavyWindowMs, this.ctx.limits.heavyBitsPerSecond, now);+ this.toHost = this.direction(this.phone, data, now);+ this.toPhone = this.direction(data, this.phone, now);+ data.once("close", (code) => this.closed(data, code));+ this.ctx.heartbeat.track(this.phone);+ this.ctx.heartbeat.track(data);+ this.ctx.metrics.inc("relay_sessions_total");+ sendJson(this.phone, { t: "ready" });+ }++ fromPhone(data: Buffer, isBinary: boolean): void {+ if (this.state !== "spliced" || !isBinary) return this.end(Close.Malformed);+ this.up += data.length;+ this.ctx.metrics.inc("relay_bytes_total", "up", data.length);+ this.forward(this.toHost!, data);+ }++ fromHost(data: Buffer, isBinary: boolean): void {+ if (this.state !== "spliced" || !isBinary) return this.end(Close.Malformed);+ this.down += data.length;+ this.ctx.metrics.inc("relay_bytes_total", "down", data.length);+ this.forward(this.toPhone!, data);+ }++ /** The relay ends the session: both sockets close with `code`. */+ end(code: number, reason?: string): void {+ if (this.state === "closed") return;+ this.finish(code);+ closeWith(this.ctx, this.phone, code, reason);+ if (this.data) closeWith(this.ctx, this.data, code, reason);+ }++ private direction(src: WebSocket, dst: WebSocket, now: number): Direction {+ const dir: Direction = { src, dst, paused: 0, lastProgress: now, wedge: undefined, sent: () => {} };+ dir.sent = (error) => {+ if (error) return;+ dir.lastProgress = this.ctx.now();+ this.ctx.heartbeat.mark(dst);+ if (dir.paused & BACKPRESSURE && dst.bufferedAmount <= this.ctx.limits.lowWaterBytes) this.resume(dir, BACKPRESSURE);+ };+ return dir;+ }++ private forward(dir: Direction, data: Buffer): void {+ const { limits } = this.ctx;+ this.ctx.heartbeat.mark(dir.src);+ dir.dst.send(data, { binary: true }, dir.sent);+ if (this.state !== "spliced") return;+ if (this.ctx.budgets.add(this.entry.hidText, data.length)) return this.overBudget();+ const now = this.ctx.now();+ if (!this.throttle && this.meter!.add(data.length, now)) {+ const perMs = limits.throttleBitsPerSecond / 8 / 1000;+ this.throttle = new TokenBucket(Math.max(limits.maxPayloadBytes, perMs * 100), perMs, this.ctx.now);+ this.ctx.metrics.inc("relay_throttled_sessions_total");+ this.ctx.log({ ev: "throttle", hid8: this.entry.hid8 });+ }+ if (this.throttle) {+ const waitMs = this.throttle.spend(data.length);+ if (waitMs > 0 && !(dir.paused & THROTTLE)) {+ this.pause(dir, THROTTLE);+ const timer = setTimeout(() => {+ this.throttleTimers.delete(timer);+ this.resume(dir, THROTTLE);+ }, waitMs);+ this.throttleTimers.add(timer);+ }+ }+ if (dir.dst.bufferedAmount > limits.highWaterBytes && !(dir.paused & BACKPRESSURE)) {+ this.ctx.metrics.inc("relay_backpressure_pauses_total");+ dir.lastProgress = now;+ this.pause(dir, BACKPRESSURE);+ this.watchWedge(dir, limits.wedgeMs);+ }+ }++ /** While backpressure holds a source, a destination that takes nothing for `wedgeMs` ends the session. */+ private watchWedge(dir: Direction, delayMs: number): void {+ clearTimeout(dir.wedge);+ dir.wedge = setTimeout(() => {+ dir.wedge = undefined;+ if (!(dir.paused & BACKPRESSURE) || this.state !== "spliced") return;+ const idle = this.ctx.now() - dir.lastProgress;+ if (idle >= this.ctx.limits.wedgeMs) this.end(Close.Limited);+ else this.watchWedge(dir, this.ctx.limits.wedgeMs - idle);+ }, delayMs);+ }++ private pause(dir: Direction, reason: number): void {+ if (dir.paused === 0) dir.src.pause();+ dir.paused |= reason;+ }++ private resume(dir: Direction, reason: number): void {+ if (!(dir.paused & reason)) return;+ dir.paused &= ~reason;+ if (reason === BACKPRESSURE) clearTimeout(dir.wedge);+ if (dir.paused === 0 && this.state === "spliced") dir.src.resume();+ }++ private overBudget(): void {+ this.ctx.metrics.inc("relay_host_budget_exceeded_total");+ this.ctx.log({ ev: "budget", hid8: this.entry.hid8 });+ for (const session of [...this.entry.sessions.values()]) session.end(Close.Limited);+ }++ /** One of the two sockets closed: the other gets the same code when it is one the ends use with each other. */+ private closed(socket: WebSocket, code: number): void {+ if (this.state === "closed") return;+ this.finish(code);+ const other = socket === this.phone ? this.data : this.phone;+ if (other) closeWith(this.ctx, other, PASS_THROUGH_CODES.has(code) ? code : 1001);+ }++ private finish(code: number): void {+ this.state = "closed";+ clearTimeout(this.openTimer);+ for (const dir of [this.toHost, this.toPhone]) clearTimeout(dir?.wedge);+ for (const timer of this.throttleTimers) clearTimeout(timer);+ this.throttleTimers.clear();+ this.entry.sessions.delete(this.sid);+ this.ctx.hosts.release(this.entry);+ this.ctx.log({+ ev: "session",+ hid8: this.entry.hid8,+ dur_s: Math.round((this.ctx.now() - this.started) / 1000),+ up: this.up,+ down: this.down,+ close: code,+ });+ }+}diff --git a/relay/tsconfig.json b/relay/tsconfig.jsonnew file mode 100644index 0000000000..1058a94a5c--- /dev/null+++ b/relay/tsconfig.json@@ -0,0 +1,20 @@+{+ "compilerOptions": {+ "target": "ES2024",+ "lib": ["ES2024"],+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "types": ["node"],+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noFallthroughCasesInSwitch": true,+ "erasableSyntaxOnly": true,+ "verbatimModuleSyntax": true,+ "allowImportingTsExtensions": true,+ "noEmit": true,+ "skipLibCheck": true+ },+ "include": ["src", "test", "load"]+}