2026-07-06 10:47:16 -05:00
|
|
|
import type { Db } from '../types/db';
|
|
|
|
|
|
refactor(server): migrate middleware, workers, and db layer to TypeScript (.cts)
- middleware/ (5): requireAuth, securityHeaders, errorFormatter, csrf,
rateLimiter — fully typed against the shared http Req/Res/Next types.
- workers/dailyWorker — fully typed.
- db/ (4): database, subscriptionCatalogSeed, migrations/versionedMigrations,
migrations/legacyReconcileMigrations — large dynamic schema/migration infra,
converted with @ts-nocheck (typing deferred). All requires updated to .cts.
Behavior-preserving. Verified: typecheck:server 0, check:server 0, suite 226/226.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 11:34:08 -05:00
|
|
|
const { getDb } = require('../db/database.cts');
|
2026-07-06 16:05:18 -05:00
|
|
|
const { log } = require('../utils/logger.cts');
|
2026-05-10 00:03:12 -05:00
|
|
|
|
2026-07-06 10:47:16 -05:00
|
|
|
interface AuditParams {
|
|
|
|
|
user_id?: number | null;
|
|
|
|
|
action: string;
|
|
|
|
|
entity_type?: string | null;
|
|
|
|
|
entity_id?: number | null;
|
|
|
|
|
details?: any;
|
|
|
|
|
ip_address?: string | null;
|
|
|
|
|
user_agent?: string | null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-10 00:03:12 -05:00
|
|
|
/**
|
|
|
|
|
* Log a security-sensitive action to the audit_log table.
|
|
|
|
|
*/
|
2026-07-06 14:23:53 -05:00
|
|
|
function logAudit({
|
|
|
|
|
user_id,
|
|
|
|
|
action,
|
|
|
|
|
entity_type,
|
|
|
|
|
entity_id,
|
|
|
|
|
details,
|
|
|
|
|
ip_address,
|
|
|
|
|
user_agent,
|
|
|
|
|
}: AuditParams): void {
|
2026-07-06 10:47:16 -05:00
|
|
|
const db: Db = getDb();
|
2026-05-10 00:03:12 -05:00
|
|
|
try {
|
|
|
|
|
db.prepare(
|
|
|
|
|
`INSERT INTO audit_log (user_id, action, entity_type, entity_id, details_json, ip_address, user_agent)
|
2026-07-06 14:23:53 -05:00
|
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
2026-05-10 00:03:12 -05:00
|
|
|
).run(
|
|
|
|
|
user_id || null,
|
|
|
|
|
action,
|
|
|
|
|
entity_type || null,
|
|
|
|
|
entity_id || null,
|
|
|
|
|
details ? JSON.stringify(details) : null,
|
|
|
|
|
ip_address || null,
|
2026-07-06 14:23:53 -05:00
|
|
|
user_agent || null,
|
2026-05-10 00:03:12 -05:00
|
|
|
);
|
2026-07-06 10:47:16 -05:00
|
|
|
} catch (err: any) {
|
2026-05-10 00:03:12 -05:00
|
|
|
// Audit logging should never crash the app
|
2026-07-06 16:05:18 -05:00
|
|
|
log.error('[audit-error] Failed to log audit event:', err.message);
|
2026-05-10 00:03:12 -05:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-06 10:47:16 -05:00
|
|
|
module.exports = { logAudit };
|