Skip to content

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

relay: wire parsing, token verify, per-IP limits, config, logs and metrics

milind-soni51d02410e57d
diff --git a/relay/package.json b/relay/package.json
new file mode 100644
index 0000000000..b1bd6a05f2
--- /dev/null
+++ b/relay/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@openmausbot/relay",
+ "private": true,
+ "version": "0.0.0",
+ "type": "module",
+ "packageManager": "[email protected]",
+ "engines": {
+ "node": ">=24"
+ },
+ "dependencies": {
+ "ws": "8.22.0"
+ },
+ "devDependencies": {
+ "@types/node": "24.19.2",
+ "@types/ws": "8.18.2",
+ "typescript": "5.9.3"
+ },
+ "scripts": {
+ "start": "node src/main.ts",
+ "check": "tsc -p tsconfig.json",
+ "test": "node --test --test-concurrency=1 test/*.test.ts",
+ "fuzz": "node --test test/fuzz.test.ts",
+ "load": "node load/load.ts",
+ "audit": "pnpm audit --prod --audit-level high"
+ }
+}
diff --git a/relay/pnpm-workspace.yaml b/relay/pnpm-workspace.yaml
new file mode 100644
index 0000000000..e39423f407
--- /dev/null
+++ b/relay/pnpm-workspace.yaml
@@ -0,0 +1,5 @@
+# The relay is its own pnpm root with its own lockfile: its image, its CI job and its audit see only the relay's
+# dependencies, and nothing the desktop app adds can reach the relay.
+packages:
+ - "."
+onlyBuiltDependencies: []
diff --git a/relay/src/config.ts b/relay/src/config.ts
new file mode 100644
index 0000000000..60f00b79ec
--- /dev/null
+++ b/relay/src/config.ts
@@ -0,0 +1,103 @@
+import type { KeyObject } from "node:crypto";
+import { parseTokenKeys } from "./token.ts";
+
+const MiB = 1024 * 1024;
+
+/** Timers and limits from wire spec §3.9 and §3.10. Only tests change them, through startRelay. */
+export interface Limits {
+ /** Before auth: the one text message must arrive within this and fit in authMessageBytes. */
+ authDeadlineMs: number;
+ authMessageBytes: number;
+ /** WebSocket maxPayload on every socket, before and after auth. */
+ maxPayloadBytes: number;
+ /** A host must send its admission set this soon after `hello`. */
+ admitDeadlineMs: number;
+ admissionMax: number;
+ /** A host must open the data socket for a phone this soon after `open`; it is also a `sid`'s whole life. */
+ openDeadlineMs: number;
+ /** Control-socket messages after auth: a burst, then a steady rate. */
+ controlBurst: number;
+ controlPerSecond: number;
+ pingIntervalMs: number;
+ pongTimeoutMs: number;
+ ipNewPerMinute: number;
+ ipOpenMax: number;
+ hostSessionsMax: number;
+ socketsMax: number;
+ fullRetryMs: number;
+ /** Backpressure: pause the source above highWater bytes queued for the destination, resume below lowWater. */
+ highWaterBytes: number;
+ lowWaterBytes: number;
+ /** A paused source whose destination makes no progress this long closes the session. */
+ wedgeMs: number;
+ /** A session averaging above heavyBitsPerSecond over heavyWindowMs is held to throttleBitsPerSecond from then on. */
+ heavyWindowMs: number;
+ heavyBitsPerSecond: number;
+ throttleBitsPerSecond: number;
+ hostBytesPerDay: number;
+ /** SIGTERM: what hosts are told in `restarting`, what phones are told in 4503, and when the process must be gone. */
+ restartReconnectInMs: number;
+ restartTryForMs: number;
+ restartPhoneRetryMs: number;
+ shutdownMs: number;
+ /** A socket the relay closes and whose peer does not finish the close handshake is cut after this. */
+ closeGraceMs: number;
+}
+
+export const DEFAULT_LIMITS: Readonly<Limits> = Object.freeze({
+ authDeadlineMs: 5_000,
+ authMessageBytes: 4 * 1024,
+ maxPayloadBytes: 70_000,
+ admitDeadlineMs: 5_000,
+ admissionMax: 32,
+ openDeadlineMs: 10_000,
+ controlBurst: 20,
+ controlPerSecond: 2,
+ pingIntervalMs: 20_000,
+ pongTimeoutMs: 10_000,
+ ipNewPerMinute: 60,
+ ipOpenMax: 256,
+ hostSessionsMax: 16,
+ socketsMax: 30_000,
+ fullRetryMs: 5_000,
+ highWaterBytes: 1 * MiB,
+ lowWaterBytes: 256 * 1024,
+ wedgeMs: 60_000,
+ heavyWindowMs: 30 * 60_000,
+ heavyBitsPerSecond: 50e6,
+ throttleBitsPerSecond: 20e6,
+ hostBytesPerDay: 50e9,
+ restartReconnectInMs: 0,
+ restartTryForMs: 15_000,
+ restartPhoneRetryMs: 1_000,
+ shutdownMs: 5_000,
+ closeGraceMs: 2_000,
+});
+
+export interface RelayConfig {
+ node: string;
+ host: string;
+ port: number;
+ tokenKeys: ReadonlyMap<string, KeyObject>;
+ /** /metrics answers only with this bearer; without one /metrics is off. */
+ metricsToken: string | undefined;
+ limits: Limits;
+}
+
+const NODE = /^relay[1-9][0-9]?$/;
+const MIN_METRICS_TOKEN = 32;
+
+/** Reads the deployment facts from the environment. Throws a message that never repeats a value it read. */
+export function loadConfig(env: NodeJS.ProcessEnv): RelayConfig {
+ const node = env.RELAY_NODE ?? "";
+ if (!NODE.test(node)) throw new Error("RELAY_NODE must be relay1 … relay99");
+ if (!env.RELAY_TOKEN_KEYS) throw new Error("RELAY_TOKEN_KEYS is required");
+ const tokenKeys = parseTokenKeys(env.RELAY_TOKEN_KEYS);
+ const metricsToken = env.RELAY_METRICS_TOKEN || undefined;
+ if (metricsToken !== undefined && metricsToken.length < MIN_METRICS_TOKEN) {
+ throw new Error(`RELAY_METRICS_TOKEN must be at least ${MIN_METRICS_TOKEN} characters`);
+ }
+ 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 } };
+}
diff --git a/relay/src/limits.ts b/relay/src/limits.ts
new file mode 100644
index 0000000000..6509f12cec
--- /dev/null
+++ b/relay/src/limits.ts
@@ -0,0 +1,136 @@
+import { isIPv4, isIPv6 } from "node:net";
+
+/** Caddy runs on the same host and is the only peer allowed to name the client in X-Forwarded-For. */
+const TRUSTED_PROXY = new Set(["127.0.0.1", "::ffff:127.0.0.1"]);
+
+/**
+ * The key a client's per-IP limits are counted under, or undefined when a trusted proxy sent an X-Forwarded-For that is
+ * not an address. The last entry is the one the proxy itself appended, so earlier entries a client wrote are ignored.
+ * Anyone but the proxy is counted by its own address and its X-Forwarded-For is ignored.
+ */
+export function clientKey(remoteAddress: string | undefined, forwardedFor: string | string[] | undefined): string | undefined {
+ if (!remoteAddress) return undefined;
+ if (!TRUSTED_PROXY.has(remoteAddress)) return addressKey(remoteAddress);
+ const header = Array.isArray(forwardedFor) ? forwardedFor.join(",") : forwardedFor;
+ if (header === undefined) return addressKey(remoteAddress);
+ const last = header.slice(header.lastIndexOf(",") + 1).trim();
+ return isIPv4(last) || isIPv6(last) ? addressKey(last) : undefined;
+}
+
+/** IPv4 by address. IPv6 by /64, because one client is routinely given a whole /64 and could rotate within it. */
+export function addressKey(address: string): string {
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address);
+ if (mapped) return mapped[1]!;
+ if (isIPv4(address)) return address;
+ const groups = expandIPv6(address);
+ return groups ? `${groups.slice(0, 4).join(":")}::/64` : address;
+}
+
+function expandIPv6(address: string): string[] | undefined {
+ let text = address.split("%")[0]!.toLowerCase();
+ const v4 = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(text);
+ if (v4) {
+ const [a, b, c, d] = v4.slice(1).map(Number) as [number, number, number, number];
+ text = `${text.slice(0, v4.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;
+ }
+ const halves = text.split("::");
+ if (halves.length > 2) return undefined;
+ const head = halves[0] ? halves[0].split(":") : [];
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
+ const fill = 8 - head.length - tail.length;
+ if (halves.length === 1 ? fill !== 0 : fill < 1) return undefined;
+ return [...head, ...Array<string>(halves.length === 2 ? fill : 0).fill("0"), ...tail].map((group) => group.padStart(4, "0"));
+}
+
+/** A token bucket that starts full: `capacity` tokens, refilled at `perMs` tokens a millisecond. */
+export class TokenBucket {
+ private readonly capacity: number;
+ private readonly perMs: number;
+ private readonly now: () => number;
+ private tokens: number;
+ private last: number;
+
+ constructor(capacity: number, perMs: number, now: () => number) {
+ this.capacity = capacity;
+ this.perMs = perMs;
+ this.now = now;
+ this.tokens = capacity;
+ this.last = now();
+ }
+
+ /** Takes `count` tokens when that many are there. */
+ take(count = 1): boolean {
+ this.refill();
+ if (this.tokens < count) return false;
+ this.tokens -= count;
+ return true;
+ }
+
+ /** Takes `count` tokens even into debt, and says how long until the bucket is out of debt (0 when it is not in debt). */
+ spend(count: number): number {
+ this.refill();
+ this.tokens -= count;
+ return this.tokens >= 0 ? 0 : Math.ceil(-this.tokens / this.perMs);
+ }
+
+ get full(): boolean {
+ this.refill();
+ return this.tokens >= this.capacity;
+ }
+
+ private refill(): void {
+ const now = this.now();
+ this.tokens = Math.min(this.capacity, this.tokens + (now - this.last) * this.perMs);
+ this.last = now;
+ }
+}
+
+export type IpVerdict = "ok" | "rate" | "open";
+
+interface IpEntry {
+ bucket: TokenBucket;
+ open: number;
+}
+
+/** New sockets a minute and open sockets, per client key. Entries live only in memory and are swept once idle. */
+export class IpLimiter {
+ private readonly entries = new Map<string, IpEntry>();
+ private readonly newPerMinute: number;
+ private readonly openMax: number;
+ private readonly now: () => number;
+
+ constructor(newPerMinute: number, openMax: number, now: () => number) {
+ this.newPerMinute = newPerMinute;
+ this.openMax = openMax;
+ this.now = now;
+ }
+
+ /** Counts a new socket for `key` when its limits allow one; the caller must `release` it when the socket closes. */
+ admit(key: string): IpVerdict {
+ let entry = this.entries.get(key);
+ if (!entry) {
+ entry = { bucket: new TokenBucket(this.newPerMinute, this.newPerMinute / 60_000, this.now), open: 0 };
+ this.entries.set(key, entry);
+ }
+ if (entry.open >= this.openMax) return "open";
+ if (!entry.bucket.take()) return "rate";
+ entry.open += 1;
+ return "ok";
+ }
+
+ release(key: string): void {
+ const entry = this.entries.get(key);
+ if (entry && entry.open > 0) entry.open -= 1;
+ }
+
+ /** Forgets keys with no open sockets and a full bucket: they would behave exactly like a new key. */
+ sweep(): void {
+ for (const [key, entry] of this.entries) {
+ if (entry.open === 0 && entry.bucket.full) this.entries.delete(key);
+ }
+ }
+
+ get size(): number {
+ return this.entries.size;
+ }
+}
diff --git a/relay/src/log.ts b/relay/src/log.ts
new file mode 100644
index 0000000000..309a02e2d8
--- /dev/null
+++ b/relay/src/log.ts
@@ -0,0 +1,23 @@
+import { sha256 } from "./wire.ts";
+
+/**
+ * Every line the relay writes. Each field is a count, a duration, a close code or `hid8`, so no IP address, token,
+ * admission value or payload byte has a field it could be written into.
+ */
+export type LogEvent =
+ | { ev: "start"; port: number }
+ | { ev: "session"; hid8: string; dur_s: number; up: number; down: number; close: number }
+ | { ev: "host"; hid8: string; dur_s: number; close: number }
+ | { ev: "throttle"; hid8: string }
+ | { ev: "budget"; hid8: string }
+ | { ev: "drain"; hosts: number; sessions: number }
+ | { ev: "stop" };
+
+export type Logger = (event: LogEvent) => void;
+
+/** The first 8 hex characters of SHA256(hostId): enough to follow one host through the logs, not enough to dial it. */
+export const hid8 = (hostId: Buffer): string => sha256(hostId).toString("hex").slice(0, 8);
+
+export function jsonLogger(node: string, write: (line: string) => void = (line) => process.stdout.write(line)): Logger {
+ return (event) => write(`${JSON.stringify({ ts: new Date().toISOString(), node, ...event })}\n`);
+}
diff --git a/relay/src/metrics.ts b/relay/src/metrics.ts
new file mode 100644
index 0000000000..4eb3203a51
--- /dev/null
+++ b/relay/src/metrics.ts
@@ -0,0 +1,83 @@
+import { timingSafeEqual } from "node:crypto";
+import { monitorEventLoopDelay } from "node:perf_hooks";
+import { sha256 } from "./wire.ts";
+
+const COUNTERS = {
+ relay_upgrades_total: { help: "WebSocket upgrades accepted, by route", label: "route" },
+ relay_refused_total: { help: "Connections refused before or at the upgrade, by reason", label: "reason" },
+ relay_closes_total: { help: "Sockets the relay closed, by close code", label: "code" },
+ relay_token_rejected_total: { help: "Host tokens rejected, by reason", label: "reason" },
+ relay_bytes_total: { help: "Payload bytes forwarded, up = phone to host, down = host to phone", label: "dir" },
+ relay_sessions_total: { help: "Phone sessions spliced to a host", label: undefined },
+ relay_backpressure_pauses_total: { help: "Times a source was paused because its destination was behind", label: undefined },
+ relay_throttled_sessions_total: { help: "Sessions held to the heavy-session rate", label: undefined },
+ relay_host_budget_exceeded_total: { help: "Hosts that used their daily byte budget", label: undefined },
+ relay_pong_timeouts_total: { help: "Sockets cut for not answering a ping", label: undefined },
+} as const;
+
+export type CounterName = keyof typeof COUNTERS;
+
+export interface Gauge {
+ name: string;
+ help: string;
+ value: number;
+}
+
+export class Metrics {
+ private readonly counts = new Map<string, number>();
+ private readonly loopDelay = monitorEventLoopDelay({ resolution: 10 });
+
+ constructor() {
+ this.loopDelay.enable();
+ }
+
+ inc(name: CounterName, label?: string | number, by = 1): void {
+ const key = label === undefined ? name : `${name}\u0000${label}`;
+ this.counts.set(key, (this.counts.get(key) ?? 0) + by);
+ }
+
+ count(name: CounterName, label?: string | number): number {
+ return this.counts.get(label === undefined ? name : `${name}\u0000${label}`) ?? 0;
+ }
+
+ /** Prometheus text format. The event-loop lag window restarts at each render, so it covers one scrape interval. */
+ render(gauges: Gauge[]): string {
+ const lines: string[] = [];
+ for (const [name, { help, label }] of Object.entries(COUNTERS)) {
+ lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} counter`);
+ const series = [...this.counts].filter(([key]) => key === name || key.startsWith(`${name}\u0000`));
+ if (series.length === 0 && label === undefined) lines.push(`${name} 0`);
+ for (const [key, value] of series) {
+ const at = key.indexOf("\u0000");
+ lines.push(at < 0 ? `${name} ${value}` : `${name}{${label}="${key.slice(at + 1)}"} ${value}`);
+ }
+ }
+ const usage = process.cpuUsage();
+ const memory = process.memoryUsage();
+ const all: Gauge[] = [
+ ...gauges,
+ { name: "relay_event_loop_lag_p99_seconds", help: "Event-loop delay p99 since the last scrape", value: this.loopDelay.percentile(99) / 1e9 },
+ { name: "relay_event_loop_lag_max_seconds", help: "Event-loop delay max since the last scrape", value: this.loopDelay.max / 1e9 },
+ { name: "process_resident_memory_bytes", help: "Resident memory", value: memory.rss },
+ { name: "process_heap_used_bytes", help: "V8 heap in use", value: memory.heapUsed },
+ { name: "process_cpu_seconds_total", help: "User and system CPU time", value: (usage.user + usage.system) / 1e6 },
+ { name: "process_start_time_seconds", help: "Start time, Unix seconds", value: Math.round(Date.now() / 1000 - process.uptime()) },
+ ];
+ this.loopDelay.reset();
+ for (const { name, help, value } of all) {
+ const type = name.endsWith("_total") ? "counter" : "gauge";
+ lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} ${type}`, `${name} ${Number.isFinite(value) ? value : 0}`);
+ }
+ return `${lines.join("\n")}\n`;
+ }
+
+ close(): void {
+ this.loopDelay.disable();
+ }
+}
+
+/** Compares a bearer header with the configured token in constant time; both sides are hashed to one length first. */
+export function bearerMatches(header: string | undefined, token: string): boolean {
+ const presented = header?.startsWith("Bearer ") ? header.slice("Bearer ".length) : "";
+ return timingSafeEqual(sha256(presented), sha256(token)) && presented.length > 0;
+}
diff --git a/relay/src/token.ts b/relay/src/token.ts
new file mode 100644
index 0000000000..080cea02b6
--- /dev/null
+++ b/relay/src/token.ts
@@ -0,0 +1,80 @@
+import { createPublicKey, verify, type KeyObject } from "node:crypto";
+import { decodeB64u, parseObject } from "./wire.ts";
+
+/** The control plane mints tokens with `exp = iat + 12 h`. */
+export const TOKEN_LIFETIME_S = 12 * 60 * 60;
+/** How far a token's `iat` may be ahead of this node's clock. */
+export const CLOCK_SKEW_S = 300;
+const MAX_TOKEN_CHARS = 2048;
+const MAX_KEYS = 2;
+const KID = /^[A-Za-z0-9_-]{1,16}$/;
+const IID = /^[A-Za-z0-9_-]{1,64}$/;
+
+export interface TokenClaims {
+ kid: string;
+ hid: Buffer;
+ hidText: string;
+ iid: string;
+ iat: number;
+ exp: number;
+}
+
+export type TokenFailure = "malformed" | "signature" | "claims" | "expired";
+export type TokenResult = { ok: true; claims: TokenClaims } | { ok: false; reason: TokenFailure };
+
+/**
+ * `RELAY_TOKEN_KEYS`: `{"k1":"<b64u 32-byte Ed25519 public key>"}`, one or two entries so a key can be rotated. The relay
+ * only ever holds public keys, so a node that is taken over cannot mint host tokens.
+ */
+export function parseTokenKeys(json: string): Map<string, KeyObject> {
+ const object = parseObject(json);
+ if (!object) throw new Error("RELAY_TOKEN_KEYS must be a JSON object");
+ const entries = Object.entries(object);
+ if (entries.length < 1 || entries.length > MAX_KEYS) throw new Error(`RELAY_TOKEN_KEYS must hold 1 to ${MAX_KEYS} keys`);
+ const keys = new Map<string, KeyObject>();
+ for (const [kid, value] of entries) {
+ if (!KID.test(kid)) throw new Error("RELAY_TOKEN_KEYS has a key id that is not 1-16 of [A-Za-z0-9_-]");
+ if (!decodeB64u(value, 32)) throw new Error(`RELAY_TOKEN_KEYS.${kid} is not a base64url 32-byte Ed25519 public key`);
+ keys.set(kid, createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: value as string }, format: "jwk" }));
+ }
+ return keys;
+}
+
+/**
+ * Checks `b64u(payloadJSON) "." b64u(Ed25519 signature over the ASCII of the first part)`. The signature is checked
+ * before the payload is parsed, so nothing unauthenticated is interpreted, and the key that verified it must be the
+ * payload's `kid`.
+ */
+export function verifyToken(token: unknown, keys: ReadonlyMap<string, KeyObject>, nowSeconds: number): TokenResult {
+ if (typeof token !== "string" || token.length > MAX_TOKEN_CHARS) return { ok: false, reason: "malformed" };
+ const dot = token.indexOf(".");
+ if (dot <= 0 || dot !== token.lastIndexOf(".")) return { ok: false, reason: "malformed" };
+ const payloadPart = token.slice(0, dot);
+ const payloadBytes = decodeB64u(payloadPart);
+ const signature = decodeB64u(token.slice(dot + 1), 64);
+ if (!payloadBytes || !signature) return { ok: false, reason: "malformed" };
+
+ const signed = Buffer.from(payloadPart, "ascii");
+ let signer: string | undefined;
+ for (const [kid, key] of keys) {
+ if (verify(null, signed, key, signature)) {
+ signer = kid;
+ break;
+ }
+ }
+ if (!signer) return { ok: false, reason: "signature" };
+
+ const payload = parseObject(payloadBytes.toString("utf8"));
+ if (!payload || payload.v !== 1 || payload.kid !== signer) return { ok: false, reason: "claims" };
+ const hid = decodeB64u(payload.hid, 16);
+ const { iat, exp, iid } = payload;
+ if (!hid || typeof iid !== "string" || !IID.test(iid)) return { ok: false, reason: "claims" };
+ if (!Number.isSafeInteger(iat) || !Number.isSafeInteger(exp)) return { ok: false, reason: "claims" };
+ const issued = iat as number;
+ const expires = exp as number;
+ if (expires <= issued || expires - issued > TOKEN_LIFETIME_S || issued > nowSeconds + CLOCK_SKEW_S) {
+ return { ok: false, reason: "claims" };
+ }
+ if (nowSeconds >= expires) return { ok: false, reason: "expired" };
+ return { ok: true, claims: { kid: signer, hid, hidText: payload.hid as string, iid, iat: issued, exp: expires } };
+}
diff --git a/relay/src/wire.ts b/relay/src/wire.ts
new file mode 100644
index 0000000000..3aa7f6a21f
--- /dev/null
+++ b/relay/src/wire.ts
@@ -0,0 +1,88 @@
+import { createHash } from "node:crypto";
+
+/** The relay's WebSocket subprotocol. Every path requires it. */
+export const SUBPROTOCOL = "omb-relay.v1";
+
+/** Close codes the relay sends (wire spec §3.9). */
+export const Close = {
+ Malformed: 4400,
+ TokenInvalid: 4401,
+ NotFound: 4404,
+ NoDataSocket: 4408,
+ Replaced: 4409,
+ Limited: 4429,
+ Unavailable: 4503,
+} as const;
+
+/** Codes the two ends of a spliced session use with each other; the relay passes these through unchanged. */
+export const PASS_THROUGH_CODES: ReadonlySet<number> = new Set([1000, 1001, 4000, 4001, 4002]);
+
+const B64U = /^[A-Za-z0-9_-]*$/;
+
+/**
+ * Strict base64url without padding. Buffer.from(…, "base64url") skips characters it does not know and accepts stray
+ * trailing bits, so two different strings could name the same bytes; re-encoding and comparing makes the text canonical.
+ */
+export function decodeB64u(text: unknown, bytes?: number, maxChars = 4096): Buffer | undefined {
+ if (typeof text !== "string" || text.length > maxChars || !B64U.test(text)) return undefined;
+ const out = Buffer.from(text, "base64url");
+ if (out.toString("base64url") !== text) return undefined;
+ if (bytes !== undefined && out.length !== bytes) return undefined;
+ return out;
+}
+
+export const sha256 = (data: Buffer | string): Buffer => createHash("sha256").update(data).digest();
+
+/** A JSON object, or undefined for anything else (array, null, a primitive, or text that is not JSON). */
+export function parseObject(text: string): Record<string, unknown> | undefined {
+ let value: unknown;
+ try {
+ value = JSON.parse(text);
+ } catch {
+ return undefined;
+ }
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
+}
+
+export interface PhoneHello {
+ hid: Buffer;
+ hidText: string;
+ adm: Buffer;
+}
+
+/** `{"t":"phone","v":1,"hid":"<b64u 16 bytes>","adm":"<b64u 32 bytes>"}` */
+export function parsePhoneHello(message: Record<string, unknown>): PhoneHello | undefined {
+ if (message.t !== "phone" || message.v !== 1) return undefined;
+ const hid = decodeB64u(message.hid, 16);
+ const adm = decodeB64u(message.adm, 32);
+ if (!hid || !adm) return undefined;
+ return { hid, hidText: message.hid as string, adm };
+}
+
+/** `{"t":"auth","v":1,"token":"…"}`; the token itself is checked by verifyToken. */
+export function parseAuth(message: Record<string, unknown>): string | undefined {
+ if (message.t !== "auth" || message.v !== 1 || typeof message.token !== "string") return undefined;
+ return message.token;
+}
+
+/** `{"t":"data","v":1,"sid":"<b64u 16 bytes>","token":"…"}` */
+export function parseData(message: Record<string, unknown>): { sid: string; token: string } | undefined {
+ if (message.t !== "data" || message.v !== 1 || typeof message.token !== "string") return undefined;
+ if (!decodeB64u(message.sid, 16)) return undefined;
+ return { sid: message.sid as string, token: message.token };
+}
+
+/** `{"t":"admit","set":["<b64u SHA256(adm)>", …]}`, at most `max` distinct 32-byte entries. */
+export function parseAdmit(message: Record<string, unknown>, max: number): Buffer[] | undefined {
+ if (message.t !== "admit" || !Array.isArray(message.set) || message.set.length > max) return undefined;
+ const seen = new Set<string>();
+ const set: Buffer[] = [];
+ for (const entry of message.set) {
+ const hash = decodeB64u(entry, 32);
+ if (!hash) return undefined;
+ if (seen.has(entry as string)) continue;
+ seen.add(entry as string);
+ set.push(hash);
+ }
+ return set;
+}