Files
SRCmail/lib/admin/audit.ts
T
Linus Rath 76b21147e4 feat: add plugin/theme harness and admin dashboard
Plugin & Theme System:
- Add plugin type definitions, permissions (30+), and validation constants
- Add IndexedDB storage layer for plugin code, theme CSS, and previews
- Add theme CSS sanitization, injection, and safety validation
- Add HookBus event system with 130+ hooks across 20 domains
- Add plugin ZIP extraction and manifest validation with JS security checks
- Add sandboxed PluginAPI factory with scoped storage, logging, and permission gating
- Add plugin loader with blob URL dynamic import and auto-disable circuit breaker
- Add 3 built-in themes (Nord, Catppuccin, Solarized)
- Add Zustand plugin store with install/uninstall/enable/disable lifecycle
- Add PluginSlot, PluginSlotRenderer, and PluginErrorBoundary components
- Add plugins and themes settings UI panels
- Integrate plugin slots into email viewer, composer, navigation rail, sidebar, and context menu
- Extend theme store with custom theme installation and activation

Admin Dashboard:
- Add admin authentication with scrypt password hashing and AES-256-GCM sessions
- Add rate-limited login (5 attempts/15min per IP)
- Add config manager with admin override > env var > default priority
- Add settings policy system with feature gates and per-setting restrictions
- Add audit logging with rotation
- Add admin API routes (login, logout, config, policy, audit, password change)
- Add admin UI pages (login, dashboard, config, policy, audit)
- Add policy store for client-side feature gate enforcement
- Wire admin password initialization into server instrumentation

Tests:
- Add 139 tests across 10 test files covering all plugin/theme modules
2026-03-25 00:44:03 +01:00

92 lines
2.9 KiB
TypeScript

import { appendFile, stat, rename, mkdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { logger } from '@/lib/logger';
import type { AuditEntry } from './types';
const MAX_LOG_SIZE = 10 * 1024 * 1024; // 10 MB
const MAX_ROTATIONS = 3;
function getAdminDir(): string {
return process.env.ADMIN_DATA_DIR || path.join(process.cwd(), 'data', 'admin');
}
function getAuditLogPath(): string {
return path.join(getAdminDir(), 'audit.log');
}
/**
* Append an audit entry to the admin audit log.
*/
export async function auditLog(action: string, detail: Record<string, unknown>, ip: string): Promise<void> {
const dir = getAdminDir();
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true });
}
const entry: AuditEntry = {
ts: new Date().toISOString(),
action,
detail,
ip,
};
const logPath = getAuditLogPath();
try {
await appendFile(logPath, JSON.stringify(entry) + '\n', 'utf-8');
await rotateIfNeeded(logPath);
} catch (error) {
logger.error('Failed to write audit log', { error: error instanceof Error ? error.message : 'Unknown error' });
}
}
async function rotateIfNeeded(logPath: string): Promise<void> {
try {
const stats = await stat(logPath);
if (stats.size < MAX_LOG_SIZE) return;
// Rotate: audit.log.3 → deleted, audit.log.2 → .3, audit.log.1 → .2, audit.log → .1
for (let i = MAX_ROTATIONS; i >= 1; i--) {
const from = i === 1 ? logPath : `${logPath}.${i - 1}`;
const to = `${logPath}.${i}`;
if (existsSync(from)) {
try { await rename(from, to); } catch { /* target may exist on overwrite */ }
}
}
} catch {
// stat failed, probably file doesn't exist yet
}
}
/**
* Read audit log entries, newest first. Supports pagination.
*/
export async function readAuditLog(page: number = 1, limit: number = 50, actionFilter?: string): Promise<{ entries: AuditEntry[]; total: number }> {
const logPath = getAuditLogPath();
try {
const { readFile } = await import('node:fs/promises');
const content = await readFile(logPath, 'utf-8');
const lines = content.trim().split('\n').filter(Boolean);
let entries: AuditEntry[] = lines.map(line => {
try { return JSON.parse(line); } catch { return null; }
}).filter((e): e is AuditEntry => e !== null);
if (actionFilter) {
entries = entries.filter(e => e.action === actionFilter);
}
const total = entries.length;
// Return newest first
entries.reverse();
const start = (page - 1) * limit;
return { entries: entries.slice(start, start + limit), total };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return { entries: [], total: 0 };
}
logger.warn('Failed to read audit log', { error: error instanceof Error ? error.message : 'Unknown error' });
return { entries: [], total: 0 };
}
}