@credentum/sanitize-log-output
v0.0.1
Published
Strip CRLF injection, ANSI escapes, null bytes, and control characters from strings before logging. Prevents OWASP Log Injection.
Maintainers
Readme
sanitize-log-output
Strip CRLF injection, ANSI escape sequences, null bytes, and control characters from strings before logging. Prevents OWASP Log Injection.
Installation
npm install @credentum/sanitize-log-outputUsage
import { sanitizeLogOutput } from '@credentum/sanitize-log-output';
const userInput = 'admin\r\n[INFO] Fake log entry\x1B[31m hidden';
console.log(`Login attempt: ${sanitizeLogOutput(userInput)}`);
// => "Login attempt: admin[INFO] Fake log entry hidden"Why Use This?
Every security audit flags it. CodeQL detects it (js-log-injection). Snyk blogs about it. OWASP names it. And the recommended fix is always the same: manually call String.prototype.replace with a regex you copy-pasted from a blog post.
This package replaces that copy-paste pattern with a tested, typed, zero-dependency function that handles what your hand-rolled regex misses:
- CRLF injection (
\r\n,\r,\n) — forges fake log entries - ANSI escape sequences (
\x1B[31m,\x1B]0;title\x07) — hides text, hijacks terminals - Null bytes (
\0) — truncates log lines - Control characters (U+0000-U+001F, U+007F-U+009F) — binary injection
Tabs are preserved by default (legitimate in structured output).
API
sanitizeLogOutput(input, options?)
Sanitizes a string for safe inclusion in log output.
Parameters:
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| input | string | — | The string to sanitize |
| options.replacement | string | "" | Replacement for stripped characters. Use "labeled" for forensic markers ([NL], [CR], [ANSI], [NULL], [CTRL]). |
| options.preserveTabs | boolean | true | Keep tab characters (\t). Set false to strip them. |
Returns: string — the sanitized string.
Examples:
// Default: strip silently, preserve tabs
sanitizeLogOutput('line1\nline2\ttab');
// => "line1line2\ttab"
// Labeled: forensic markers for incident response
sanitizeLogOutput('inject\r\nfake\x1B[31mred', { replacement: 'labeled' });
// => "inject[CR][NL]fake[ANSI]red"
// Custom replacement character
sanitizeLogOutput('line1\nline2', { replacement: ' ' });
// => "line1 line2"
// Strip tabs too
sanitizeLogOutput('col1\tcol2\nline2', { preserveTabs: false });
// => "col1col2line2"What This Does NOT Do
- PII masking — use pino-redaction
- Structured log formatting — use pino or winston
- HTML sanitization — use DOMPurify
- Log file analysis — use logshield
License
MIT
