// PEP-254 Access Hub: the journal is written before the action and can't be changed quietly // (hash chain + checkpoints outside the table), the owner exports and checks it; every connection // key sits under its own data key. Scenario names follow // openspec/changes/pep-254-access-hub-journal-integrity/specs/access-hub/spec.md. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { after, before, describe, test } from "node:test"; import { and, eq } from "drizzle-orm"; import { stripAsIs } from "@peppa/shared/i18n"; import type { ConnectionFetch } from "@peppa/core"; import { core, db, project, teardown } from "./helpers.ts"; process.env.PEPPA_SECRET = "mock-journal-secret-current"; delete process.env.PEPPA_SECRET_PREVIOUS; const { connections, connectionLog, agents, sessions, events, telegramOutbox } = await import("@peppa/db"); const KEY = "sk_live_mock_journal_111111"; const KEY_MAIL = "sk_live_mock_mail_222222"; let anna: Awaited>; let boris: Awaited>; before(async () => { anna = await core.upsertUserFromGitea(db, { id: 2541, login: "mock-j-anna" }, { access_token: "a" }); boris = await core.upsertUserFromGitea(db, { id: 2542, login: "mock-j-boris" }, { access_token: "b" }); process.env.PEPPA_PLATFORM_KEY = (await project({ turns: [] })).key; await db.update((await import("@peppa/db")).users).set({ telegramChatId: 254001 }).where(eq((await import("@peppa/db")).users.id, anna.id)); }); after(teardown); process.env.PEPPA_CONNECTIONS_UNISOLATED = "on"; /** A mock external service in-process: status per path, optional hang. */ function mockFetch(o: { status?: number; fail?: boolean } = {}): ConnectionFetch { return async ({ url }) => { if (o.fail) throw new Error("mock crash in the middle"); return { status: o.status ?? 200, contentType: "application/json", body: Buffer.from(JSON.stringify({ path: url.pathname })), truncated: false }; }; } async function setup(ownerId: number, name: string, secret = KEY) { const p = await project({ turns: [] }); const proj = await core.getProject(db, p.key); await core.setProjectOwner(db, proj.id, ownerId); const task = (await core.listTasks(db, { projectId: proj.id }))[0]!; const c = await core.createConnection(db, ownerId, { name, baseUrl: "https://crm.example.com/api", secret }); await core.grantConnection(db, ownerId, c.id, { projectId: proj.id, operations: "GET /items" }); const s = await core.createSession(db, { projectId: proj.id, taskId: task.id }); const [a] = await db.insert(agents).values({ name: `Мок-журнал ${s.id}` }).returning(); await db.update(sessions).set({ agentId: a!.id }).where(eq(sessions.id, s.id)); return { proj, c, sessionId: s.id }; } const ownerRows = (ownerId: number) => db.select().from(connectionLog).where(eq(connectionLog.ownerId, ownerId)).orderBy(connectionLog.id); describe("Журнал пишется до действия", () => { test("Итог дописывается после вызова", async () => { const { c, sessionId, proj } = await setup(anna.id, "CRM"); let seenRows = -1; const r = await core.callConnection(db, { sessionId, connection: "CRM", method: "GET", path: "/items/5" }, { fetch: async (req) => { // At the moment of the request the call is already in the journal. seenRows = (await db.select().from(connectionLog).where(and(eq(connectionLog.connectionId, c.id), eq(connectionLog.kind, "call")))).length; return mockFetch()(req); }, }); assert.equal(r.ok, true); assert.equal(seenRows, 1, "the call is written before the service is called"); const rows = (await ownerRows(anna.id)).filter((x) => x.connectionId === c.id); assert.deepEqual(rows.map((x) => x.kind), ["call", "result"]); assert.equal(rows[1]!.parentId, rows[0]!.id); assert.equal(rows[1]!.statusCode, 200); assert.equal(rows[0]!.projectKey, proj.key); const view = (await core.connectionJournal(db, anna.id, { connectionId: c.id }))[0]!; assert.equal(view.path, "/items/5"); assert.equal(view.statusCode, 200); assert.equal(view.state, "done"); assert.equal((await core.connectionJournal(db, anna.id, { connectionId: c.id })).length, 1, "the result joins its call on screen"); }); test("Сбой посередине виден", async () => { const { c, sessionId } = await setup(anna.id, "CRM-crash"); const t0 = new Date(); // The process «dies» between the call row and the result: simulate by dropping the result. await core.callConnection(db, { sessionId, connection: "CRM-crash", method: "GET", path: "/items/5" }, { fetch: mockFetch(), now: t0 }); const [res] = await db.select().from(connectionLog).where(and(eq(connectionLog.connectionId, c.id), eq(connectionLog.kind, "result"))); // A real crash leaves no result row; it is the last row of the chain, so removing it keeps the chain whole. await db.delete(connectionLog).where(eq(connectionLog.id, res!.id)); const soon = (await core.connectionJournal(db, anna.id, { connectionId: c.id, now: new Date(t0.getTime() + 1000) }))[0]!; assert.equal(soon.state, "running"); const later = (await core.connectionJournal(db, anna.id, { connectionId: c.id, now: new Date(t0.getTime() + 60_000) }))[0]!; assert.equal(later.state, "unfinished"); assert.equal((await core.verifyConnectionJournal(db, anna.id)).ok, true); }); test("Отказ — одна запись, лимит считает только вызовы", async () => { const { c, sessionId } = await setup(anna.id, "CRM-deny"); const r = await core.callConnection(db, { sessionId, connection: "CRM-deny", method: "DELETE", path: "/items/5" }, { fetch: mockFetch() }); assert.equal(r.ok, false); const rows = await db.select().from(connectionLog).where(eq(connectionLog.connectionId, c.id)); assert.equal(rows.length, 1); assert.equal(rows[0]!.decision, "denied"); }); }); describe("Журнал защищён от подделки", () => { test("Изменённая запись обнаруживается", async () => { const { sessionId } = await setup(boris.id, "CRM-b"); for (const p of ["/items/1", "/items/5", "/items/9"]) await core.callConnection(db, { sessionId, connection: "CRM-b", method: "GET", path: p }, { fetch: mockFetch() }); const before = await core.verifyConnectionJournal(db, boris.id); assert.equal(before.ok, true); assert.equal(before.checked, 6); const rows = await ownerRows(boris.id); const second = rows.find((r) => r.path === "/items/5" && r.kind === "call")!; await db.update(connectionLog).set({ path: "/items/6" }).where(eq(connectionLog.id, second.id)); const v = await core.verifyConnectionJournal(db, boris.id); assert.equal(v.ok, false); assert.equal(v.brokenAt, second.id); assert.equal(v.reason, "hash"); await db.update(connectionLog).set({ path: "/items/5" }).where(eq(connectionLog.id, second.id)); // A deleted row in the middle breaks the link. const third = rows.find((r) => r.path === "/items/9" && r.kind === "call")!; const saved = rows.find((r) => r.id === third.id)!; await db.delete(connectionLog).where(eq(connectionLog.id, third.id)); const d = await core.verifyConnectionJournal(db, boris.id); assert.equal(d.ok, false); assert.equal(d.reason, "link"); await db.insert(connectionLog).values(saved); assert.equal((await core.verifyConnectionJournal(db, boris.id)).ok, true); }); test("Пересчитанная цепочка не совпадает с контрольной точкой", async () => { const t0 = new Date("2026-11-24T10:00:00Z"); const r = await core.connectionJournalTick(db, { now: t0, force: true }); assert.ok(r.checkpoints >= 2, "a checkpoint per owner"); const cp = await core.getJournalCheckpoint(db, boris.id); assert.ok(cp); const [ev] = await db.select().from(events).where(eq(events.type, "connection_journal_checkpoint")); assert.ok(ev, "the checkpoint is in the platform journal"); // Rewrite a row before the checkpoint and recompute every hash after it. const rows = (await ownerRows(boris.id)).map(core.toRecord); rows[0]!.path = "/forged"; let prev = rows[0]!.prev_hash!; for (const r2 of rows) { r2.prev_hash = prev; r2.hash = core.journalHash(prev, r2); prev = r2.hash; await db.update(connectionLog).set({ path: r2.path, prevHash: r2.prev_hash, hash: r2.hash }).where(eq(connectionLog.id, r2.id)); } assert.equal(core.verifyJournalRows(rows).ok, true, "the chain alone looks fine"); const v = await core.verifyConnectionJournal(db, boris.id); assert.equal(v.ok, false); assert.equal(v.reason, "checkpoint"); }); test("Нарушение доходит до людей", async () => { const asel = await core.upsertUserFromGitea(db, { id: 2543, login: "mock-j-asel" }, { access_token: "c" }); const users = (await import("@peppa/db")).users; await db.update(users).set({ telegramChatId: 254003 }).where(eq(users.id, asel.id)); await core.setPlatformAdmins(db, ["mock-j-asel"]); await db.update(users).set({ telegramChatId: 254002 }).where(eq(users.id, boris.id)); const t1 = new Date("2026-11-24T12:00:00Z"); const r = await core.connectionJournalTick(db, { now: t1, force: true }); assert.deepEqual(r.broken, [boris.id]); const outbox = async (chat: number) => (await db.select().from(telegramOutbox)).filter((m) => (m.params as { chat_id?: number }).chat_id === chat); assert.equal((await outbox(254003)).length, 1, "the superadmin gets one message"); assert.equal((await outbox(254002)).length, 1, "the owner gets one message"); assert.match(stripAsIs(String((await outbox(254002))[0]!.params.text)), /изменён в обход FORGE/); await core.connectionJournalTick(db, { now: new Date(t1.getTime() + 3600_000), force: true }); assert.equal((await outbox(254003)).length, 1, "the same break is not reported again"); assert.equal((await outbox(254002)).length, 1); }); }); describe("Выгрузка журнала", () => { test("Выгрузка проверяется", async () => { const jsonl = await core.exportConnectionJournal(db, anna.id, "jsonl"); const rows = core.parseJournalJsonl(jsonl); const own = await ownerRows(anna.id); assert.equal(rows.length, own.length); assert.ok(rows.every((r) => typeof r.hash === "string" && typeof r.prev_hash === "string")); assert.equal(core.verifyJournalRows(rows).ok, true); // The script from the page checks the file on its own. const dir = mkdtempSync(join(tmpdir(), "mock-journal-")); writeFileSync(join(dir, "journal.jsonl"), jsonl); writeFileSync(join(dir, "verify.mjs"), core.JOURNAL_VERIFY_SCRIPT); assert.match(execFileSync(process.execPath, [join(dir, "verify.mjs"), join(dir, "journal.jsonl")], { encoding: "utf8" }), /^ok, head [0-9a-f]{64}/m); const forged = jsonl.replace('"/items/5"', '"/items/6"'); writeFileSync(join(dir, "journal.jsonl"), forged); assert.match(execFileSync(process.execPath, [join(dir, "verify.mjs"), join(dir, "journal.jsonl")], { encoding: "utf8" }), /journal changed/); const csv = await core.exportConnectionJournal(db, anna.id, "csv"); assert.equal(csv.trim().split("\n").length, own.length + 1); assert.match(csv.split("\n")[0]!, /prev_hash,hash$/); }); test("Чужой журнал не выгружается", async () => { const mine = core.parseJournalJsonl(await core.exportConnectionJournal(db, anna.id, "jsonl")); assert.ok(mine.every((r) => r.owner_id === anna.id)); assert.ok(!mine.some((r) => r.connection === "CRM-b")); }); }); describe("Отдельный ключ шифрования у каждого подключения", () => { test("Ключ данных одного подключения не открывает другое", async () => { const a = await core.createConnection(db, anna.id, { name: "CRM-env", baseUrl: "https://crm.example.com/api", secret: KEY }); const b = await core.createConnection(db, anna.id, { name: "Почта", baseUrl: "https://mail.example.com/api", secret: KEY_MAIL }); const [ra] = await db.select().from(connections).where(eq(connections.id, a.id)); const [rb] = await db.select().from(connections).where(eq(connections.id, b.id)); assert.ok(ra!.dekEnc && rb!.dekEnc && ra!.dekEnc !== rb!.dekEnc); assert.ok(ra!.secretEnc!.startsWith("v2.")); assert.equal(core.openConnectionSecret(ra!), KEY); assert.equal(core.openConnectionSecret(rb!), KEY_MAIL); assert.throws(() => core.openConnectionSecret({ secretEnc: rb!.secretEnc, dekEnc: ra!.dekEnc }), "CRM's data key does not open Почта"); assert.throws(() => core.decrypt(rb!.secretEnc!.slice(3)), "the platform key alone does not open a key either"); }); test("Старое подключение переводится на свой ключ", async () => { const c = await core.createConnection(db, anna.id, { name: "CRM-old", baseUrl: "https://crm.example.com/api", secret: KEY }); // As stored before PEP-254: the key itself under PEPPA_SECRET, no data key. await db.update(connections).set({ secretEnc: core.encrypt(KEY), dekEnc: null }).where(eq(connections.id, c.id)); const [old] = await db.select().from(connections).where(eq(connections.id, c.id)); assert.equal(core.openConnectionSecret(old!), KEY, "old rows still work before the move"); const r = await core.upgradeConnectionKeys(db); assert.ok(r.upgraded >= 1); const [moved] = await db.select().from(connections).where(eq(connections.id, c.id)); assert.ok(moved!.dekEnc && moved!.secretEnc!.startsWith("v2.")); assert.equal(core.openConnectionSecret(moved!), KEY); assert.equal((await core.upgradeConnectionKeys(db)).upgraded, 0, "idempotent"); }); test("Ротация ключа платформы", async () => { const { c, sessionId } = await setup(anna.id, "CRM-rot"); const [beforeRow] = await db.select().from(connections).where(eq(connections.id, c.id)); process.env.PEPPA_SECRET_PREVIOUS = process.env.PEPPA_SECRET; process.env.PEPPA_SECRET = "mock-journal-secret-next"; try { const r = await core.reencryptAll(db, "mock-j-asel"); assert.ok(r.reencrypted >= 1); assert.equal(r.unreadable.length, 0); const [afterRow] = await db.select().from(connections).where(eq(connections.id, c.id)); assert.notEqual(afterRow!.dekEnc, beforeRow!.dekEnc, "the data key is re-encrypted"); assert.equal(afterRow!.secretEnc, beforeRow!.secretEnc, "the encrypted key itself is untouched"); delete process.env.PEPPA_SECRET_PREVIOUS; assert.equal(core.encryptedWith(afterRow!.dekEnc!), "current"); let auth = ""; const res = await core.callConnection(db, { sessionId, connection: "CRM-rot", method: "GET", path: "/items" }, { fetch: async (req) => { auth = req.headers.Authorization ?? req.headers.authorization ?? ""; return mockFetch()(req); }, }); assert.equal(res.ok, true); assert.equal(auth, `Bearer ${KEY}`); } finally { delete process.env.PEPPA_SECRET_PREVIOUS; } }); }); describe("Старый журнал получает цепочку", () => { test("Записи до изменения связываются при переводе", async () => { const carl = await core.upsertUserFromGitea(db, { id: 2544, login: "mock-j-carl" }, { access_token: "d" }); const c = await core.createConnection(db, carl.id, { name: "Old", baseUrl: "https://crm.example.com/api", secret: KEY }); for (const p of ["/a", "/b"]) await db.insert(connectionLog).values({ ownerId: carl.id, connectionId: c.id, connectionName: "Old", method: "GET", path: p, decision: "allowed", statusCode: 200, createdAt: new Date() }); assert.equal((await core.verifyConnectionJournal(db, carl.id)).unprotected, 2); assert.equal(await core.upgradeConnectionJournal(db), 2); const v = await core.verifyConnectionJournal(db, carl.id); assert.equal(v.ok, true); assert.equal(v.checked, 2); assert.equal(await core.upgradeConnectionJournal(db), 0, "idempotent"); }); });