229 lines
12 KiB
TypeScript
229 lines
12 KiB
TypeScript
// PEP-225: one WebSocket per tab — subscriptions with access checks, events only for their own
|
||
// scope with the changed task rows, catching up after a drop, the terminal (output and input)
|
||
// over the socket, limits, and the upgrade itself (login, origin).
|
||
import assert from "node:assert/strict";
|
||
import { createServer, type Server } from "node:http";
|
||
import type { AddressInfo } from "node:net";
|
||
import { after, describe, test } from "node:test";
|
||
import { createLiveWs, LiveConnection, LIVE_WS_RATE_MAX, type LiveWs } from "@peppa/runner/live-ws";
|
||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
after(teardown);
|
||
|
||
let seq = 0;
|
||
const user = (login: string) => core.upsertUserFromGitea(db, { id: 9100 + seq++, login }, { access_token: "x" });
|
||
type Msg = Record<string, unknown> & { t: string };
|
||
|
||
/** A connection driven directly: what the server sent and how it closed. */
|
||
function conn(u: import("@peppa/core").User) {
|
||
const out: Msg[] = [];
|
||
const closed: Array<{ code: number; reason: string }> = [];
|
||
const c = new LiveConnection(db, u, (m) => out.push(m as Msg), (code, reason) => closed.push({ code, reason }));
|
||
const send = (m: object) => c.receive(JSON.stringify(m));
|
||
return { c, out, closed, send };
|
||
}
|
||
|
||
async function ownedStory(login: string) {
|
||
const owner = await user(login);
|
||
const p = await project({ turns: [] });
|
||
const ref = await core.resolveTask(db, p.taskKey);
|
||
await core.setProjectOwner(db, ref.project.id, owner.id);
|
||
return { owner, p, ref };
|
||
}
|
||
|
||
describe("tab channel (PEP-225)", () => {
|
||
test("Подписка без прав: ответ 404, события не приходят", async () => {
|
||
const { ref } = await ownedStory("ws-owner-1");
|
||
const outsider = await user("ws-outsider-1");
|
||
const x = conn(outsider);
|
||
await x.send({ t: "sub", scope: `task:${ref.task.id}` });
|
||
assert.deepEqual(x.out.at(-1), { t: "err", scope: `task:${ref.task.id}`, status: 404, error: "Не найдено" });
|
||
await x.send({ t: "sub", scope: "observe" });
|
||
assert.equal(x.out.at(-1)!.status, 404, "observe — only a superadmin");
|
||
await x.send({ t: "sub", scope: "nonsense" });
|
||
assert.equal(x.out.at(-1)!.status, 400);
|
||
assert.deepEqual(x.c.scopes, []);
|
||
x.c.close();
|
||
});
|
||
|
||
test("Событие доходит только до своей области — со строкой задачи", async () => {
|
||
const a = await ownedStory("ws-owner-2");
|
||
const b = await core.createTask(db, { projectId: a.ref.project.id, title: "Соседняя задача" });
|
||
const x = conn(a.owner);
|
||
await x.send({ t: "sub", scope: `task:${a.ref.task.id}` });
|
||
assert.equal(x.out.at(-1)!.t, "ok");
|
||
try {
|
||
await core.updateTask(db, b, { status: "in_progress" });
|
||
await runner.liveHub(db).check();
|
||
assert.equal(x.out.filter((m) => m.t === "ev").length, 0, "another story is not this scope");
|
||
|
||
await core.updateTask(db, a.ref, { status: "review" });
|
||
await runner.liveHub(db).check();
|
||
const ev = x.out.find((m) => m.t === "ev") as Msg & { tasks?: Array<{ id: number; status: string; column: string }>; parts: string[] };
|
||
assert.ok(ev, "change of the story arrives");
|
||
assert.equal(ev.type, "change");
|
||
assert.ok(ev.parts.includes("t"));
|
||
assert.deepEqual(ev.tasks?.map((r) => [r.id, r.status, r.column]), [[a.ref.task.id, "review", "review"]]);
|
||
} finally {
|
||
x.c.close();
|
||
}
|
||
assert.ok(!runner.liveHub(db).watched.includes(`task:${a.ref.task.id}`), "closing the tab unsubscribes");
|
||
});
|
||
|
||
test("Доска проекта: смена статуса — строка без пометки other, новая задача — с пометкой", async () => {
|
||
const a = await ownedStory("ws-owner-3");
|
||
const x = conn(a.owner);
|
||
const scope = `project:${a.ref.project.id}`;
|
||
await x.send({ t: "sub", scope });
|
||
try {
|
||
await core.updateTask(db, a.ref, { status: "in_progress" });
|
||
await runner.liveHub(db).check();
|
||
const first = x.out.filter((m) => m.t === "ev").at(-1) as Msg & { tasks: Array<{ id: number; other?: boolean; column: string }> };
|
||
assert.deepEqual(first.tasks.map((r) => [r.id, r.column, r.other ?? false]), [[a.ref.task.id, "in_progress", false]]);
|
||
const fresh = (await core.createTask(db, { projectId: a.ref.project.id, title: "Новая" })).task;
|
||
await runner.liveHub(db).check();
|
||
const second = x.out.filter((m) => m.t === "ev").at(-1) as Msg & { tasks: Array<{ id: number; other?: boolean }> };
|
||
assert.deepEqual(second.tasks.map((r) => [r.id, r.other]), [[fresh.id, true]], "a new card can't be drawn in place");
|
||
} finally {
|
||
x.c.close();
|
||
}
|
||
});
|
||
|
||
test("Связь пропала: переподключение с since догоняет пропущенное, без изменений — тишина", async () => {
|
||
const a = await ownedStory("ws-owner-4");
|
||
const scope = `project:${a.ref.project.id}`;
|
||
const first = conn(a.owner);
|
||
await first.send({ t: "sub", scope });
|
||
const v1 = first.out.find((m) => m.t === "ok")!.v as string;
|
||
assert.ok(v1, "ok carries the version");
|
||
first.c.close(); // the drop
|
||
|
||
// Nothing changed: no event on re-subscribe. A watcher keeps the scope alive meanwhile.
|
||
const keep = conn(a.owner);
|
||
await keep.send({ t: "sub", scope });
|
||
const same = conn(a.owner);
|
||
await same.send({ t: "sub", scope, since: v1 });
|
||
assert.equal(same.out.filter((m) => m.t === "ev").length, 0);
|
||
same.c.close();
|
||
|
||
await core.updateTask(db, a.ref, { status: "review" });
|
||
await runner.liveHub(db).check();
|
||
const back = conn(a.owner);
|
||
await back.send({ t: "sub", scope, since: v1 });
|
||
const ev = back.out.find((m) => m.t === "ev") as Msg & { parts: string[] };
|
||
assert.ok(ev, "the missed change arrives at once");
|
||
assert.deepEqual(ev.parts, ["*"]);
|
||
back.c.close();
|
||
keep.c.close();
|
||
});
|
||
|
||
test("Шаги агента после since приходят при переподключении", async () => {
|
||
const a = await ownedStory("ws-owner-5");
|
||
const s = await core.createSession(db, { projectId: a.ref.project.id, taskId: a.ref.task.id });
|
||
await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "one", ok: true });
|
||
const keep = conn(a.owner);
|
||
await keep.send({ t: "sub", scope: `steps:${s.id}` });
|
||
const seen = (await db.$client.prepare(`SELECT max(id) AS id FROM events WHERE session_id = ? AND type = 'step'`).get(s.id)) as { id: number };
|
||
await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "two", ok: true });
|
||
await runner.liveHub(db).check();
|
||
const back = conn(a.owner);
|
||
await back.send({ t: "sub", scope: `steps:${s.id}`, since: seen.id });
|
||
const steps = back.out.filter((m) => m.t === "ev" && m.type === "step").map((m) => (m.step as { text: string }).text);
|
||
assert.deepEqual(steps, ["two"]);
|
||
back.c.close();
|
||
keep.c.close();
|
||
});
|
||
|
||
test("Значение области: attention отдаёт текущее при подписке и новое при изменении", async () => {
|
||
const a = await ownedStory("ws-owner-6");
|
||
let n = 1;
|
||
runner.setLiveProvider("attention", (_db, uid) => ({ count: uid === a.owner.id ? n : -1, sound: false }));
|
||
const x = conn(a.owner);
|
||
await x.send({ t: "sub", scope: "attention" });
|
||
await waitFor("first value", async () => x.out.some((m) => m.t === "ev" && m.type === "data"));
|
||
assert.deepEqual((x.out.find((m) => m.type === "data")!.data as { count: number }).count, 1);
|
||
n = 2;
|
||
await core.askPm(db, a.ref, { kind: "question", text: "Какой цвет?" });
|
||
await runner.liveHub(db).check();
|
||
await waitFor("new value", async () => x.out.filter((m) => m.type === "data").length === 2);
|
||
assert.equal((x.out.filter((m) => m.type === "data")[1]!.data as { count: number }).count, 2);
|
||
x.c.close();
|
||
});
|
||
|
||
test("Терминал через сокет: кадр, ввод с подтверждением, завершённая сессия — отказ", async () => {
|
||
const a = await ownedStory("ws-owner-7");
|
||
const s = await core.createSession(db, { projectId: a.ref.project.id, taskId: a.ref.task.id });
|
||
const name = `peppa-wsterm-${process.pid}`;
|
||
await core.updateSession(db, s.id, { tmuxName: name, status: "running" });
|
||
await runner.tmux.newSession({ name, cwd: a.p.dir, command: `sh -c 'while read l; do echo "got:$l"; done'`, env: {}, width: 100 });
|
||
const x = conn(a.owner);
|
||
const scope = `terminal:${s.id}`;
|
||
try {
|
||
await x.send({ t: "sub", scope });
|
||
assert.equal(x.out.at(-1)!.t, "ok");
|
||
await waitFor("frame", async () => x.out.some((m) => m.t === "ev" && m.type === "frame"));
|
||
await x.send({ t: "in", scope, keys: "hi\r", id: 1 });
|
||
assert.deepEqual(x.out.find((m) => m.t === "ack"), { t: "ack", id: 1 });
|
||
await waitFor("echo", async () => (await runner.tmux.capturePane(name)).includes("got:hi"));
|
||
await waitFor("echo over the socket", async () => x.out.some((m) => m.t === "ev" && (m.type === "out" || m.type === "frame") && String(m.data).includes("got:hi")));
|
||
|
||
const outsider = conn(await user("ws-outsider-7"));
|
||
await outsider.send({ t: "sub", scope });
|
||
assert.equal(outsider.out.at(-1)!.status, 404);
|
||
await outsider.send({ t: "in", scope, keys: "rm\r", id: 9 });
|
||
assert.ok(outsider.out.find((m) => m.t === "ack" && m.id === 9)!.error, "no input without access");
|
||
|
||
await core.updateSession(db, s.id, { status: "done", endedAt: new Date() });
|
||
await x.send({ t: "in", scope, keys: "late\r", id: 2 });
|
||
assert.ok((x.out.find((m) => m.t === "ack" && m.id === 2) as Msg).error, "finished session refuses input");
|
||
} finally {
|
||
x.c.close();
|
||
await runner.tmux.killSession(name).catch(() => {});
|
||
}
|
||
});
|
||
|
||
test("Сообщения слишком часто: соединение закрывается 1008", async () => {
|
||
const x = conn(await user("ws-spammer"));
|
||
const now = Date.now();
|
||
for (let i = 0; i <= LIVE_WS_RATE_MAX; i++) await x.c.receive(JSON.stringify({ t: "ping" }), now);
|
||
assert.deepEqual(x.closed, [{ code: 1008, reason: "rate" }]);
|
||
x.c.close();
|
||
});
|
||
|
||
test("Апгрейд: без входа 401, чужой сайт 403, свой — hello и подписка", async () => {
|
||
const owner = await user("ws-http-owner");
|
||
const ws: LiveWs = createLiveWs({ db, authenticate: async (req) => (req.headers.cookie === "peppa_session=good" ? owner : null), boot: () => "boot-1" });
|
||
const server: Server = createServer((_req, res) => res.end());
|
||
server.on("upgrade", (req, socket, head) => ws.handleUpgrade(req, socket, head));
|
||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||
const port = (server.address() as AddressInfo).port;
|
||
const url = `ws://127.0.0.1:${port}/api/ws`;
|
||
const open = (headers: Record<string, string>) =>
|
||
new Promise<{ ok: boolean; msgs: Msg[]; sock: WebSocket }>((resolve) => {
|
||
const sock = new (WebSocket as unknown as new (u: string, o: object) => WebSocket)(url, { headers });
|
||
const msgs: Msg[] = [];
|
||
sock.onmessage = (e) => msgs.push(JSON.parse(String(e.data)));
|
||
sock.onopen = () => resolve({ ok: true, msgs, sock });
|
||
sock.onerror = () => resolve({ ok: false, msgs, sock });
|
||
});
|
||
try {
|
||
assert.equal((await open({})).ok, false, "no login");
|
||
assert.equal((await open({ cookie: "peppa_session=good", origin: "https://evil.example" })).ok, false, "foreign origin");
|
||
const good = await open({ cookie: "peppa_session=good", origin: `http://127.0.0.1:${port}` });
|
||
assert.ok(good.ok);
|
||
await waitFor("hello", async () => good.msgs.some((m) => m.t === "hello"));
|
||
assert.equal(good.msgs[0]!.boot, "boot-1");
|
||
good.sock.send(JSON.stringify({ t: "sub", scope: "home" }));
|
||
good.sock.send(JSON.stringify({ t: "ping" }));
|
||
await waitFor("ok + pong", async () => good.msgs.some((m) => m.t === "ok") && good.msgs.some((m) => m.t === "pong"));
|
||
assert.equal(ws.clients, 1);
|
||
good.sock.close();
|
||
await waitFor("closed", async () => ws.clients === 0);
|
||
} finally {
|
||
ws.close();
|
||
server.close();
|
||
}
|
||
});
|
||
});
|