The log injection bug behind one unescaped newline

I shipped a log injection bug behind one unescaped newline, and it sat in my own security code from the very first commit. It never crashed anything. It never failed a test. A comment directly above it promised that newline injection was blocked.
That gap is the part worth writing down. Not the regex. The distance between what the comment claimed and what the code did.
nextjs-logger takes log calls from a browser and prints them in your terminal. I covered how that pipe works in an earlier post about the relay endpoint. The moment you print a browser-supplied string to a terminal, you have a problem: that string can contain characters a terminal treats as instructions, not as text.
Bug one: stripping \r is not the same as blocking \n
Here is the attack. Someone sends a log message like this:
log.info("ok\n01:02:03 [FATAL] database credentials rotated");If that \n arrives at your terminal as a real line break, your log now shows two lines. The second one looks like a genuine FATAL entry, complete with a timestamp. Nothing actually happened. You cannot tell it apart from a real log line, and neither can any script parsing that file.
This matters more than it sounds. A lot of incident response starts with someone grepping for FATAL at 2am.
My sanitizer had this comment on it: log injection (ANSI escape codes, newline injection) → sanitised before printing. Here is what the code actually did, pulled from the first commit:
return raw
.replace(ANSI_ESCAPE_RE, '') // strip ANSI escapes
.replace(/\r/g, '') // strip carriage returns
.replace(/\x00/g, '') // strip null bytes
.slice(0, 4096);Read line two again. It removes \r. It never touches \n.
So \r\n from a Windows client got flattened into \n, which is still a real line break. And a bare \n, which is what every JavaScript string literal produces, went through completely untouched.
I ran both versions against that forged message to be sure:
OLD real newlines: 1 → renders as 2 terminal lines
NEW real newlines: 0 → renders as 1 terminal lineEscape it, do not delete it
My first instinct was to strip \n too. That is the wrong fix.
Deleting a newline destroys information. If someone pastes a stack trace into a log call, silently removing the breaks means you can no longer tell a multi-line paste ever happened. You have swapped a security bug for a data bug.
The fix is to escape the newline into the two visible characters \ and n:
export function sanitiseMessage(raw: string): string {
return raw
.replace(ANSI_ESCAPE_RE, '') // terminal escape sequences
.replace(CONTROL_CHARS_RE, '') // remaining control bytes
.replace(/\t/g, ' ') // tabs can fake column alignment
.replace(/\r\n|\r|\n/g, '\\n') // escape — never forge a new line
.slice(0, 4096);
}Now the content stays fully readable. You can see exactly what was sent. It just cannot pretend to be a new line any more. Genuinely multi-line data has somewhere else to go: the structured data field, where JSON encoding escapes line breaks for exactly the same reason without losing them.
The ANSI regex only knew about one family
While I was in there I checked the escape-sequence pattern. The old one was /\x1B\[[0-9;]*[a-zA-Z]/g.
That matches CSI sequences, the ESC [ ... letter shape used for colors. It is the family everyone thinks of. It is not the only one.
I fed four real sequences through both versions:
CSI color ESC [ 31 m OLD -> "red" escape left? no
OSC title ESC ] 0 ; x BEL OLD -> "\x1B]0;PWNED\x07text" escape left? YES
Fe reset ESC c OLD -> "\x1Bctext" escape left? YES
nF charset ESC ( B OLD -> "\x1B(Btext" escape left? YESThree of four walked straight past it. OSC can rewrite your terminal’s window title. ESC c is a full terminal reset. All of them are reachable from a string a browser sent.
The replacement matches the families rather than the one example that was top of mind:
const ANSI_ESCAPE_RE =
/\x1B(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)?|[@-Z\\-_]|[ -\/]*[0-~])/g;All four now come out clean. Messages are also capped at 4,096 characters, and fields like namespace at 256, so a single entry cannot flood a terminal.
Bug two: one assignment, two completely different failures
This one is stranger, and it is the reason I am writing this post rather than just pushing a patch.
redact() walks a structured object and replaces the value of any key matching a pattern, like password or token, with [REDACTED]. The obvious way to rebuild that object is one line:
out[key] = keyMatches(key, patterns) ? REDACTED : walk(val);That line is correct for every key except one. When key is the string __proto__, you are not writing an ordinary property. You are hitting the inherited __proto__ setter on Object.prototype.
Most write-ups stop there and say “it pollutes the prototype.” That is only half true, and the half that is missing surprised me. (The other thing they get wrong is which line does it — I later tested every way of copying such an object and found that JSON.parse never pollutes anything, while the copy on the next line might.)
What actually happens depends on the type of the value you assign. I tested both paths:
Case A — value is a string (the key matched, so it becomes "[REDACTED]")
own __proto__ key? false
prototype changed? false
JSON.stringify {}
Case B — value is an object (the key did not match, so walk() returned an object)
own __proto__ key? false
prototype changed? TRUE
obj.isAdmin trueThe __proto__ setter ignores anything that is not an object or null. So in Case A the assignment is a silent no-op. Nothing is stored. Nothing is reparented. The key just evaporates, and a value you promised to mark as redacted is now missing entirely.
Case B is the one that bothers me. Run a real redaction and look at the output:
input {"__proto__":{"isAdmin":true},"user":"ehsan"}
OLD JSON.stringify → {"user":"ehsan"}
but out.isAdmin === true
NEW JSON.stringify → {"__proto__":{"isAdmin":true},"user":"ehsan"}
and out.isAdmin === undefinedLook at the old result carefully. Serialize it and you get a clean object with one harmless field. Read a property off it and isAdmin is true.
The data did not vanish. It moved onto the prototype, where JSON.stringify cannot see it but if (user.isAdmin) absolutely can. An object that looks empty in your logs and answers true to a permission check is a worse outcome than either plain failure.
The fix is to refuse the setter entirely
Object.defineProperty(out, key, {
value: next,
enumerable: true,
writable: true,
configurable: true,
});Object.defineProperty always creates a real own property on out. It does not consult the prototype chain, so there is no setter to hijack. Identical behaviour for every normal key, correct behaviour for the one that is not normal.
I wrote about a different shape of this same hazard in the RPC bridge security model, where the danger is merging attacker JSON rather than rebuilding it key by key. Same root cause, different entry point.
How I found them
The newline bug came from pasting a multi-line string into a log.info() call during unrelated testing and noticing the terminal printed what looked like two entries. That is the honest version of how most bugs surface. Not an adversarial mindset. Just output that looked slightly wrong, and not shrugging it off as a rendering quirk.
The __proto__ bug I went looking for. Once the first comment turned out to be wrong, I stopped trusting the rest of the file. I read every function hunting for one specific shape: a place where a key name gets used to write to an object instead of just read from it. That is the exact signature __proto__ exploits. It was the next function down.
The test that would have caught both
Not “does the sanitizer strip ANSI codes.” That test existed and passed.
The test that matters asserts the bypass, not the feature:
- Give
sanitiseMessagea string with a bare\n. Assert the output contains zero real newline characters and does contain a literal backslash-n. - Give
redactan object with an own key named__proto__. Assert the output has an own__proto__key holding[REDACTED], and thatObject.getPrototypeOf(out)is stillObject.prototype.
One assertion each. Both would have failed on day one.
The hardening suite now runs 20 tests over this file in about 62ms, and all 20 pass. The count is not the point. Which cases they describe is.
What I actually took from this
A comment that says a function blocks newline injection is a claim. A test that pushes a bare \n through it and checks the output is a guarantee.
In a code review those two look identical. Both read as “this is handled.” Only one of them fails out loud the moment it stops being true.
So now, whenever I write a comment describing what a security function promises, I ask whether a test asserts that exact promise by name. Not a test that happens to call the function while checking something else. If the answer is no, the comment is a promise nothing is checking, and it will quietly drift away from the truth the first time somebody edits that file without reading it closely.
Both of mine had already drifted. On the very first commit.