feat(audit,backup,cli): upgrade Audit Log, harden async Backup + scheduled backups & CLI tools
This commit is contained in:
parent
1b2e425a00
commit
9a27525def
8 changed files with 1590 additions and 222 deletions
|
|
@ -20,6 +20,28 @@ export interface AuditLogRecord {
|
|||
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;
|
||||
|
||||
|
|
@ -49,33 +71,143 @@ export class AuditService {
|
|||
);
|
||||
}
|
||||
|
||||
list(options: { limit?: number; offset?: number; action?: string } = {}): {
|
||||
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);
|
||||
|
||||
if (options.action) {
|
||||
const countRow = this.db
|
||||
.prepare('SELECT COUNT(*) AS cnt FROM audit_log WHERE action = ?')
|
||||
.get(options.action) as { cnt: number };
|
||||
const items = this.db
|
||||
.prepare(
|
||||
'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log WHERE action = ? ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?',
|
||||
)
|
||||
.all(options.action, limit, offset) as AuditLogRecord[];
|
||||
return { total: countRow.cnt, items };
|
||||
}
|
||||
const where = this.buildWhereClause(options);
|
||||
|
||||
const countRow = this.db
|
||||
.prepare('SELECT COUNT(*) AS cnt FROM audit_log')
|
||||
.get() as { cnt: number };
|
||||
.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 ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?',
|
||||
`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(limit, offset) as AuditLogRecord[];
|
||||
.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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue