213 lines
5.8 KiB
TypeScript
213 lines
5.8 KiB
TypeScript
import type Database from 'better-sqlite3';
|
|
|
|
export interface AuditEntryInput {
|
|
action: string;
|
|
actorIp: string;
|
|
sessionIdHash?: string | null;
|
|
target?: string | null;
|
|
status: 'ok' | 'denied' | 'error';
|
|
details?: Record<string, unknown> | string | null;
|
|
}
|
|
|
|
export interface AuditLogRecord {
|
|
id: number;
|
|
ts: number;
|
|
action: string;
|
|
actor_ip: string;
|
|
session_id_hash: string | null;
|
|
target: string | null;
|
|
status: string;
|
|
details: string | null;
|
|
}
|
|
|
|
export interface AuditListOptions {
|
|
limit?: number;
|
|
offset?: number;
|
|
action?: string;
|
|
actionPrefix?: string;
|
|
status?: 'ok' | 'denied' | 'error';
|
|
ip?: string;
|
|
target?: string;
|
|
q?: string;
|
|
from?: number;
|
|
to?: number;
|
|
}
|
|
|
|
function escapeLike(input: string): string {
|
|
return input.replace(/[\\%_]/g, '\\$&');
|
|
}
|
|
|
|
function sanitizeCsvCell(value: string): string {
|
|
const safe = /^[ \t]*[=+\-@\t\r]/.test(value) ? `'${value}` : value;
|
|
return `"${safe.replace(/"/g, '""')}"`;
|
|
}
|
|
|
|
export class AuditService {
|
|
private readonly insertStmt;
|
|
|
|
constructor(private readonly db: Database.Database) {
|
|
this.insertStmt = this.db.prepare(`
|
|
INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
`);
|
|
}
|
|
|
|
log(entry: AuditEntryInput): void {
|
|
const detailsText =
|
|
entry.details == null
|
|
? null
|
|
: typeof entry.details === 'string'
|
|
? entry.details
|
|
: JSON.stringify(entry.details);
|
|
|
|
this.insertStmt.run(
|
|
Date.now(),
|
|
entry.action,
|
|
entry.actorIp,
|
|
entry.sessionIdHash ?? null,
|
|
entry.target ?? null,
|
|
entry.status,
|
|
detailsText,
|
|
);
|
|
}
|
|
|
|
private buildWhereClause(options: AuditListOptions): { sql: string; params: Array<string | number> } {
|
|
const clauses: string[] = [];
|
|
const params: Array<string | number> = [];
|
|
|
|
if (options.action) {
|
|
clauses.push('action = ?');
|
|
params.push(options.action);
|
|
} else if (options.actionPrefix) {
|
|
clauses.push("action LIKE ? ESCAPE '\\'");
|
|
params.push(`${escapeLike(options.actionPrefix)}%`);
|
|
}
|
|
|
|
if (options.status) {
|
|
clauses.push('status = ?');
|
|
params.push(options.status);
|
|
}
|
|
|
|
if (options.ip) {
|
|
clauses.push('actor_ip = ?');
|
|
params.push(options.ip);
|
|
}
|
|
|
|
if (options.target) {
|
|
clauses.push("target LIKE ? ESCAPE '\\'");
|
|
params.push(`%${escapeLike(options.target)}%`);
|
|
}
|
|
|
|
if (typeof options.from === 'number' && Number.isFinite(options.from)) {
|
|
clauses.push('ts >= ?');
|
|
params.push(options.from);
|
|
}
|
|
if (typeof options.to === 'number' && Number.isFinite(options.to)) {
|
|
clauses.push('ts <= ?');
|
|
params.push(options.to);
|
|
}
|
|
|
|
if (options.q) {
|
|
const needle = `%${escapeLike(options.q)}%`;
|
|
clauses.push(
|
|
"(action LIKE ? ESCAPE '\\' OR actor_ip LIKE ? ESCAPE '\\' OR COALESCE(target, '') LIKE ? ESCAPE '\\' OR COALESCE(details, '') LIKE ? ESCAPE '\\')",
|
|
);
|
|
params.push(needle, needle, needle, needle);
|
|
}
|
|
|
|
return {
|
|
sql: clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '',
|
|
params,
|
|
};
|
|
}
|
|
|
|
list(options: AuditListOptions = {}): {
|
|
total: number;
|
|
items: AuditLogRecord[];
|
|
} {
|
|
const limit = Math.max(1, Math.min(200, options.limit ?? 50));
|
|
const offset = Math.max(0, options.offset ?? 0);
|
|
const where = this.buildWhereClause(options);
|
|
|
|
const countRow = this.db
|
|
.prepare(`SELECT COUNT(*) AS cnt FROM audit_log ${where.sql}`)
|
|
.get(...where.params) as { cnt: number };
|
|
|
|
const items = this.db
|
|
.prepare(
|
|
`SELECT id, ts, action, actor_ip, session_id_hash, target, status, details
|
|
FROM audit_log ${where.sql}
|
|
ORDER BY ts DESC, id DESC
|
|
LIMIT ? OFFSET ?`,
|
|
)
|
|
.all(...where.params, limit, offset) as AuditLogRecord[];
|
|
|
|
return { total: countRow.cnt, items };
|
|
}
|
|
|
|
listActions(): string[] {
|
|
const rows = this.db
|
|
.prepare('SELECT DISTINCT action FROM audit_log ORDER BY action ASC LIMIT 200')
|
|
.all() as Array<{ action: string }>;
|
|
return rows.map((r) => r.action);
|
|
}
|
|
|
|
exportRecords(
|
|
options: AuditListOptions,
|
|
format: 'csv' | 'ndjson',
|
|
maxRows = 10_000,
|
|
): string {
|
|
const cap = Math.max(1, Math.min(50_000, maxRows));
|
|
const where = this.buildWhereClause(options);
|
|
const rows = this.db
|
|
.prepare(
|
|
`SELECT id, ts, action, actor_ip, session_id_hash, target, status, details
|
|
FROM audit_log ${where.sql}
|
|
ORDER BY ts DESC, id DESC
|
|
LIMIT ?`,
|
|
)
|
|
.all(...where.params, cap) as AuditLogRecord[];
|
|
|
|
if (format === 'ndjson') {
|
|
return `${rows
|
|
.map((r) =>
|
|
JSON.stringify({
|
|
id: r.id,
|
|
ts: r.ts,
|
|
isoTime: new Date(r.ts).toISOString(),
|
|
action: r.action,
|
|
status: r.status,
|
|
actorIp: r.actor_ip,
|
|
target: r.target,
|
|
sessionIdHash: r.session_id_hash,
|
|
details: r.details,
|
|
}),
|
|
)
|
|
.join('\n')}\n`;
|
|
}
|
|
|
|
const lines = [
|
|
'id,ts,isoTime,action,status,actorIp,target,sessionIdHash,details',
|
|
...rows.map((r) =>
|
|
[
|
|
String(r.id),
|
|
String(r.ts),
|
|
sanitizeCsvCell(new Date(r.ts).toISOString()),
|
|
sanitizeCsvCell(r.action),
|
|
sanitizeCsvCell(r.status),
|
|
sanitizeCsvCell(r.actor_ip),
|
|
sanitizeCsvCell(r.target ?? ''),
|
|
sanitizeCsvCell(r.session_id_hash ?? ''),
|
|
sanitizeCsvCell(r.details ?? ''),
|
|
].join(','),
|
|
),
|
|
];
|
|
return `${lines.join('\n')}\n`;
|
|
}
|
|
|
|
pruneOlderThan(retentionDays: number): number {
|
|
const days = Math.max(1, retentionDays);
|
|
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
|
|
return this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(cutoff).changes;
|
|
}
|
|
}
|