feat(bot): add audit log writer

This commit is contained in:
yiekheng 2026-05-09 16:12:53 +08:00
parent 4a790b9a60
commit 3f3b090caa
2 changed files with 54 additions and 0 deletions

View File

@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import type { DB } from "./db.js";
import { writeAuditLog } from "./audit.js";
describe("writeAuditLog", () => {
it("inserts a row with normalized fields", async () => {
const inserted: unknown[] = [];
const fakeDb = {
insert: () => ({
values: (v: unknown) => {
inserted.push(v);
return Promise.resolve();
},
}),
} as unknown as DB;
await writeAuditLog(fakeDb, {
operatorId: null,
source: "telegram",
action: "test.event",
payload: { foo: "bar" },
});
expect(inserted).toHaveLength(1);
expect(inserted[0]).toMatchObject({
operatorId: null,
source: "telegram",
action: "test.event",
payload: { foo: "bar" },
});
});
});

22
apps/bot/src/audit.ts Normal file
View File

@ -0,0 +1,22 @@
import { auditLog, type DB, type NewAuditLogEntry } from "@cmbot/db";
export type AuditInput = {
operatorId: string | null;
source: "web" | "telegram" | "system";
action: string;
targetType?: string | null;
targetId?: string | null;
payload?: Record<string, unknown>;
};
export async function writeAuditLog(db: DB, input: AuditInput): Promise<void> {
const row: NewAuditLogEntry = {
operatorId: input.operatorId,
source: input.source,
action: input.action,
targetType: input.targetType ?? null,
targetId: input.targetId ?? null,
payload: input.payload ?? {},
};
await db.insert(auditLog).values(row);
}