Skip to content

Basinfy/Basinfy-SaaS-Studio / .agents/skills/saas-lgpd-audit-logging

saas-lgpd-audit-logging

Unverified

Implement immutable, hash-chained accountability audit logs (LGPD Art. 6 X & Res. 15/2024).

Running this workflow on this client

Run commands from the project root (use Git Bash on Windows if bash points to an unavailable WSL distro). Shared studio files live in .claude/; follow .agents/PORTABLE-RUNTIME.md and .claude/docs/config-resolution.md for client tools, delegation, and approval rules.

Audit Logging

Locale & User Profile: Match locale (pt-BR → natural Brazilian Portuguese questions/options, overriding English examples; en → English) and user_profile (founder → plain business language with (Recomendado) first, zero tech jargon; developer → technical). Keep code/tests in English.

Log imutável encadeado para prova de conformidade (Art. 6º, X — responsabilização) e registro de incidentes (Art. 10 Res. 15/2024 — 5 anos).

Princípios

  1. Append-only — sem updates nem deletes
  2. Hash chain — cada entry referencia o hash da anterior (tamper-evident)
  3. Minimização — log evento e hash do payload, NÃO o payload em claro
  4. PII out — nunca logar PII completa (mascarar)
  5. Retenção — mínimo 5 anos para eventos relacionados a incidentes; 6m+ para eventos correntes

Eventos a logar

  • Autenticação (login, logout, MFA, falhas)
  • Acesso a dados pessoais (especialmente sensíveis)
  • Mudanças em consentimento (grant, revoke)
  • DSAR (recebimento, fulfillment, rejeição)
  • Mudanças de configuração de privacidade
  • Acesso administrativo a dados de outros usuários
  • Exports e downloads em massa
  • Mudanças em RBAC

Schema Prisma

model AuditLogEntry {
  id          String   @id @default(cuid())
  actorId     String?  // null se sistema
  actorType   ActorType
  action      String   // "READ", "WRITE", "DELETE", "EXPORT", "DSAR_FULFILLED", "CONSENT_REVOKED"
  resource    String   // "User:abc123", "Order:xyz"
  subjectId   String?  // titular afetado (se aplicável)
  legalBasis  String?
  purpose     String?
  ipAddress   String?  @db.Inet
  userAgent   String?
  payloadHash String   // SHA-256 do payload (sem PII)
  prevHash    String?  // hash do registro anterior
  selfHash    String   // SHA-256(prevHash || timestamp || action || resource || payloadHash)
  timestamp   DateTime @default(now())

  @@index([subjectId, timestamp])
  @@index([actorId, timestamp])
  @@index([action, timestamp])
}

enum ActorType { USER ADMIN SYSTEM OPERATOR }

Middleware Next.js

// lib/audit.ts
import { createHash } from "crypto";
import { db } from "./db";

export async function logAudit(entry: {
  actorId?: string;
  actorType: ActorType;
  action: string;
  resource: string;
  subjectId?: string;
  legalBasis?: string;
  purpose?: string;
  payload?: object;
  req?: Request;
}) {
  const last = await db.auditLogEntry.findFirst({
    orderBy: { timestamp: "desc" },
    select: { selfHash: true }
  });

  const payloadHash = createHash("sha256")
    .update(JSON.stringify(entry.payload ?? {}))
    .digest("hex");

  const timestamp = new Date();

  const selfHash = createHash("sha256")
    .update(`${last?.selfHash ?? ""}|${timestamp.toISOString()}|${entry.action}|${entry.resource}|${payloadHash}`)
    .digest("hex");

  return db.auditLogEntry.create({
    data: {
      ...entry,
      payload: undefined,
      payloadHash,
      prevHash: last?.selfHash,
      selfHash,
      ipAddress: entry.req?.headers.get("x-forwarded-for") ?? null,
      userAgent: entry.req?.headers.get("user-agent") ?? null,
      timestamp
    }
  });
}

Verificação de integridade

Script periódico que percorre todas as entries em ordem e verifica que cada selfHash bate. Qualquer divergência = tampering ou bug.

Status update

## F6 — Audit logging ✓
- Schema implementado
- Middleware ativo em rotas críticas
- Verificação de integridade agendada (semanal)
- Retenção configurada (5 anos para eventos críticos)
- Próximo: saas-lgpd-encryption-keys
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 470kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 470kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 470kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall