peppa/packages/runner/src/live-ws.ts
peppa-bot fa63f2eece
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 45с
peppa/build build: success за 31с
peppa/test test: success за 1277с
peppa-ci / ci (pull_request) Successful in 23m10s
PEP-224: статус функций из мониторинга (сведено с main после PEP-225)
Функция → мониторинги (core/feature-status.ts), серая кнопка входа через eGov и статус MCP,
отказ startEgovFlow, журнал и сообщения в канал. После переезда живых обновлений на
WebSocket (PEP-225): область `features` в LIVE_PLAIN_SCOPES, открыта без входа (SSE и
WebSocket с `anonymous: true` — только открытые области), смотрится по таймеру вместе с
`observe`, смена сбрасывает кэш статусов.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 05:34:54 +00:00

276 lines
11 KiB
TypeScript

// One WebSocket per browser tab (PEP-225): `GET /api/ws` carries every live scope of the tab —
// the hub's scopes (live.ts) and the runner terminal (terminal.ts, output and input) — instead of
// an SSE stream per page part. The web's own server (apps/web/server.ts) hands the upgrade here;
// the protocol itself (LiveConnection) knows nothing of the transport, tests drive it directly.
//
// Client → server: {t:"sub", scope, since?} · {t:"unsub", scope} · {t:"in", scope:"terminal:<id>", keys?|paste?, id} · {t:"ping"}
// Server → client: {t:"hello", boot} · {t:"ok", scope, v?} · {t:"err", scope?, status, error} · {t:"ev", scope, type, …} · {t:"ack", id, error?} · {t:"pong"}
import type { IncomingMessage } from "node:http";
import type { Duplex } from "node:stream";
import { WebSocketServer, type WebSocket } from "ws";
import { m } from "@peppa/shared/i18n";
import { PeppaError, projectSecretMasker, type User } from "@peppa/core";
import type { Db } from "@peppa/db";
import * as tmux from "./tmux.ts";
import { checkScopeAccess, LIVE_MAX_SCOPES, LIVE_PING_MS, liveHub, LiveError, parseScope, type LiveScope } from "./live.ts";
import { acquireViewer, terminalInput, terminalSession, watchTerminal } from "./terminal.ts";
/** Largest message from a client: a 64 KB paste in JSON with escapes. */
export const LIVE_WS_MAX_PAYLOAD = 300_000;
/** Client messages per window before the socket is closed (1008). */
export const LIVE_WS_RATE_MAX = 60;
export const LIVE_WS_RATE_WINDOW_MS = 5000;
export const LIVE_WS_PATH = "/api/ws";
type Out = Record<string, unknown>;
/** One tab's connection: its subscriptions, input and limits. */
export class LiveConnection {
private subs = new Map<LiveScope, () => void>();
private pending = new Set<LiveScope>();
private window = { start: 0, n: 0 };
private input: Promise<void> = Promise.resolve();
private closed = false;
private db: Db;
/** null — a tab without a sign-in (PEP-224): only open scopes (`features`) pass checkScopeAccess. */
private user: User | null;
private out: (msg: Out) => void;
private kill: (code: number, reason: string) => void;
constructor(db: Db, user: User | null, out: (msg: Out) => void, kill: (code: number, reason: string) => void) {
this.db = db;
this.user = user;
this.out = out;
this.kill = kill;
}
private send(msg: Out) {
if (!this.closed) this.out(msg);
}
/** Handles one text message; returns once it is dealt with (tests await it). */
async receive(raw: string, now = Date.now()): Promise<void> {
if (this.closed) return;
if (now - this.window.start >= LIVE_WS_RATE_WINDOW_MS) this.window = { start: now, n: 0 };
if (++this.window.n > LIVE_WS_RATE_MAX) return this.kill(1008, "rate");
let msg: { t?: unknown; scope?: unknown; since?: unknown; keys?: unknown; paste?: unknown; id?: unknown };
try {
msg = JSON.parse(raw);
} catch {
return this.send({ t: "err", status: 400, error: m("Неверный JSON") });
}
if (msg.t === "ping") return this.send({ t: "pong" });
const scopeRaw = typeof msg.scope === "string" ? msg.scope : "";
let scope: LiveScope;
try {
scope = parseScope(scopeRaw);
} catch (e) {
return this.send({ t: "err", scope: scopeRaw, status: 400, error: (e as Error).message });
}
if (msg.t === "sub") return this.subscribe(scope, typeof msg.since === "string" || typeof msg.since === "number" ? msg.since : undefined);
if (msg.t === "unsub") return this.unsubscribe(scope);
if (msg.t === "in") return this.terminalIn(scope, msg);
this.send({ t: "err", scope, status: 400, error: m("Неизвестное сообщение") });
}
private async subscribe(scope: LiveScope, since: string | number | undefined) {
if (this.subs.has(scope) || this.pending.has(scope)) return this.send({ t: "ok", scope });
if (this.subs.size + this.pending.size >= LIVE_MAX_SCOPES) return this.send({ t: "err", scope, status: 429, error: m("Слишком много областей") });
this.pending.add(scope);
try {
await checkScopeAccess(this.db, this.user, scope);
const stop = scope.startsWith("terminal:") ? await this.watchTerminal(scope) : this.watchHub(scope, since);
// Unsubscribed (or closed) while access was checked.
if (!this.pending.has(scope) || this.closed) return stop();
this.subs.set(scope, stop);
this.send({ t: "ok", scope, v: scope.startsWith("terminal:") ? undefined : liveHub(this.db).versionOf(scope, this.user?.id ?? 0) });
} catch (e) {
const status = e instanceof LiveError ? e.status : (e as { status?: number }).status ?? 500;
if (status === 500) console.error(`live-ws: ${scope}`, e);
this.send({ t: "err", scope, status, error: e instanceof LiveError || e instanceof PeppaError ? e.message : m("Ошибка потока") });
} finally {
this.pending.delete(scope);
}
}
private watchHub(scope: LiveScope, since: string | number | undefined): () => void {
return liveHub(this.db).subscribe([scope], (e) => this.send({ t: "ev", ...e }), { userId: this.user?.id ?? 0, since: { [scope]: since } });
}
/** The runner terminal (PEP-9): the shared TerminalFeed of the pane, secrets masked, viewers per user limited. */
private async watchTerminal(scope: LiveScope): Promise<() => void> {
if (!this.user) throw new LiveError(m("Нужен вход"), 401);
const s = await terminalSession(this.db, this.user, Number(scope.slice(9)));
const mask = await projectSecretMasker(this.db, s.projectId);
const release = acquireViewer(this.user.id);
let done = false;
const stopFeed = watchTerminal(
tmux.sessionPane(s),
(e) => {
this.send({ t: "ev", scope, ...e });
if (e.type === "end") queueMicrotask(() => this.unsubscribe(scope));
},
{ mask },
);
return () => {
if (done) return;
done = true;
stopFeed();
release();
};
}
private unsubscribe(scope: LiveScope) {
this.pending.delete(scope);
const stop = this.subs.get(scope);
this.subs.delete(scope);
stop?.();
}
/** Keyboard input / paste of the terminal: in order, with the PEP-9 checks and limits. */
private terminalIn(scope: LiveScope, msg: { keys?: unknown; paste?: unknown; id?: unknown }) {
const id = typeof msg.id === "number" || typeof msg.id === "string" ? msg.id : null;
// glossary-ignore: the runner terminal is the engineer's view (PEP-9).
if (!scope.startsWith("terminal:")) return this.send({ t: "ack", id, error: m("Ввод — только в терминал") });
const input = { keys: typeof msg.keys === "string" ? msg.keys : undefined, paste: typeof msg.paste === "string" ? msg.paste : undefined };
const run = async () => {
try {
if (!this.user) throw new LiveError(m("Нужен вход"), 401);
await terminalInput(this.db, this.user, Number(scope.slice(9)), input);
this.send({ t: "ack", id });
} catch (e) {
// glossary-ignore: the runner terminal is the engineer's view (PEP-9).
this.send({ t: "ack", id, error: e instanceof PeppaError || e instanceof LiveError ? e.message : m("Ошибка терминала") });
if (!(e instanceof PeppaError)) console.error("live-ws: terminal input", e);
}
};
this.input = this.input.then(run);
return this.input;
}
get scopes(): LiveScope[] {
return [...this.subs.keys()];
}
close() {
if (this.closed) return;
this.closed = true;
for (const stop of this.subs.values()) stop();
this.subs.clear();
this.pending.clear();
}
}
/** Same-site only: the cookie is `lax`, a WebSocket from another site would carry it. */
export function sameOriginUpgrade(req: IncomingMessage): boolean {
const origin = req.headers.origin;
if (!origin) return true; // not a browser
const host = (req.headers["x-forwarded-host"] as string | undefined)?.split(",")[0]?.trim() || req.headers.host;
try {
return new URL(origin).host === host;
} catch {
return false;
}
}
export interface LiveWsOptions {
db: Db;
/** The signed-in user of the request (cookie `peppa_session`), or null. */
authenticate: (req: IncomingMessage) => Promise<User | null>;
/** Boot id of the web process (the client compares it after a reconnect). */
boot?: () => string;
pingMs?: number;
/** PEP-224: let a tab without a sign-in in — it can watch open scopes only (the login page watches `features`). */
anonymous?: boolean;
}
export interface LiveWs {
handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void;
readonly clients: number;
close(): void;
}
function refuse(socket: Duplex, status: number, text: string) {
try {
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
} catch {}
socket.destroy();
}
/** The WebSocket endpoint: auth and origin before the upgrade, a ping every 15 s, one LiveConnection per socket. */
export function createLiveWs(opts: LiveWsOptions): LiveWs {
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: LIVE_WS_MAX_PAYLOAD });
const alive = new WeakMap<WebSocket, number>();
const pingMs = opts.pingMs ?? LIVE_PING_MS;
// Two pings without a pong: the connection is dead (a sleeping phone, a dropped proxy).
const pinger = setInterval(() => {
for (const ws of wss.clients) {
const missed = (alive.get(ws) ?? 0) + 1;
if (missed > 2) {
ws.terminate();
continue;
}
alive.set(ws, missed);
try {
ws.ping();
} catch {}
}
}, pingMs);
pinger.unref?.();
wss.on("connection", (ws: WebSocket, _req: IncomingMessage, user: User | null) => {
alive.set(ws, 0);
const conn = new LiveConnection(
opts.db,
user,
(msg) => {
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg));
},
(code, reason) => ws.close(code, reason),
);
ws.on("pong", () => alive.set(ws, 0));
ws.on("message", (data, isBinary) => {
alive.set(ws, 0);
if (isBinary) return ws.close(1003, "text only");
void conn.receive(data.toString());
});
ws.on("close", () => conn.close());
ws.on("error", () => conn.close());
ws.send(JSON.stringify({ t: "hello", boot: opts.boot?.() ?? "" }));
});
return {
handleUpgrade(req, socket, head) {
socket.on("error", () => socket.destroy());
if (!sameOriginUpgrade(req)) return refuse(socket, 403, "Forbidden");
opts
.authenticate(req)
.then((user) => {
if (!user && !opts.anonymous) return refuse(socket, 401, "Unauthorized");
wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req, user));
})
.catch((e) => {
console.error("live-ws: upgrade", e);
refuse(socket, 500, "Internal Server Error");
});
},
get clients() {
return wss.clients.size;
},
close() {
clearInterval(pinger);
for (const ws of wss.clients) ws.terminate();
wss.close();
},
};
}
/** Reads one cookie from a raw Cookie header. */
export function readCookie(header: string | undefined, name: string): string | undefined {
for (const part of (header ?? "").split(";")) {
const i = part.indexOf("=");
if (i > 0 && part.slice(0, i).trim() === name) return decodeURIComponent(part.slice(i + 1).trim());
}
return undefined;
}