fix(cli): sanitize terminal output - #32
Conversation
|
Please fix the items below:
Also Normalize carriage return before applying the character class. |
| const ansi = (code: string, text: string)=> | ||
| is_tty ? `\x1b[${code}m${text}\x1b[0m` : text; | ||
| is_tty() ? `\x1b[${code}m${text}\x1b[0m` : text; |
There was a problem hiding this comment.
ansi() decides on colors via process.stdout.isTTY, but success/warn/info/fail write to stderr it might cause 2 bugs:
cmd | jq- stdout is a pipe, stderr is still a TTY -> diagnostics lose color.cmd 2>error.log- stdout is a TTY, stderr is a file -> raw\x1b[33mwrites in the log file.
Suggested fix:
const is_tty = ()=>process.stdout.isTTY === true;
const is_tty_err = ()=>process.stderr.isTTY === true;
const ansi = (code: string, text: string, tty = is_tty())=>
tty ? `\x1b[${code}m${text}\x1b[0m` : text;
const green = (s: string, tty?: boolean)=>ansi('32', s, tty ?? is_tty());
const red = (s: string, tty?: boolean)=>ansi('31', s, tty ?? is_tty());
const yellow = (s: string, tty?: boolean)=>ansi('33', s, tty ?? is_tty());
const dim = (s: string, tty?: boolean)=>ansi('2', s, tty ?? is_tty());
const warn = (msg: string)=>
console.error(yellow(`⚠ ${terminal_safe(msg)}`, is_tty_err()));
// same for success / info / fail
We can skip it for now, it's not a blocker. Maybe it's a case for another request
| return tty | ||
| ? terminal_safe(text).replace(/\n/g, ' ') | ||
| : text; | ||
| }; |
There was a problem hiding this comment.
We can replace \n and \t always here to not break the table (no need to check if tty)
Fixes unsafe terminal output when API-controlled values contain escape/control characters.
The changes:
sanitize untrusted values when printing to a TTY
sanitize and flatten values in print_table() before calculating column widths
preserve raw output when stdout is piped or redirected
make the TTY check dynamic
add tests for TTY sanitization, redirected output, and malicious table values
bump version to 0.3.6