Configuration Guide Guía de Configuración
Learn how to configure Panoptes SDK to fit your application's needs. From basic setup to advanced options. Aprende cómo configurar Panoptes SDK para adaptarse a las necesidades de tu aplicación. Desde configuración básica hasta opciones avanzadas.
Core Configuration: Configuración Principal: initAudit()
initAudit() The
import { initAudit } from '@panoptes/sdk';
initAudit({
appName: 'my-app', // Required: Your application name
environment: 'production', // Optional: development, staging, production
transports: {
enabled: ['console'] // At least one transport required
}
});import { initAudit } from '@panoptes/sdk';
initAudit({
// Application metadata
appName: 'my-app', // Required: Identifies your application in logs
environment: 'production', // Optional: 'development' | 'staging' | 'production'
version: '1.0.0', // Optional: Your app version
// Audit behavior
enabled: true, // Optional: Master switch (default: true)
captureBeforeState: true, // Optional: Capture data before UPDATE/DELETE (default: true)
captureAfterState: true, // Optional: Capture data after INSERT/UPDATE (default: true)
// Performance options
asyncMode: true, // Optional: Process audits asynchronously (default: true)
bufferSize: 100, // Optional: Buffer size for async mode (default: 100)
// Transports configuration
transports: {
enabled: ['console', 'database', 'file', 'http'],
// Console transport options
console: {
prettyPrint: true // Optional: Pretty print JSON (default: false)
},
// File transport options
file: {
path: './logs/audit.log' // Optional: Log file path (default: 'panoptes-audit.log')
},
// HTTP transport options
http: {
endpoint: 'https://api.example.com/audit', // Required for HTTP transport
headers: { // Optional: Custom headers
'Authorization': 'Bearer token',
'X-Custom-Header': 'value'
},
timeout: 5000 // Optional: Request timeout in ms (default: 5000)
},
// Database transport options
database: {
client: auditDbClient, // Required: Database client instance
engine: 'postgres', // Required: 'postgres' | 'mysql' | 'mssql' | 'sqlite' | 'oracle'
tableName: 'audit_logs', // Optional: Table name (default: 'panoptes_audit_log')
autoCreateTable: true // Optional: Auto-create audit table (default: false)
}
},
// Filtering rules (optional)
rules: {
// Tables to always audit (all operations)
includeTables: ['users', 'orders', 'payments'],
// Tables to never audit
excludeTables: ['sessions', 'logs', 'cache'],
// Operations to audit (if not specified, all are audited)
includeOperations: ['INSERT', 'UPDATE', 'DELETE'],
// Custom filter function
filter: (auditEvent) => {
// Return true to audit, false to skip
return auditEvent.operation.type !== 'SELECT';
}
},
// Error handling (optional)
onError: (error, auditEvent) => {
console.error('Audit error:', error);
// You can send to error tracking service here
}
});Configuration by Environment Configuración por Ambiente
Different environments typically require different configurations. Here are recommended setups for each environment. Diferentes ambientes típicamente requieren diferentes configuraciones. Aquí están las configuraciones recomendadas para cada ambiente.
Development Environment Ambiente de Desarrollo
Console output with pretty printing for easy debugging Salida de consola con formato para fácil depuración
initAudit({
appName: 'my-app',
environment: 'development',
transports: {
enabled: ['console'],
console: {
prettyPrint: true
}
},
captureBeforeState: true,
captureAfterState: true
});Staging Environment Ambiente de Staging
Console + file logging for testing before production Consola + archivo para probar antes de producción
initAudit({
appName: 'my-app',
environment: 'staging',
transports: {
enabled: ['console', 'file'],
file: {
path: '/var/log/audit.log'
}
},
asyncMode: true,
bufferSize: 100
});Production Environment Ambiente de Producción
Database + SIEM integration for compliance Base de datos + integración SIEM para cumplimiento
initAudit({
appName: 'my-app',
environment: 'production',
transports: {
enabled: ['database', 'http'],
database: {
client: auditDb,
engine: 'postgres',
autoCreateTable: true
},
http: {
endpoint: process.env.SIEM_URL,
headers: {
'Authorization': `Bearer ${process.env.SIEM_TOKEN}`
}
}
},
asyncMode: true,
bufferSize: 500,
onError: (error) => {
errorTracker.capture(error);
}
}); User Context: Contexto de Usuario: setUserContext()
setUserContext() User context provides crucial information about who is performing database operations. This should be set for each request or session. El contexto de usuario proporciona información crucial sobre quién está realizando operaciones en la base de datos. Esto debe establecerse para cada petición o sesión.
import { setUserContext } from '@panoptes/sdk';
setUserContext({
// Actor information (who is making the change)
actorType: 'USER', // 'USER' | 'SERVICE' | 'SYSTEM' | 'ADMIN' | 'API'
actorId: 'user-123', // Unique user/service identifier
actorName: 'John Doe', // Display name
actorEmail: 'john@example.com', // Email address (optional)
actorRoles: ['admin', 'editor'], // User roles (optional)
// Tenant/Organization (for multi-tenant apps)
tenantId: 'org-456', // Organization/tenant identifier (optional)
tenantName: 'Acme Corp', // Organization name (optional)
// Request context
requestId: 'req-789', // Request/correlation ID (optional)
sessionId: 'sess-abc', // Session identifier (optional)
actorIp: '192.168.1.100', // IP address (optional)
userAgent: 'Mozilla/5.0...', // Browser/client info (optional)
// Custom metadata
metadata: { // Any additional custom fields
department: 'Engineering',
location: 'US-WEST',
authMethod: 'SSO'
}
});Express.js
// Middleware to set user context from request
app.use((req, res, next) => {
if (req.user) {
setUserContext({
actorType: 'USER',
actorId: req.user.id,
actorName: req.user.name,
actorEmail: req.user.email,
actorRoles: req.user.roles,
requestId: req.id,
sessionId: req.session?.id,
actorIp: req.ip,
userAgent: req.get('user-agent')
});
}
next();
});Next.js (App Router)
// In middleware.ts or before database operations
import { setUserContext } from '@panoptes/sdk';
import { auth } from '@/auth';
export async function middleware(request) {
const session = await auth();
if (session?.user) {
setUserContext({
actorType: 'USER',
actorId: session.user.id,
actorName: session.user.name,
actorEmail: session.user.email,
requestId: request.headers.get('x-request-id'),
actorIp: request.ip
});
}
}Fastify
// Fastify hook
fastify.addHook('onRequest', async (request, reply) => {
if (request.user) {
setUserContext({
actorType: 'USER',
actorId: request.user.id,
actorName: request.user.name,
actorEmail: request.user.email,
requestId: request.id,
actorIp: request.ip,
userAgent: request.headers['user-agent']
});
}
});Audit Rules & Filtering Reglas de Auditoría y Filtrado
Configure which tables and operations to audit. By default, Panoptes audits all operations on all tables. Configura qué tablas y operaciones auditar. Por defecto, Panoptes audita todas las operaciones en todas las tablas.
initAudit({
appName: 'my-app',
transports: { enabled: ['database'] },
rules: {
// Option 1: Whitelist approach - only audit these tables
includeTables: ['users', 'orders', 'payments', 'customers'],
// Option 2: Blacklist approach - audit all EXCEPT these tables
excludeTables: ['sessions', 'cache', 'logs', 'migrations'],
// Note: Use either includeTables OR excludeTables, not both
}
});initAudit({
appName: 'my-app',
transports: { enabled: ['database'] },
rules: {
// Only audit data modifications (skip SELECT)
includeOperations: ['INSERT', 'UPDATE', 'DELETE'],
// Or exclude specific operations
excludeOperations: ['SELECT'],
}
});initAudit({
appName: 'my-app',
transports: { enabled: ['database'] },
rules: {
filter: (auditEvent) => {
// Skip if no user context (system operations)
if (!auditEvent.actor?.userId) {
return false;
}
// Only audit sensitive tables
const sensitiveTables = ['users', 'payments', 'personal_data'];
if (!sensitiveTables.includes(auditEvent.operation.mainTable)) {
return false;
}
// Skip SELECT operations on non-sensitive data
if (auditEvent.operation.type === 'SELECT' &&
!auditEvent.operation.mainTable.includes('sensitive')) {
return false;
}
// Only audit operations by non-admin users
if (auditEvent.actor.roles?.includes('super-admin')) {
return false; // Don't audit super-admin actions
}
return true; // Audit this event
}
}
});- Start broad, then narrow: Begin by auditing everything, then exclude as needed Empieza amplio, luego reduce: Comienza auditando todo, luego excluye según necesites
- Skip high-volume tables: Exclude logs, sessions, and cache tables Omite tablas de alto volumen: Excluye logs, sesiones y tablas de caché
- Focus on sensitive data: Always audit PII, financial, and authentication tables Enfócate en datos sensibles: Siempre audita PII, financieros y tablas de autenticación
- Consider performance: Filtering reduces storage and processing costs Considera el rendimiento: El filtrado reduce costos de almacenamiento y procesamiento
Environment Variables Variables de Entorno
For security and flexibility, use environment variables for sensitive configuration values. Por seguridad y flexibilidad, usa variables de entorno para valores de configuración sensibles.
# Application
PANOPTES_APP_NAME=my-app
PANOPTES_ENVIRONMENT=production
PANOPTES_VERSION=1.0.0
# Audit behavior
PANOPTES_ENABLED=true
PANOPTES_ASYNC_MODE=true
PANOPTES_BUFFER_SIZE=500
# Transports
PANOPTES_TRANSPORTS=database,http
PANOPTES_FILE_PATH=/var/log/panoptes/audit.log
# HTTP Transport
PANOPTES_HTTP_ENDPOINT=https://siem.example.com/api/events
PANOPTES_HTTP_TOKEN=your-secret-token
# Database Transport (Audit Database)
PANOPTES_AUDIT_DB_HOST=audit-db.example.com
PANOPTES_AUDIT_DB_PORT=5432
PANOPTES_AUDIT_DB_NAME=audit_logs
PANOPTES_AUDIT_DB_USER=audit_user
PANOPTES_AUDIT_DB_PASSWORD=secure-password
PANOPTES_AUDIT_TABLE_NAME=panoptes_audit_log
PANOPTES_AUTO_CREATE_TABLE=trueimport { initAudit, createAuditedPostgresClient } from '@panoptes/sdk';
import { Client } from 'pg';
// Create audit database client
const auditDbClient = new Client({
host: process.env.PANOPTES_AUDIT_DB_HOST,
port: parseInt(process.env.PANOPTES_AUDIT_DB_PORT || '5432'),
database: process.env.PANOPTES_AUDIT_DB_NAME,
user: process.env.PANOPTES_AUDIT_DB_USER,
password: process.env.PANOPTES_AUDIT_DB_PASSWORD
});
await auditDbClient.connect();
// Initialize with environment variables
initAudit({
appName: process.env.PANOPTES_APP_NAME || 'my-app',
environment: process.env.PANOPTES_ENVIRONMENT || 'development',
version: process.env.PANOPTES_VERSION,
enabled: process.env.PANOPTES_ENABLED !== 'false',
asyncMode: process.env.PANOPTES_ASYNC_MODE === 'true',
bufferSize: parseInt(process.env.PANOPTES_BUFFER_SIZE || '100'),
transports: {
enabled: process.env.PANOPTES_TRANSPORTS?.split(',') || ['console'],
file: {
path: process.env.PANOPTES_FILE_PATH
},
http: {
endpoint: process.env.PANOPTES_HTTP_ENDPOINT,
headers: {
'Authorization': `Bearer ${process.env.PANOPTES_HTTP_TOKEN}`
}
},
database: {
client: auditDbClient,
engine: 'postgres',
tableName: process.env.PANOPTES_AUDIT_TABLE_NAME || 'panoptes_audit_log',
autoCreateTable: process.env.PANOPTES_AUTO_CREATE_TABLE === 'true'
}
}
});Performance Optimization Optimización de Rendimiento
initAudit({
appName: 'my-app',
// Enable async processing (non-blocking)
asyncMode: true, // Default: true
// Buffer size - higher = better batching, but more memory
bufferSize: 500, // Default: 100
// For high-volume scenarios
captureBeforeState: false, // Skip before state if not needed
transports: {
enabled: ['database'],
database: {
// Use connection pooling for audit DB
client: auditPoolClient,
engine: 'postgres'
}
}
});asyncMode: asyncMode: Processes audits in background, doesn't block your queriesProcesa auditorías en segundo plano, no bloquea tus consultas
bufferSize: bufferSize: Number of events to buffer before processing (higher = better performance)Número de eventos a bufferear antes de procesar (mayor = mejor rendimiento)
- 1. Use async mode in production (default: true) Usa modo async en producción (default: true)
- 2. Increase buffer size for high-volume apps (500-1000) Aumenta el buffer para apps de alto volumen (500-1000)
- 3. Skip before state if you don't need it (saves DB reads) Omite estado anterior si no lo necesitas (ahorra lecturas BD)
- 4. Filter aggressively - only audit what you need Filtra agresivamente - solo audita lo necesario
- 5. Use separate audit DB - don't store audits in your app database Usa BD de auditoría separada - no almacenes auditorías en tu BD de app
Next Steps Próximos Pasos
Now that you know how to configure Panoptes, continue to Integrations to learn about transports and external systems. Ahora que sabes cómo configurar Panoptes, continúa a Integraciones para aprender sobre transportes y sistemas externos.
