import { getDbClient } from "./client.server.js"; import type { Log, Prisma } from "./prisma-browser.js"; export type AdminAuditLogFilters = { q?: string | null; action?: string | null; url?: string | null; tenantId?: string | null; userId?: string | null; createdAtFrom?: string | Date | null; createdAtTo?: string | Date | null; }; export type AdminAuditLogListArgs = AdminAuditLogFilters & { take?: number | null; skip?: number | null; }; export type TenantAuditLogFilters = Omit & { tenantId?: string | null; }; export type TenantAuditLogListArgs = TenantAuditLogFilters & { take?: number | null; skip?: number | null; }; export type AdminAuditLogRow = Log & { tenant?: { id: string; name: string; slug?: string | null } | null; user?: { id: string; email: string; firstName?: string | null; lastName?: string | null } | null; apiKey?: { id: string; alias: string } | null; }; export type AdminAuditLogListResult = { rows: AdminAuditLogRow[]; total: number; take: number; skip: number; }; export type AdminAuditLogClient = { log: { findMany(args: { where: Prisma.LogWhereInput; include: typeof adminAuditLogInclude; orderBy: Prisma.LogOrderByWithRelationInput; take: number; skip: number; }): Promise; count(args: { where: Prisma.LogWhereInput }): Promise; }; }; export const adminAuditLogInclude = { user: { select: { id: true, email: true, firstName: true, lastName: true } }, tenant: { select: { id: true, name: true, slug: true } }, apiKey: { select: { id: true, alias: true } }, } satisfies Prisma.LogInclude; const DEFAULT_AUDIT_LOG_TAKE = 50; const MAX_AUDIT_LOG_TAKE = 500; const CSV_HEADERS = ["Created At", "Tenant", "Actor", "Actor Type", "Action", "URL", "Details"] as const; const FORMULA_PREFIX_PATTERN = /^[=+\-@\t\r]/; const SENSITIVE_LOG_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|body|header/i; export function buildAuditLogWhereFromFilters(filters: AdminAuditLogFilters): Prisma.LogWhereInput { const where: Prisma.LogWhereInput = {}; const and: Prisma.LogWhereInput[] = []; const q = normalizeFilter(filters.q); if (q) { and.push({ OR: [ { action: { contains: q, mode: "insensitive" } }, { url: { contains: q, mode: "insensitive" } }, { details: { contains: q, mode: "insensitive" } }, { tenantId: { contains: q, mode: "insensitive" } }, { userId: { contains: q, mode: "insensitive" } }, ], }); } const action = normalizeFilter(filters.action); if (action) where.action = action; const url = normalizeFilter(filters.url); if (url) where.url = { contains: url, mode: "insensitive" }; const tenantId = normalizeFilter(filters.tenantId); if (tenantId) where.tenantId = tenantId; const userId = normalizeFilter(filters.userId); if (userId) where.userId = userId; const createdAt: Prisma.DateTimeFilter<"Log"> = {}; const createdAtFrom = parseValidDate(filters.createdAtFrom); const createdAtTo = parseValidDate(filters.createdAtTo); if (createdAtFrom) createdAt.gte = createdAtFrom; if (createdAtTo) createdAt.lte = createdAtTo; if (Object.keys(createdAt).length > 0) where.createdAt = createdAt; if (and.length > 0) where.AND = and; return where; } export async function getAdminAuditLogList( args: AdminAuditLogListArgs, client: AdminAuditLogClient = getDbClient() as unknown as AdminAuditLogClient, ): Promise { const where = buildAuditLogWhereFromFilters(args); return getAuditLogListWithWhere(where, args, client); } export async function getTenantAuditLogList( tenantId: string, args: TenantAuditLogListArgs, client: AdminAuditLogClient = getDbClient() as unknown as AdminAuditLogClient, ): Promise { const where = buildAuditLogWhereFromFilters(args); where.tenantId = tenantId; return getAuditLogListWithWhere(where, args, client); } export function serializeAdminAuditLogsCsv(rows: readonly AdminAuditLogRow[]): string { const lines = [CSV_HEADERS.map(escapeCsvCell).join(",")]; for (const row of rows) { lines.push( [row.createdAt.toISOString(), formatTenant(row), formatActor(row), getActorType(row), row.action, row.url, redactLogDetails(row.details)] .map(escapeCsvCell) .join(","), ); } return `${lines.join("\n")}\n`; } async function getAuditLogListWithWhere( where: Prisma.LogWhereInput, args: { take?: number | null; skip?: number | null }, client: AdminAuditLogClient, ): Promise { const take = normalizeTake(args.take); const skip = normalizeSkip(args.skip); const queryArgs = { where, include: adminAuditLogInclude, orderBy: { createdAt: "desc" } satisfies Prisma.LogOrderByWithRelationInput, take, skip, }; const [rows, total] = await Promise.all([client.log.findMany(queryArgs), client.log.count({ where })]); return { rows, total, take, skip }; } function normalizeFilter(value: string | null | undefined): string | undefined { const normalized = value?.trim(); return normalized ? normalized : undefined; } function parseValidDate(value: string | Date | null | undefined): Date | undefined { if (!value) return undefined; const date = value instanceof Date ? value : new Date(value); return Number.isNaN(date.getTime()) ? undefined : date; } function normalizeTake(value: number | null | undefined): number { if (!Number.isFinite(value) || !value || value < 1) return DEFAULT_AUDIT_LOG_TAKE; return Math.min(Math.trunc(value), MAX_AUDIT_LOG_TAKE); } function normalizeSkip(value: number | null | undefined): number { if (!Number.isFinite(value) || !value || value < 0) return 0; return Math.trunc(value); } function formatTenant(row: AdminAuditLogRow): string { if (row.tenant) return row.tenant.name || row.tenant.slug || row.tenant.id; return row.tenantId ?? ""; } function formatActor(row: AdminAuditLogRow): string { if (row.user) { const name = [row.user.firstName, row.user.lastName].filter(Boolean).join(" ").trim(); return name ? `${name} <${row.user.email}>` : row.user.email; } if (row.apiKey) return row.apiKey.alias; return row.userId ?? row.apiKeyId ?? "System"; } function getActorType(row: AdminAuditLogRow): string { if (row.userId || row.user) return "User"; if (row.apiKeyId || row.apiKey) return "API Key"; return "System"; } function escapeCsvCell(value: unknown): string { const stringValue = String(value ?? ""); const safeValue = FORMULA_PREFIX_PATTERN.test(stringValue) ? `'${stringValue}` : stringValue; return `"${safeValue.replaceAll('"', '""')}"`; } export function redactLogDetails(details?: string | null): string | null { if (!details) { return details ?? null; } try { return JSON.stringify(redactLogValue(JSON.parse(details))); } catch { return redactSensitiveText(details); } } function redactLogValue(value: unknown): unknown { if (Array.isArray(value)) { return value.map(redactLogValue); } if (value && typeof value === "object") { return Object.fromEntries( Object.entries(value as Record).map(([key, entry]) => [key, SENSITIVE_LOG_KEY_PATTERN.test(key) ? "[REDACTED]" : redactLogValue(entry)]), ); } if (typeof value === "string") { return redactSensitiveText(value); } return value; } function redactSensitiveText(value: string): string { return value .replace(/(authorization)\s*=\s*Bearer\s+\S+/gi, "$1=Bearer [REDACTED]") .replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]") .replace(/(password|secret|token|api[-_]?key)=\S+/gi, "$1=[REDACTED]"); }