← back to Patty

lib/audit.ts

37 lines

import { query } from './db';

/**
 * Log an audit event to the audit_events table.
 *
 * @param eventType   - e.g. 'petition.created', 'signature.added', 'login', 'campaign.sent'
 * @param entityType  - e.g. 'petition', 'user', 'campaign', 'signature'
 * @param entityId    - primary key of the affected entity (nullable)
 * @param metadata    - arbitrary JSON payload with extra context
 * @param ipAddress   - client IP if available
 */
export async function auditLog(
  eventType: string,
  entityType: string,
  entityId: string | null,
  metadata?: Record<string, unknown>,
  ipAddress?: string,
): Promise<void> {
  const metaJson = metadata ? JSON.stringify(metadata) : null;

  console.log(
    `[audit] ${eventType} | ${entityType} | ${entityId ?? '(none)'} | ip=${ipAddress ?? 'unknown'}`,
    metadata ? JSON.stringify(metadata) : '',
  );

  try {
    await query(
      `INSERT INTO audit_events (event_type, entity_type, entity_id, metadata, ip_address)
       VALUES ($1, $2, $3, $4, $5)`,
      [eventType, entityType, entityId, metaJson, ipAddress ?? null],
    );
  } catch (err) {
    // Audit failures should never crash the calling operation
    console.error('[audit] Failed to write audit event:', (err as Error).message);
  }
}