Add thread audit replay controls
This commit is contained in:
1 parent
bbf90a1a62
commit
6768d19239
19 files changed
+299
-3
No files matched your search
@@ -18,6 +18,7 @@ import { SearchService } from "../services/search-service";
|
||||
import { IdentityAccessService } from "../services/identity-access-service";
|
||||
import { OperationsService } from "../services/operations-service";
|
||||
import { SdlcService } from "../services/sdlc-service";
|
||||
import { AuditService } from "../services/audit-service";
|
||||
|
||||
export interface IpcDeps {
|
||||
connection: DatabaseConnection;
|
||||
@@ -40,6 +41,7 @@ export function registerIpcHandlers(deps: IpcDeps): void {
|
||||
const identityAccess = new IdentityAccessService(deps.connection.db);
|
||||
const operations = new OperationsService(deps.connection.db);
|
||||
const sdlc = new SdlcService(deps.connection.db);
|
||||
const audit = new AuditService(deps.connection.db);
|
||||
const onboarding = new OnboardingService({
|
||||
db: deps.connection.db,
|
||||
saveProviderCredential: (input) => providers.saveCredential(input),
|
||||
@@ -163,6 +165,7 @@ export function registerIpcHandlers(deps: IpcDeps): void {
|
||||
ipcMain.handle(IPC_CHANNELS.runEvalSuite, (_event, input) => mutate(() => sdlc.runEvalSuite(input)));
|
||||
ipcMain.handle(IPC_CHANNELS.setPrBotGate, (_event, input) => mutate(() => sdlc.setPrBotGate(input)));
|
||||
ipcMain.handle(IPC_CHANNELS.createComplianceExport, (_event, input) => mutate(() => compliance.createExport(input)));
|
||||
ipcMain.handle(IPC_CHANNELS.createAuditReplay, (_event, input) => mutate(() => audit.createThreadReplay(input)));
|
||||
ipcMain.handle(IPC_CHANNELS.createLegalHold, (_event, input) => mutate(() => compliance.createLegalHold(input)));
|
||||
ipcMain.handle(IPC_CHANNELS.setLegalHoldState, (_event, input) => mutate(() => compliance.setLegalHoldState(input)));
|
||||
ipcMain.handle(IPC_CHANNELS.createRetentionFreeze, (_event, input) => mutate(() => compliance.createRetentionFreeze(input)));
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
export const auditReplaySchema = `
|
||||
create table if not exists audit_replay_runs (
|
||||
id text primary key,
|
||||
org_id text not null references organizations(id) on delete cascade,
|
||||
thread_id text not null references chat_threads(id) on delete cascade,
|
||||
event_count integer not null,
|
||||
event_digest text not null,
|
||||
replay_json text not null,
|
||||
created_by_employee_id text references employees(id) on delete set null,
|
||||
created_at text not null
|
||||
);
|
||||
|
||||
create index if not exists idx_audit_replay_runs_org_created on audit_replay_runs(org_id, created_at);
|
||||
create index if not exists idx_audit_replay_runs_thread on audit_replay_runs(thread_id, created_at);
|
||||
|
||||
insert into schema_migrations(version, name, applied_at)
|
||||
values (19, 'audit_replay', datetime('now'));
|
||||
`;
|
||||
@@ -17,6 +17,7 @@ import { identityAccessSchema } from "./migrations/015-identity-access";
|
||||
import { orgGovernanceSchema } from "./migrations/016-org-governance";
|
||||
import { operationsControlsSchema } from "./migrations/017-operations-controls";
|
||||
import { sdlcControlsSchema } from "./migrations/018-sdlc-controls";
|
||||
import { auditReplaySchema } from "./migrations/019-audit-replay";
|
||||
|
||||
interface Migration {
|
||||
version: number;
|
||||
@@ -43,6 +44,7 @@ const MIGRATIONS: Migration[] = [
|
||||
{ version: 16, name: "org_governance", sql: orgGovernanceSchema },
|
||||
{ version: 17, name: "operations_controls", sql: operationsControlsSchema },
|
||||
{ version: 18, name: "sdlc_controls", sql: sdlcControlsSchema },
|
||||
{ version: 19, name: "audit_replay", sql: auditReplaySchema },
|
||||
];
|
||||
|
||||
const SCHEMA_VERSION = MIGRATIONS[MIGRATIONS.length - 1].version;
|
||||
|
||||
@@ -1,6 +1,36 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import type { CreateAuditReplayInput } from "../../shared/commands";
|
||||
import { createId } from "../../shared/ids";
|
||||
|
||||
interface AuditEventRow {
|
||||
id: string;
|
||||
org_id: string;
|
||||
entity_type: string;
|
||||
entity_id: string;
|
||||
actor_type: string;
|
||||
actor_id: string | null;
|
||||
action: string;
|
||||
payload_json: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface ChatThreadRow {
|
||||
id: string;
|
||||
root_message_id: string | null;
|
||||
}
|
||||
|
||||
interface ReplayEvent {
|
||||
id: string;
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
actorType: string;
|
||||
actorId: string | null;
|
||||
action: string;
|
||||
payload: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export class AuditService {
|
||||
constructor(private readonly db: DatabaseSync) {}
|
||||
|
||||
@@ -28,4 +58,98 @@ export class AuditService {
|
||||
new Date().toISOString(),
|
||||
);
|
||||
}
|
||||
|
||||
createThreadReplay(input: CreateAuditReplayInput): string {
|
||||
const thread = this.requireThread(input.orgId, input.threadId);
|
||||
this.requireEmployee(input.orgId, input.createdByEmployeeId);
|
||||
const messageIds = this.threadMessageIds(input.orgId, input.threadId, thread.root_message_id);
|
||||
const events = this.threadEvents(input.orgId, input.threadId, messageIds);
|
||||
if (events.length === 0) throw new Error("Thread replay requires audit events.");
|
||||
const replay = {
|
||||
threadId: input.threadId,
|
||||
rootMessageId: thread.root_message_id,
|
||||
messageIds: [...messageIds].sort(),
|
||||
events,
|
||||
};
|
||||
const replayJson = JSON.stringify(replay);
|
||||
const eventDigest = createHash("sha256").update(replayJson).digest("hex");
|
||||
const id = createId("arp");
|
||||
const now = new Date().toISOString();
|
||||
this.db.prepare(`
|
||||
insert into audit_replay_runs(
|
||||
id, org_id, thread_id, event_count, event_digest, replay_json,
|
||||
created_by_employee_id, created_at
|
||||
) values (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(id, input.orgId, input.threadId, events.length, eventDigest, replayJson, input.createdByEmployeeId, now);
|
||||
this.record({
|
||||
orgId: input.orgId,
|
||||
entityType: "audit_replay_run",
|
||||
entityId: id,
|
||||
actorType: "employee",
|
||||
actorId: input.createdByEmployeeId,
|
||||
action: "created",
|
||||
payload: { threadId: input.threadId, eventCount: events.length, eventDigest },
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
private requireThread(orgId: string, threadId: string): ChatThreadRow {
|
||||
const thread = this.db.prepare("select id, root_message_id from chat_threads where id = ? and org_id = ?")
|
||||
.get(threadId, orgId) as ChatThreadRow | undefined;
|
||||
if (!thread) throw new Error("Chat thread was not found.");
|
||||
return thread;
|
||||
}
|
||||
|
||||
private requireEmployee(orgId: string, employeeId: string): void {
|
||||
const employee = this.db.prepare("select id from employees where id = ? and org_id = ?").get(employeeId, orgId);
|
||||
if (!employee) throw new Error("Audit replay employee was not found.");
|
||||
}
|
||||
|
||||
private threadMessageIds(orgId: string, threadId: string, rootMessageId: string | null): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
if (rootMessageId) ids.add(rootMessageId);
|
||||
const rows = this.db.prepare("select id from chat_messages where org_id = ? and thread_id = ? order by created_at asc")
|
||||
.all(orgId, threadId) as Array<{ id: string }>;
|
||||
for (const row of rows) ids.add(row.id);
|
||||
return ids;
|
||||
}
|
||||
|
||||
private threadEvents(orgId: string, threadId: string, messageIds: Set<string>): ReplayEvent[] {
|
||||
const rows = this.db.prepare("select * from audit_events where org_id = ? order by created_at asc, id asc")
|
||||
.all(orgId) as unknown as AuditEventRow[];
|
||||
return rows
|
||||
.filter((row) => eventMatchesThread(row, threadId, messageIds))
|
||||
.map((row) => ({
|
||||
id: row.id,
|
||||
entityType: row.entity_type,
|
||||
entityId: row.entity_id,
|
||||
actorType: row.actor_type,
|
||||
actorId: row.actor_id,
|
||||
action: row.action,
|
||||
payload: parsePayload(row.payload_json),
|
||||
createdAt: row.created_at,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
function eventMatchesThread(row: AuditEventRow, threadId: string, messageIds: Set<string>): boolean {
|
||||
if (row.entity_type === "audit_replay_run") return false;
|
||||
if (row.entity_type === "chat_thread" && row.entity_id === threadId) return true;
|
||||
if (row.entity_type === "chat_message" && messageIds.has(row.entity_id)) return true;
|
||||
const payload = parsePayload(row.payload_json);
|
||||
return stringField(payload, "threadId") === threadId
|
||||
|| stringField(payload, "sourceThreadId") === threadId
|
||||
|| messageIds.has(stringField(payload, "messageId"))
|
||||
|| messageIds.has(stringField(payload, "sourceMessageId"));
|
||||
}
|
||||
|
||||
function parsePayload(payloadJson: string): Record<string, unknown> {
|
||||
const parsed = JSON.parse(payloadJson) as unknown;
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("Audit event payload is invalid.");
|
||||
return parsed as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function stringField(payload: Record<string, unknown>, key: string): string {
|
||||
const value = payload[key];
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
@@ -70,6 +70,7 @@ const LEGACY_TABLES = [
|
||||
"legal_holds",
|
||||
"retention_freezes",
|
||||
"search_documents",
|
||||
"audit_replay_runs",
|
||||
"audit_events",
|
||||
];
|
||||
|
||||
@@ -222,6 +223,9 @@ const RELATION_CHECKS: RelationCheck[] = [
|
||||
{ table: "legal_holds", column: "created_by_employee_id", referencedTable: "employees", referencedColumn: "id", reason: "dangling_creator_employee_id" },
|
||||
{ table: "retention_freezes", column: "org_id", referencedTable: "organizations", referencedColumn: "id", reason: "dangling_org_id" },
|
||||
{ table: "retention_freezes", column: "created_by_employee_id", referencedTable: "employees", referencedColumn: "id", reason: "dangling_creator_employee_id" },
|
||||
{ table: "audit_replay_runs", column: "org_id", referencedTable: "organizations", referencedColumn: "id", reason: "dangling_org_id" },
|
||||
{ table: "audit_replay_runs", column: "thread_id", referencedTable: "chat_threads", referencedColumn: "id", reason: "dangling_thread_id" },
|
||||
{ table: "audit_replay_runs", column: "created_by_employee_id", referencedTable: "employees", referencedColumn: "id", reason: "dangling_creator_employee_id" },
|
||||
{ table: "audit_events", column: "org_id", referencedTable: "organizations", referencedColumn: "id", reason: "dangling_org_id" },
|
||||
];
|
||||
|
||||
|
||||
@@ -245,7 +245,7 @@ export class SdlcService {
|
||||
const schemaVersion = count(this.db, "select coalesce(max(version), 0) as count from schema_migrations");
|
||||
return [
|
||||
{ key: "provider_adapter_coverage", passed: missing.length === 0, value: `${adapterKeys.length}/${catalogKeys.length}` },
|
||||
{ key: "schema_version", passed: schemaVersion >= 18, value: schemaVersion },
|
||||
{ key: "schema_version", passed: schemaVersion >= 19, value: schemaVersion },
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -121,6 +121,7 @@ export class SnapshotService {
|
||||
evalCases: list(this.db, "eval_cases", "title asc"),
|
||||
evalRuns: list(this.db, "eval_runs", "created_at desc"),
|
||||
prBotGates,
|
||||
auditReplayRuns: list(this.db, "audit_replay_runs", "created_at desc"),
|
||||
auditEvents: list<AppSnapshot["auditEvents"][number]>(this.db, "audit_events", "created_at desc").slice(0, 200),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user