// PEP-254: the Access Hub journal can't be changed quietly. // Every row of an owner carries the hash of the owner's previous row and its own: // hash = sha256(prev_hash + "\n" + JSON.stringify([id, owner_id, kind, parent_id, connection, // project, agent, method, path, decision, reason, status_code, duration_ms, created_at])) // (created_at in ms; the first row of an owner has prev_hash ""). Foreign keys are not hashed — // they turn null when a connection, project or session is deleted; their name snapshots are. // The hash has no key, so an owner can check an export alone; rewriting the whole chain is caught // by daily checkpoints kept outside the table (platform journal + the «services» channel). import { asIs, m as tr } from "@peppa/shared/i18n"; import { connectionLog, projects, users, type Db } from "@peppa/db"; import { and, asc, desc, eq, isNotNull, isNull, sql } from "drizzle-orm"; import { createHash } from "node:crypto"; import { logEvent } from "./audit.ts"; import { addMasterMessage } from "./chats.ts"; import { alertAdmins } from "./monitor.ts"; import { deliverToUser } from "./notifications.ts"; import { platformProjectKey, postToChannel } from "./platform-channel.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; export type ConnectionJournalKind = "call" | "result"; export type ConnectionJournalDecision = "allowed" | "denied" | "failed"; /** What a gateway decision writes; ids and the hash are added by `appendJournal`. */ export interface ConnectionJournalEntry { ownerId: number; kind: ConnectionJournalKind; parentId?: number | null; connectionId: number | null; connectionName: string | null; projectId?: number | null; projectKey?: string | null; sessionId?: number | null; agentId?: number | null; agentName?: string | null; method: string; path: string; decision: ConnectionJournalDecision; reason: string | null; statusCode: number | null; durationMs?: number | null; createdAt: Date; } /** One row as exported and as hashed (snake_case — the same names as in the file). */ export interface ConnectionJournalRecord { id: number; owner_id: number; kind: ConnectionJournalKind; parent_id: number | null; connection: string | null; project: string | null; agent: string | null; method: string; path: string; decision: ConnectionJournalDecision; reason: string | null; status_code: number | null; duration_ms: number | null; created_at: number; prev_hash: string | null; hash: string | null; } export function journalCanonical(r: Omit): string { return JSON.stringify([r.id, r.owner_id, r.kind, r.parent_id, r.connection, r.project, r.agent, r.method, r.path, r.decision, r.reason, r.status_code, r.duration_ms, r.created_at]); } export const journalHash = (prevHash: string, r: Omit): string => createHash("sha256").update(`${prevHash}\n${journalCanonical(r)}`).digest("hex"); type LogRow = typeof connectionLog.$inferSelect; export const toRecord = (r: LogRow): ConnectionJournalRecord => ({ id: r.id, owner_id: r.ownerId!, kind: r.kind, parent_id: r.parentId ?? null, connection: r.connectionName ?? null, project: r.projectKey ?? null, agent: r.agentName ?? null, method: r.method, path: r.path, decision: r.decision, reason: r.reason ?? null, status_code: r.statusCode ?? null, duration_ms: r.durationMs ?? null, created_at: r.createdAt.getTime(), prev_hash: r.prevHash ?? null, hash: r.hash ?? null, }); /** * Appends one row to the owner's chain. One synchronous transaction (BEGIN IMMEDIATE): reading * the head and inserting can't interleave with another call of the same owner. */ export function appendJournal(db: Db, e: ConnectionJournalEntry): number { return db.transaction((tx) => { const head = tx .select({ hash: connectionLog.hash }) .from(connectionLog) .where(and(eq(connectionLog.ownerId, e.ownerId), isNotNull(connectionLog.hash))) .orderBy(desc(connectionLog.id)) .limit(1) .get(); const projectKey = e.projectKey ?? (e.projectId ? (tx.select({ key: projects.key }).from(projects).where(eq(projects.id, e.projectId)).get()?.key ?? null) : null); const prevHash = head?.hash ?? ""; const row = tx .insert(connectionLog) .values({ ownerId: e.ownerId, kind: e.kind, parentId: e.parentId ?? null, connectionId: e.connectionId, connectionName: e.connectionName, projectId: e.projectId ?? null, projectKey, sessionId: e.sessionId ?? null, agentId: e.agentId ?? null, agentName: e.agentName ?? null, method: e.method, path: e.path, decision: e.decision, reason: e.reason, statusCode: e.statusCode, durationMs: e.durationMs ?? null, createdAt: e.createdAt, prevHash, }) .returning() .get(); const hash = journalHash(prevHash, toRecord(row)); tx.update(connectionLog).set({ hash }).where(eq(connectionLog.id, row.id)).run(); return row.id; }); } export type ConnectionJournalBreak = "hash" | "link" | "missing_hash" | "checkpoint"; export interface ConnectionJournalVerdict { ok: boolean; /** Rows checked (hashed ones). */ checked: number; /** Rows written before the journal was protected (no hash, before the first hashed row). */ unprotected: number; head: { id: number; hash: string } | null; first: { id: number; hash: string } | null; brokenAt?: number; reason?: ConnectionJournalBreak; } /** * Checks a chain (rows of ONE owner, any order). Leading rows without a hash are older than * PEP-254 and are not checked; the first hashed row anchors the chain (its prev_hash is taken). * Works on exported records too — the same code an owner could run. */ export function verifyJournalRows(input: ConnectionJournalRecord[]): ConnectionJournalVerdict { const rows = [...input].sort((a, b) => a.id - b.id); let i = 0; while (i < rows.length && rows[i]!.hash == null) i++; const out: ConnectionJournalVerdict = { ok: true, checked: 0, unprotected: i, head: null, first: null }; let prev: string | null = null; for (; i < rows.length; i++) { const r = rows[i]!; const fail = (reason: ConnectionJournalBreak) => ({ ...out, ok: false, brokenAt: r.id, reason }); if (r.hash == null || r.prev_hash == null) return fail("missing_hash"); if (prev !== null && r.prev_hash !== prev) return fail("link"); if (journalHash(r.prev_hash, r) !== r.hash) return fail("hash"); if (!out.first) out.first = { id: r.id, hash: r.hash }; out.head = { id: r.id, hash: r.hash }; prev = r.hash; out.checked++; } return out; } export interface ConnectionJournalCheckpoint { id: number; hash: string; firstId: number; firstHash: string; at: number; } const checkpointKey = (ownerId: number) => `connection.journal.checkpoint:${ownerId}`; const brokenKey = (ownerId: number) => `connection.journal.broken:${ownerId}`; export const getJournalCheckpoint = (db: Db, ownerId: number) => getSetting(db, checkpointKey(ownerId)); async function ownerRows(db: Db, ownerId: number): Promise { return (await db.select().from(connectionLog).where(eq(connectionLog.ownerId, ownerId)).orderBy(asc(connectionLog.id))).map(toRecord); } /** * The owner's chain plus the last checkpoint: the row it names must still be there with the same * hash, and so must the first row — a chain rewritten from scratch doesn't pass. */ export async function verifyConnectionJournal(db: Db, ownerId: number): Promise { const rows = await ownerRows(db, ownerId); const v = verifyJournalRows(rows); if (!v.ok) return v; const cp = await getJournalCheckpoint(db, ownerId); if (cp) { const byId = new Map(rows.map((r) => [r.id, r])); if (byId.get(cp.firstId)?.hash !== cp.firstHash) return { ...v, ok: false, brokenAt: cp.firstId, reason: "checkpoint" }; if (byId.get(cp.id)?.hash !== cp.hash) return { ...v, ok: false, brokenAt: cp.id, reason: "checkpoint" }; } return v; } /** * Gives a hash chain to owners whose journal has none yet (rows from before PEP-254). Owners that * already have a chain keep their older rows as «before protection». */ export async function upgradeConnectionJournal(db: Db): Promise { const owners = await db .select({ ownerId: connectionLog.ownerId }) .from(connectionLog) .where(isNotNull(connectionLog.ownerId)) .groupBy(connectionLog.ownerId) .having(sql`count(${connectionLog.hash}) = 0`); let n = 0; for (const { ownerId } of owners) { n += db.transaction((tx) => { if (tx.select({ id: connectionLog.id }).from(connectionLog).where(and(eq(connectionLog.ownerId, ownerId!), isNotNull(connectionLog.hash))).limit(1).get()) return 0; const rows = tx.select().from(connectionLog).where(and(eq(connectionLog.ownerId, ownerId!), isNull(connectionLog.hash))).orderBy(asc(connectionLog.id)).all(); let prev = ""; for (const r of rows) { const hash = journalHash(prev, toRecord(r)); tx.update(connectionLog).set({ prevHash: prev, hash }).where(eq(connectionLog.id, r.id)).run(); prev = hash; } return rows.length; }); } return n; } // ---------- export ---------- export const JOURNAL_EXPORT_FIELDS = ["id", "owner_id", "kind", "parent_id", "connection", "project", "agent", "method", "path", "decision", "reason", "status_code", "duration_ms", "created_at", "prev_hash", "hash"] as const; const csvCell = (v: unknown) => { if (v == null) return ""; const s = String(v); // A leading = + - @ would be a formula in a spreadsheet: quote it with an apostrophe. const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s; return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe; }; /** The owner's whole journal with hashes, oldest first. Only the owner's own rows. */ export async function exportConnectionJournal(db: Db, ownerId: number, format: "jsonl" | "csv"): Promise { const rows = await ownerRows(db, ownerId); if (format === "jsonl") return rows.map((r) => JSON.stringify(Object.fromEntries(JOURNAL_EXPORT_FIELDS.map((f) => [f, r[f]])))).join("\n") + (rows.length ? "\n" : ""); return [JOURNAL_EXPORT_FIELDS.join(","), ...rows.map((r) => JOURNAL_EXPORT_FIELDS.map((f) => csvCell(r[f])).join(","))].join("\n") + "\n"; } /** Reads an exported JSONL back (for checking it). */ export const parseJournalJsonl = (text: string): ConnectionJournalRecord[] => text .split("\n") .filter((l) => l.trim()) .map((l) => JSON.parse(l) as ConnectionJournalRecord); /** A self-contained Node script that checks an exported JSONL (shown on the «Подключения» page). */ export const JOURNAL_VERIFY_SCRIPT = `// node verify.mjs journal.jsonl import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; const rows = readFileSync(process.argv[2], "utf8").split("\\n").filter(Boolean).map((l) => JSON.parse(l)); let prev = null, bad = 0; for (const r of rows) { if (r.hash == null) continue; // written before the protection const body = JSON.stringify([r.id, r.owner_id, r.kind, r.parent_id, r.connection, r.project, r.agent, r.method, r.path, r.decision, r.reason, r.status_code, r.duration_ms, r.created_at]); const h = createHash("sha256").update(r.prev_hash + "\\n" + body).digest("hex"); if ((prev !== null && r.prev_hash !== prev) || h !== r.hash) { console.log("BROKEN at id", r.id); bad++; break; } prev = r.hash; } console.log(bad ? "journal changed" : "ok, head " + prev); `; // ---------- daily checkpoint and check ---------- const CHECKPOINT_EVERY_MS = 24 * 3600_000; const TICK_EVERY_MS = 3600_000; let lastTick = 0; export interface ConnectionJournalTickResult { checked: number; checkpoints: number; broken: number[]; } /** * Watchdog, once an hour: moves old keys and journals onto PEP-254, checks every owner's chain, * once a day per owner writes a checkpoint (platform journal event + one «services» channel post * for the day). A broken chain — one message to the superadmins and to the owner per break. */ export async function connectionJournalTick(db: Db, o: { now?: Date; force?: boolean; log?: (m: string) => void } = {}): Promise { const now = o.now ?? new Date(); const out: ConnectionJournalTickResult = { checked: 0, checkpoints: 0, broken: [] }; if (process.env.PEPPA_CONNECTION_JOURNAL === "off") return out; if (!o.force && now.getTime() - lastTick < TICK_EVERY_MS) return out; lastTick = now.getTime(); const log = o.log ?? (() => {}); const { upgradeConnectionKeys } = await import("./connections.ts"); await upgradeConnectionKeys(db).catch(() => null); await upgradeConnectionJournal(db); const owners = (await db.select({ ownerId: connectionLog.ownerId }).from(connectionLog).where(isNotNull(connectionLog.hash)).groupBy(connectionLog.ownerId)).map((r) => r.ownerId!); const [platform] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, platformProjectKey())); const heads: string[] = []; for (const ownerId of owners) { out.checked++; const v = await verifyConnectionJournal(db, ownerId); if (!v.ok) { out.broken.push(ownerId); await reportBreak(db, ownerId, v, log); continue; } await deleteSetting(db, brokenKey(ownerId)); const cp = await getJournalCheckpoint(db, ownerId); if (!v.head || !v.first) continue; if (cp && (cp.id === v.head.id || now.getTime() - cp.at < CHECKPOINT_EVERY_MS)) continue; const next: ConnectionJournalCheckpoint = { id: v.head.id, hash: v.head.hash, firstId: v.first.id, firstHash: v.first.hash, at: now.getTime() }; await setSetting(db, checkpointKey(ownerId), next); if (platform) await logEvent(db, { projectId: platform.id, type: "connection_journal_checkpoint", payload: { ownerId, headId: next.id, headHash: next.hash, firstId: next.firstId, firstHash: next.firstHash } }); heads.push(`u${ownerId} #${next.id} ${next.hash.slice(0, 16)}`); out.checkpoints++; } if (heads.length) { // glossary-ignore: the «services» channel is read by the platform's engineers. const html = `${tr("Журнал подключений: контрольные точки")}\n${heads.join("\n")}`; await postToChannel(db, "services", `mon:ch:connection-journal:${now.toISOString().slice(0, 13)}`, html).catch(() => false); } return out; } async function reportBreak(db: Db, ownerId: number, v: ConnectionJournalVerdict, log: (m: string) => void): Promise { const seen = await getSetting<{ id: number }>(db, brokenKey(ownerId)); if (seen?.id === v.brokenAt) return; // already told about this break await setSetting(db, brokenKey(ownerId), { id: v.brokenAt, reason: v.reason, at: Date.now() }); const [u] = await db.select().from(users).where(eq(users.id, ownerId)); const [platform] = await db.select({ id: projects.id }).from(projects).where(eq(projects.key, platformProjectKey())); if (platform) await logEvent(db, { projectId: platform.id, type: "connection_journal_broken", payload: { ownerId, id: v.brokenAt, reason: v.reason } }); const admin = tr("Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.", { login: asIs(u?.login ?? `#${ownerId}`), id: v.brokenAt ?? 0 }); await alertAdmins(db, `connection-journal:${ownerId}:${v.brokenAt}`, admin, log).catch(() => 0); if (!u || u.disabledAt) return; const text = tr("Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения»."); const key = `connection-journal:${ownerId}:${v.brokenAt}`; await addMasterMessage(db, ownerId, { kind: "event", important: true, text, dedupeKey: `master:${key}`, url: "/connections" }).catch(() => null); await deliverToUser(db, u, { event: "failures", dedupeKey: `${key}:${u.telegramChatId}`, pushKey: `${key}:u${u.id}`, telegram: { params: { text } }, push: { title: tr("FORGE"), body: text, url: "/connections", tag: "connection-journal" }, }).catch(() => null); }