59 lines
1.6 KiB
TypeScript
59 lines
1.6 KiB
TypeScript
/**
|
|
* Fire-and-forget security audit helpers (access denials, auth failures).
|
|
*/
|
|
|
|
import { Request } from 'express';
|
|
import * as auditLogRepository from '../repositories/auditLogRepository';
|
|
import { AuthRequest } from '../middleware/auth';
|
|
|
|
export function auditContextFromRequest(req: Request | AuthRequest): {
|
|
ipAddress?: string;
|
|
userAgent?: string;
|
|
userId?: string;
|
|
} {
|
|
const authReq = req as AuthRequest;
|
|
return {
|
|
ipAddress: req.ip || req.socket?.remoteAddress || undefined,
|
|
userAgent: req.get('user-agent') || undefined,
|
|
userId: authReq.user?.userId,
|
|
};
|
|
}
|
|
|
|
/** Records a security-relevant audit event without blocking the caller. */
|
|
export function logSecurityEvent(
|
|
action: string,
|
|
ctx: {
|
|
userId?: string | null;
|
|
ipAddress?: string | null;
|
|
userAgent?: string | null;
|
|
resourceType?: string | null;
|
|
resourceId?: string | null;
|
|
metadata?: Record<string, unknown> | null;
|
|
}
|
|
): void {
|
|
void auditLogRepository
|
|
.create({
|
|
userId: ctx.userId ?? null,
|
|
action,
|
|
resourceType: ctx.resourceType ?? null,
|
|
resourceId: ctx.resourceId ?? null,
|
|
ipAddress: ctx.ipAddress ?? null,
|
|
userAgent: ctx.userAgent ?? null,
|
|
metadata: ctx.metadata ?? null,
|
|
})
|
|
.catch(() => undefined);
|
|
}
|
|
|
|
/** Logs HTTP 403 / permission denial. */
|
|
export function logAccessDenied(
|
|
req: AuthRequest,
|
|
reason: string,
|
|
metadata?: Record<string, unknown>
|
|
): void {
|
|
const base = auditContextFromRequest(req);
|
|
logSecurityEvent('access_denied', {
|
|
...base,
|
|
metadata: { reason, path: req.path, method: req.method, ...metadata },
|
|
});
|
|
}
|