Files
CapaKraken/packages/api/src/middleware/logging.ts
T
Hartmut 9d43e4b113 feat: ACN Application Security Standard V7.30 compliance (19/23 items)
CRITICAL — Authentication & Access:
- TOTP MFA: otpauth-based, QR setup UI, sign-in flow integration,
  admin disable override, /account/security self-service page
- Session Timeouts: 8h absolute (maxAge), 30min idle (updateAge)
- Failed Auth Logging: Pino warn for invalid password/user/totp,
  info for successful login, audit entries for all auth events
- Concurrent Session Limit: ActiveSession model, oldest-kick strategy,
  max 3 per user (configurable in SystemSettings)

CRITICAL — HTTP Security:
- HSTS: max-age=31536000; includeSubDomains
- CSP: script/style/img/font/connect-src with Gemini/OpenAI whitelist
- X-XSS-Protection: 0 (CSP replaces legacy)
- Auth page cache: no-store, no-cache, must-revalidate
- Rate Limiting: 100/15min general API, 5/15min auth (Map-based)

Data Protection:
- XSS Sanitization: DOMPurify on comment bodies
- autocomplete="new-password" on all password/secret fields
- SameSite=Strict on all cookies (Credentials-only, no OAuth)
- File Upload Magic Bytes validation (PNG/JPEG/WebP/GIF/BMP/TIFF)

Logging & Monitoring:
- Login/Logout audit entries (Auth entityType)
- External API call logging with timing (OpenAI, Gemini)
- Input validation failure logging at warn level
- Concurrent session tracking in ActiveSession table

Documentation:
- docs/security-architecture.md (11 sections)
- docs/sdlc.md (CI pipeline, security gates, incident response)
- .gitea/PULL_REQUEST_TEMPLATE.md (security checklist)

Schema: User.totpSecret/totpEnabled, SystemSettings.sessionMaxAge/
sessionIdleTimeout/maxConcurrentSessions, ActiveSession model

Tests: 310 engine + 37 staffing pass. TypeScript clean.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-03-27 14:16:39 +01:00

73 lines
2.0 KiB
TypeScript

import { TRPCError } from "@trpc/server";
import { logger } from "../lib/logger.js";
const SLOW_THRESHOLD_MS = 500;
/**
* Core logging logic for tRPC procedure calls.
*
* Designed to be wrapped with `t.middleware()` in trpc.ts.
* Generates a requestId (UUID) per call and attaches it to the context.
*
* Log levels:
* - debug: normal requests
* - warn: slow requests (>500ms)
* - error: failed requests
*/
export async function loggingMiddleware(opts: {
ctx: { dbUser?: { id: string } | null; requestId?: string };
type: "query" | "mutation" | "subscription";
path: string;
next: (opts: { ctx: Record<string, unknown> }) => Promise<{ ok: boolean }>;
}) {
const { ctx, type, path, next } = opts;
const requestId = crypto.randomUUID();
const userId = ctx.dbUser?.id ?? "anonymous";
const start = performance.now();
const logBase = {
requestId,
type,
path,
userId,
};
try {
const result = await next({
ctx: { ...ctx, requestId },
});
const durationMs = Math.round(performance.now() - start);
const logData = { ...logBase, durationMs, status: "ok" as const };
if (durationMs > SLOW_THRESHOLD_MS) {
logger.warn(logData, "Slow tRPC call");
} else {
logger.debug(logData, "tRPC call");
}
return result;
} catch (error) {
const durationMs = Math.round(performance.now() - start);
const errorCode =
error instanceof TRPCError ? error.code : "INTERNAL_SERVER_ERROR";
const errorMessage =
error instanceof Error ? error.message : "Unknown error";
// Log input validation failures at warn level (not error)
if (errorCode === "BAD_REQUEST") {
logger.warn(
{ ...logBase, durationMs, status: "error" as const, errorCode, errorMessage },
"Input validation failure",
);
} else {
logger.error(
{ ...logBase, durationMs, status: "error" as const, errorCode, errorMessage },
"tRPC call failed",
);
}
throw error;
}
}