Santize inserts

This commit is contained in:
Owen
2026-03-20 10:27:18 -07:00
parent 56e25d01ae
commit 222dd6bba3

View File

@@ -5,6 +5,26 @@ import cache from "#dynamic/lib/cache";
import { calculateCutoffTimestamp } from "@server/lib/cleanupLogs"; import { calculateCutoffTimestamp } from "@server/lib/cleanupLogs";
import { stripPortFromHost } from "@server/lib/ip"; import { stripPortFromHost } from "@server/lib/ip";
/**
* Sanitize a string field by replacing lone UTF-16 surrogates (which cannot
* be encoded as valid UTF-8) with the Unicode replacement character, and
* stripping ASCII control characters that are invalid in most text columns.
*/
function sanitizeString(value: string | undefined | null): string | undefined {
if (value == null) return undefined;
return (
value
// Replace lone high surrogates (not followed by a low surrogate)
// and lone low surrogates (not preceded by a high surrogate)
.replace(
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,
"\uFFFD"
)
// Strip C0 control characters except HT (\x09), LF (\x0A), CR (\x0D)
.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "")
);
}
/** /**
Reasons: Reasons:
@@ -253,24 +273,23 @@ export async function logRequestAudit(
// Add to buffer instead of writing directly to DB // Add to buffer instead of writing directly to DB
auditLogBuffer.push({ auditLogBuffer.push({
timestamp, timestamp,
orgId: data.orgId, orgId: sanitizeString(data.orgId),
actorType, actorType: sanitizeString(actorType),
actor, actor: sanitizeString(actor),
actorId, actorId: sanitizeString(actorId),
metadata, metadata: sanitizeString(metadata),
action: data.action, action: data.action,
resourceId: data.resourceId, resourceId: data.resourceId,
reason: data.reason, reason: data.reason,
location: data.location, location: sanitizeString(data.location),
originalRequestURL: body.originalRequestURL, originalRequestURL: sanitizeString(body.originalRequestURL) ?? "",
scheme: body.scheme, scheme: sanitizeString(body.scheme) ?? "",
host: body.host, host: sanitizeString(body.host) ?? "",
path: body.path, path: sanitizeString(body.path) ?? "",
method: body.method, method: sanitizeString(body.method) ?? "",
ip: clientIp, ip: sanitizeString(clientIp),
tls: body.tls tls: body.tls
}); });
// Flush immediately if buffer is full, otherwise schedule a flush // Flush immediately if buffer is full, otherwise schedule a flush
if (auditLogBuffer.length >= BATCH_SIZE) { if (auditLogBuffer.length >= BATCH_SIZE) {
// Fire and forget - don't block the caller // Fire and forget - don't block the caller