security
security
¶
Terminal output sanitization.
Strings derived from external sources (SSH key comments, file paths, credential names, JSON config values, container output) may contain ANSI escape sequences or other C0/C1 control characters. Printing them raw to a terminal allows output spoofing, title manipulation, or clipboard injection via OSC 52 (CWE-150).
sanitize_tty neutralises them in a
single-line field; sanitize_log_text
does the same for multiline task output while keeping its layout and,
on an interactive terminal, its colours.
__all__ = ['sanitize_log_text', 'sanitize_tty']
module-attribute
¶
sanitize_tty(s)
¶
Replace terminal control characters with safe representations.
Whitespace controls (newline, carriage return, tab) become spaces.
All other characters in Unicode category C (control, format,
surrogate, private use, unassigned) are rendered as \xNN hex
escapes. Printable text passes through unchanged.
Source code in src/terok_util/security.py
sanitize_log_text(text, *, color)
¶
Make multiline task output safe to display while keeping its layout.
Line breaks and tabs survive, and \r\n reads as \n, so log
lines keep their shape. Complete SGR colour sequences are kept when
color is true (an interactive terminal renders them) and removed
otherwise (a file or a pipe), so a legitimate agent's colours reach
the operator but never land in a log file as noise. Kept colours are
reset at the end of the text, so a task's styling cannot outlive its
own output, and SGR 8 (conceal) is not colour: it hides text, so it
is escaped like any other control. Every other control character is
hex-escaped exactly as in
sanitize_tty: cursor movement,
screen erasure, OSC title or clipboard writes and bidi overrides stay
visible text.