import { readFile, readdir, stat } from 'node:fs/promises'; import path from 'node:path'; import { ACCESS_LEVELS } from '../../config/constants.js'; import { env } from '../../config/env.js'; import { maskSecrets } from '../../core/logger.js'; import { getDatabase } from '../../database/index.js'; import { badRequest, notFound } from '../http.js'; /** Functional event log and technical log files (M16-T05). */ const LOG_FILE = /^\d{4}-\d{2}-\d{2}\.log$/; export function registerLogRoutes(router) { router.get( '/api/logs/events', ({ query }) => { const clauses = []; const params = []; const type = query.get('type'); if (type) { clauses.push('type LIKE ?'); params.push(`${type}%`); } const actorId = query.get('actorId'); if (actorId) { clauses.push('actor_id = ?'); params.push(actorId); } const limit = Math.min(Number.parseInt(query.get('limit') ?? '100', 10), 500); params.push(limit); const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : ''; const events = getDatabase() .prepare(`SELECT * FROM event_logs ${where} ORDER BY id DESC LIMIT ?`) .all(...params) .map((row) => ({ ...row, payload: row.payload ? JSON.parse(row.payload) : null })); return { events, types: getDatabase() .prepare( 'SELECT type, COUNT(*) AS count FROM event_logs GROUP BY type ORDER BY count DESC LIMIT 40', ) .all(), }; }, { access: ACCESS_LEVELS.STAFF }, ); router.get( '/api/logs/files', async () => { const entries = await readdir(env.logDir).catch(() => []); const files = []; for (const name of entries.filter((entry) => LOG_FILE.test(entry))) { const info = await stat(path.join(env.logDir, name)).catch(() => null); if (info) files.push({ name, sizeBytes: info.size, modifiedAt: info.mtime.toISOString() }); } return { directory: env.logDir, files: files.sort((a, b) => b.name.localeCompare(a.name)) }; }, { access: ACCESS_LEVELS.DEV }, ); router.get( '/api/logs/files/:name', async ({ params, query }) => { // The name pattern is the only thing standing between this route and the // rest of the filesystem, so it is strict on purpose. if (!LOG_FILE.test(params.name)) throw badRequest('Nom de fichier de log invalide.'); const content = await readFile(path.join(env.logDir, params.name), 'utf8').catch(() => null); if (content === null) throw notFound('Fichier de log introuvable.'); const lines = Math.min(Number.parseInt(query.get('lines') ?? '300', 10), 2000); const level = query.get('level'); const parsed = content .split('\n') .filter(Boolean) .map((line) => { try { return JSON.parse(line); } catch { return { level: 'info', message: line }; } }) .filter((entry) => !level || entry.level === level); // `maskSecrets` already ran at write time; it runs again in case the file // predates a secret rotation. return { name: params.name, entries: JSON.parse(maskSecrets(JSON.stringify(parsed.slice(-lines)))) }; }, { access: ACCESS_LEVELS.DEV }, ); }