Screening Untrusted Office Inputs Before LLM Triage
Accounts-payable, billing, and vendor-support queues ingest emails, attachments, and CSV schedules from unauthenticated external senders. inbox-guard is a zero-dependency Node.js library and CLI that screens inbound office artifacts and tokenizes structured PII before text reaches an external language model or an operator's spreadsheet client. This note documents the implementation in src/ at commit 633f2dd and its exact scope boundaries. For a hands-on four-invoice CSV walkthrough you can run without reading the code, see docs/checking-a-change.md.
1. Attachment Canonicalization & Magic-Byte Screening (src/attachment.mjs)
Checking only MIME headers or path.extname() misses visual extension spoofing, OS-specific filename canonicalization quirks, and renamed binaries or archives. checkAttachment({ filename, headBytes }) (lines 286–699) evaluates filename normalization and leading byte signatures independently, returning every matching finding:
Filename Canonicalization, Bidi Overrides & OS Edge Cases
- Unicode bidirectional & dot-leader spoofing (lines 45, 49, 299–305, 353–359):
BIDI_OVERRIDE_RE(/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/) catches Right-to-Left Override (U+202E) and directional marks (UNICODE_BIDI_SPOOF)—whereinvoice_\u202Efdp.scrrenders visually asinvoice_rcs.pdfwhile ending in.scron disk—andDOT_LEADER_SPOOF_RE(/[\u2024\u2025\u3002\uFE52\uFF0E]/) flags Unicode dot-leader and fullwidth period lookalikes (UNICODE_DOT_SPOOF). - Windows/SMB trailing dots, NTFS
:streamADS, Win32-illegal chars, reserved device stems & padding (lines 46–51, 160–207, 307–477): Windows and SMB strip trailing dots and spaces when saving files, turninginvoice.exe.orinvoice.exeback into.exe(TRAILING_DOT_OR_SPACE, lines 345–351).findNtfsAdsColonIndex(lines 160–207) flags NTFS Alternate Data Stream and device-colon syntax such asinvoice.pdf:evil.exe,file.exe::$DATA, trailinginvoice.exe:, andCON:.pdf(NTFS_ADS_FILENAME, lines 335–343) without false-positiving on spaces after colons (A: Smith.pdf) or numeric timestamps (Invoice 10:30.pdf). Directory separators and drive prefixes emitPATH_TRAVERSAL_FILENAME(lines 315–328, without false-positiving on benign double dots inside filenames such asAcme Inc..pdforReport...final.pdf). Windows/shell wildcard, redirection, and quote characters ([<>"|?*]) emitINVALID_FILENAME_CHARS(lines 380–386), non-alphanumeric or;version-suffixed extensions (invoice.exe;1,invoice.exe") emitMALFORMED_EXTENSIONwhile still matching their stripped extension token against blocked/active sets (lines 422–446), andWINDOWS_RESERVED_STEM_RE(lines 50–51, 388–403) rejects DOS/NT device stems (CON,PRN,AUX,NUL,COM1..9,LPT1..9, including superscript digits andCON:.pdf→WINDOWS_RESERVED_FILENAME). Null/whitespace/Unicode-filler padding (U+200B, Hangul fillerU+3164→EXTENSION_PADDING, lines 361–378) and ASCII/C1 control bytes (CONTROL_CHAR_FILENAME, lines 307–313) are flagged alongside pre-null (invoice.exe\x00.pdf), ADS stream, and punctuation-stripped segments (lines 450–477, 505–519). - Extension policy sets (lines 1–43, 479–533): Classifies extensions into 104 blocked executable/script/package/macro/query formats (
BLOCKED_EXTENSIONS, lines 1–15:.exe,.scr,.lnk,.msi,.ps1,.ps1xml,.wsc,.sct,.hta,.iso,.dmg,.appx,.msix,.library-ms,.search-ms,.one,.doc,.xls,.ppt,.docm,.xlsm,.xll,.iqy,.slk, etc. →BLOCKED_EXTENSION), 14 active local markup/message formats (ACTIVE_CONTENT_EXTENSIONS, lines 17–20:.svg,.svgz,.html,.htm,.xhtml,.shtml,.htmlz,.mht,.mhtml,.xml,.xsl,.xslt,.swf,.eml→ACTIVE_CONTENT_EXTENSION), and 17 archive/container formats whose inner entries have not been unpacked and screened (ARCHIVE_CONTAINER_EXTENSIONS, lines 22–25:.zip,.7z,.rar,.tar,.gz,.tgz,.bz2,.xz,.zst,.cab,.msg, etc. →UNINSPECTED_ARCHIVE_CONTAINER). Multi-dot filenames pairing one of 14 benign decoy tokens (BENIGN_DECOY_EXTENSIONS, lines 27–30) with a blocked or active terminal extension emitDOUBLE_EXTENSION_DECOY(lines 521–533).
Leading Magic-Byte Verification & Truncated-Buffer Handling
When headBytes is supplied, normalizeHeadBytes (lines 88–100) rejects non-byte inputs such as raw strings with INVALID_HEADER_BYTES (lines 536–544), and classifySignatureMatch (lines 107–119) distinguishes "match", "truncated", and "mismatch" so empty or partial byte slices emit TRUNCATED_OR_EMPTY_BYTES (lines 546–553, 673–679) rather than a false pass or false mismatch:
| Finding Code | Signature / Condition (src/attachment.mjs) |
What It Catches |
|---|---|---|
EXECUTABLE_MAGIC_BYTES |
4D 5A (MZ PE), 7F 45 4C 46 (\x7FELF), Mach-O / Java class headers (CF FA ED FE, FE ED FA CF, CE FA ED FE, FE ED FA CE, CA FE BA BE, CA FE BA BF), or #! shebang (#!/bin/sh, #! /bin/sh, lines 78–86, 555–572) |
Native Windows, Linux, or macOS binaries and interpreter scripts renamed to document extensions like wire-instructions.pdf. |
ARCHIVE_MAGIC_MISMATCH |
PK\x03\x04 / PK\x05\x06 / PK\x07\x08 ZIP bytes outside ARCHIVE_CONTAINER_EXTENSIONS (17) and ZIP_PACKAGE_EXTENSIONS (7: .docx, .xlsx, .pptx, .odt, .ods, .odp, .epub), or Rar!, 7z, gzip, bzip2 (BZh1..9), xz, zstd, or MSCF CAB bytes on a non-archive extension (lines 574–606) |
ZIP or compressed archive containers disguised under flat document or plaintext extensions (.txt, .csv, .pdf, .doc). |
OLE2_CONTAINER_MISMATCH |
D0 CF 11 E0 A1 B1 1A E1 Compound File header outside OLE2_PACKAGE_EXTENSIONS (14 legacy extensions, lines 36–39, 608–614) |
Macro-capable or encrypted OLE2 containers renamed to .docx, .xlsx, .pptx, .csv, or .txt. |
PDF_HEADER_MISMATCH, PNG_HEADER_MISMATCH, JPEG_HEADER_MISMATCH, GIF_HEADER_MISMATCH, RTF_HEADER_MISMATCH, OOXML_HEADER_MISMATCH |
Claimed .pdf, .png, .jpg/.jpeg, .gif, .rtf, or .docx/.xlsx/.pptx lacking its required leading bytes (%PDF-, 8-byte PNG, JPEG SOI, GIF87a/89a, {\rtf, or PK ZIP, lines 616–680) |
Header spoofing before files reach downstream PDF, image, RTF, or OOXML parsers. |
HTML_SCRIPT_IN_PLAINTEXT |
Leading 4 KB of 12 plaintext/legacy extensions (TEXT_OR_LEGACY_DOC_EXTENSIONS, lines 41–43, decoded across UTF-8, UTF-16LE/BE BOMs, and null-interleaved UTF-16, lines 209–278, 682–691) containing <script, <!doctype html, <html, <body, <svg, <iframe, <object, <embed, <hta:, MHTML multipart/related headers, or inline on*= handlers |
HTML/MHTML smuggling and active script payloads disguised as CSV, text, or legacy document files. |
2. CSV Formula Neutralization & RFC-4180 Serialization (src/csv.mjs, src/csv-file.mjs)
Spreadsheet applications interpret cells starting with =, +, -, @, or |—including fullwidth/small Unicode variants (=, +, -, @), cells preceded by control/Unicode-whitespace/zero-width prefixes, or cells wrapped inside leading quotes ("=CMD...")—as formulas or DDE expressions when a CSV is opened.
Prefixing every cell starting with - breaks accounting exports where negative currency figures (-$1,250.00, -1,250.00€), decimals (-1,420.55, -.50), scientific notation (-1.5E3), percentages (-12.5%), and parenthesized credit balances (($1,250.00)) are ordinary numeric values. In src/csv.mjs (lines 55–79):
export function isFormulaInjectionCell(
value,
{ allowNegativeNumbers = true, allowPipeTrigger = false } = {}
) {
if (typeof value !== "string" || value.length === 0) return false;
const stripped = value.replace(LEADING_CONTROL_SPACE_OR_QUOTE_RE, "");
if (stripped.length === 0) return false;
const first = stripped[0];
const isTrigger = BASE_FORMULA_TRIGGERS.has(first) || (!allowPipeTrigger && first === "|");
if (!isTrigger) return false;
// Never exempt `-` when preceded by control characters, line separators, or invisible format chars
if (LEADING_UNSAFE_CONTROL_OR_INVISIBLE_RE.test(value)) return true;
if (first === "-" && allowNegativeNumbers) {
const candidate = trimTrailingSpaceAndQuotes(stripped);
if (candidate.length <= 128 && SAFE_NEGATIVE_NUMBER_RE.test(candidate)) {
return false;
}
}
return true;
}
- Control, Unicode-space & quote-wrapped triggers (lines 1–21):
LEADING_CONTROL_SPACE_OR_QUOTE_REstrips leading ASCII/C1 control bytes (\x00-\x20,\x7F-\x9F, including\t,\r,\n,\x0B,\x0C), Unicode whitespace (\s, including NBSPU+00A0, ideographic spaceU+3000, line/paragraph separatorsU+2028/U+2029), zero-width/bidi/filler format characters (U+200B..U+200F,U+3164,U+FE00..U+FE0F,U+FEFF), and leading double quotes before testingBASE_FORMULA_TRIGGERSand|.LEADING_UNSAFE_CONTROL_OR_INVISIBLE_REprevents exempting-whenever control, line-separator, or invisible format characters lead the cell (such as\x0B-1250.00). - Strict negative-balance grammar (lines 26–27):
SAFE_NEGATIVE_NUMBER_REuses literal ASCII space (\x20) rather than\sso multi-line or tab-injected payloads (-\n1+1,-\t=1+1) alongside cell references and expressions (-$A1,-SUM(A1:A4),-1+1) fail the check and receive a leading'. - Parsed array contract &
serializeCsvRow(lines 101–159):sanitizeCsvRows(rows, options)validates thatrowsand every inner row satisfyArray.isArrayand records 0-based{ row, column, originalPreview }coordinates.serializeCsvRow(row, options)sanitizes cells idempotently and formats an RFC-4180 row, doubling internal"characters and enclosing fields in double quotes whenever they contain commas, quotes, CR/LF, tabs,\x0B,\x0C,U+2028/U+2029, outer whitespace, or a neutralized leading'. - Raw UTF-8 CSV text & CLI commands (
src/csv-file.mjs, lines 4–89):checkCsvText(lines 59–71) andsanitizeCsvText(lines 74–89)—exposed in the CLI ascheck-csvandsanitize-csv—parse comma-separated UTF-8 text by logical record so embedded line breaks inside quoted fields never shift coordinates, report 1-based spreadsheet coordinates (header = row 1), reject NUL bytes,sep=directives, unclosed quotes, and ragged row widths before emitting output, preserve a leading UTF-8 BOM, and serialize with CRLF record separators. See the four-invoice walkthrough indocs/checking-a-change.md.
3. Header Spoofing, WHATWG HTML5 Comments & Linear CSS Parsing (src/email.mjs)
Inbound HTML mail routed into automated triage can hide instructions from human reviewers while exposing them to HTML-to-text extractors, or craft malformed comments and long attribute strings to stall backtracking regexes. inspectInboundEmail (lines 1384–1466) runs four checks in linear O(n) time:
- Raw-first RFC 5322 & RFC 2047 sender/comment spoofing (
FROM_DISPLAY_NAME_SPOOF&REPLY_TO_DOMAIN_MISMATCH, lines 1092–1421): Decoding RFC 2047 encoded-words before RFC 5322 tokenization would allow payloads like=?UTF-8?Q?"?=or=?UTF-8?Q?<...>?=to inject synthetic quotes, comments, or angle-brackets. Instead,splitTopLevelMailboxes(lines 1147–1190) andparseSingleMailbox(lines 1197–1344) split mailboxes and parse quotes,(comment)blocks,<angle-addr>specifications, and bareaddr-spectokens on the raw header first—treating=?charset?B/Q?...?=atoms viascanRfc2047WordEnd(lines 1128–1145) as opaque—and decode RFC 2047 words strictly inside display-label and comment parts. Thusattacker@evil.example (ceo@company.com)resolvesaddress = "attacker@evil.example"and exposes(ceo@company.com)indisplayLabel.findSpoofedDisplayEmail(lines 1352–1374) decodes HTML entities (@), folds fullwidth (@) and Cyrillic/Greek confusables (foldConfusables, lines 82–128), and collapses spaced@tokens without false-positiving when a plain display name matches the actual address, while every domain in multi-addressReply-Toheaders is checked againstfromDomains. - Invisible Unicode, Variation Selectors & Plane-14 Tag stripping (
INVISIBLE_UNICODE_CHARS, lines 4–5, 1423–1432, 1462–1463):INVISIBLE_UNICODE_REdetects soft hyphens (U+00AD), grapheme/bidi controls, Hangul/Braille/Khmer fillers (U+3164,U+2800,U+FFA0,U+17B4..U+17B5), zero-width spaces/joiners, BMP Variation Selectors (U+FE00..U+FE0F), interlinear annotations (U+FFF9..U+FFFB), Plane-14 Unicode Tags (U+E0000..U+E007F), and Variation Selectors Supplement (U+E0100..U+E01EF)—including entity-encoded forms in HTML (​,󠁁)—escalating severity tohighat 8+ characters and stripping them fromsanitizedSubjectandsanitizedText. - WHATWG HTML5 comment scanner & linear CSS declaration parser (
HIDDEN_HTML_CONTENT, lines 48–50, 137–1028): Naive regex comment stripping (/<!--[\s\S]*?-->/g) diverges from HTML5 parsing on abrupt closures (<!-->,<!--->), bang closures (<!-- x --!>), and unclosed comments—allowing two malformed comments to swallow a hidden element in between while browsers still parse it.skipHtmlComment(lines 854–871) implements the WHATWG HTML5 comment closures directly, memoizesstate.noTerminator, and skips consecutive unclosed<!--openers in one sticky match so repeated unclosed comments stayO(n):
function skipHtmlComment(html, lt, state) {
const next = lt + 4;
if (html[next] === ">") return next + 1;
if (html.startsWith("->", next)) return next + 2;
if (!state.noTerminator) {
const closing = /--!?>/g;
closing.lastIndex = next;
if (closing.test(html)) return closing.lastIndex;
state.noTerminator = true;
}
// Without a closing delimiter, discard only the openers and inspect the rest.
const openers = /(?:<!--)+/y;
openers.lastIndex = lt;
openers.test(html);
return openers.lastIndex;
}
For inline style attributes and quote-aware <style> blocks (extractStyleBlocks, lines 873–919), decodeHtmlEntities (lines 48–50, 137–166) strips arbitrary-length leading zeros on decimal and hex character references (:) and resolves named entities including :, ;, 
, and 	; containsHiddenCssDeclaration (lines 712–721) strips CSS /*...*/ comments (testing both space and empty-string replacement to catch dis/**/play:none) and decodes CSS backslash escapes; and checkCleanedCssDeclarations (lines 569–710) plus scanCleanedStylesheetRules (lines 740–837) parse semicolon-delimited prop: value declarations and stylesheet rule blocks in strictly linear O(n) time (~2 ms on 200 KB adversarial inputs), terminating unclosed CSS strings on unescaped \n/\r/\f per CSS Syntax Level 3 <bad-string-token> recovery and stripping <!--/--> (CDO/CDC) tokens (trimCssCdoCdcAndSpace, lines 723–739). Checks cover display:none, visibility:hidden|collapse, content-visibility:hidden, opacity <= 0.02 and filter:opacity(...) (via parseCssNumberAndUnit, lines 215–278, so opacity:0.8 passes), font-size <= 1px (<= 0.08em/rem, <= 8%, including font shorthand, while 0.75em passes), color:transparent and near-zero-alpha #rgba/#rrggbbaa/rgb()/rgba()/hsl()/oklch(), matching solid foreground and background colors on the same rule (color:#fff;background:#fff), zero/1px dimensions paired with overflow:hidden|clip, offscreen negative offsets (left:-999px, margin-left:-9999px, text-indent:-9999em), near-zero transform:scale(...) / scale:0, and clip:rect(0,0,0,0) / clip-path:circle(0)|ellipse(0...)|inset(50%)|polygon(0...), alongside DOM attributes hidden, aria-hidden="true", <input type="hidden">, <template>, and collapsed <details> (without open, lines 927–1028), while skipping conditional @media (...) / print / speech layout rules (lines 817–825).
Finally, extractHtmlTextForInspection (lines 1030–1090) strips HTML5 comments and tags (collapsing inline formatting tags such as <span> and <b> without inserting whitespace), decodes entities, strips INVISIBLE_UNICODE_RE, and folds confusables before testing PROMPT_OVERRIDE_PATTERNS (INSTRUCTION_OVERRIDE_PATTERN, lines 7–14, 1442–1458).
4. Randomized Session-Scoped PII Tokenization (src/redact.mjs)
If a redactor emits predictable bare placeholders such as <ACCOUNT_1>, an untrusted sender can embed obfuscated text like <ACCOUNT\u200B_1> or fullwidth <ACCOUNT_1> that evades literal-token matching on input, gets normalized into <ACCOUNT_1> by a downstream LLM, and causes restore() to substitute another entity's real value into attacker-controlled output. createRedactor() (lines 40–49 and 68–92) prevents token forgery by appending a per-session 6-hex-character CSPRNG nonce (<KIND_n_nonce>) by default:
const LITERAL_TOKEN_SRC = String.raw`<(?:EMAIL|SSN|PHONE|ACCOUNT|LITERAL)_\d+(?:_[0-9a-fA-F]{4,16})?>`;
const REDACT_RE = new RegExp(
`(?<email>${EMAIL_SRC})|(?<ssn>${SSN_SRC})|(?<intlPhone>${INTL_PHONE_SRC})|(?<account>${ACCOUNT_SRC})|(?<nanpPhone>${NANP_PHONE_SRC})|(?<literal>${LITERAL_TOKEN_SRC})`,
"g"
);
// Single-pass restoration regex; matches both nonced (`<EMAIL_1_9f2c1a>`) and deterministic
// (`<EMAIL_1>`) tokens, substituting only tokens present in this session's `tokenToValue` map.
const RESTORE_TOKEN_RE = /<(?:EMAIL|SSN|PHONE|ACCOUNT|LITERAL)_\d+(?:_[0-9a-f]{6})?>/g;
export function createRedactor({ deterministic = false } = {}) {
const sessionNonce = deterministic ? "" : `_${randomBytes(3).toString("hex")}`;
const valueToToken = new Map();
const tokenToValue = new Map();
const counts = { EMAIL: 0, SSN: 0, PHONE: 0, ACCOUNT: 0 };
let literalCount = 0;
function assignToken(kind, rawValue) {
const normalizedKey =
kind === "LITERAL" ? `LITERAL:${rawValue}` : `${kind}:${rawValue.toLowerCase()}`;
if (valueToToken.has(normalizedKey)) {
return valueToToken.get(normalizedKey);
}
let token;
if (kind === "LITERAL") {
literalCount += 1;
token = `<LITERAL_${literalCount}${sessionNonce}>`;
} else {
counts[kind] += 1;
token = `<${kind}_${counts[kind]}${sessionNonce}>`;
}
valueToToken.set(normalizedKey, token);
tokenToValue.set(token, rawValue);
return token;
}
- Single-pass tokenization & precision boundaries (lines 28–45, 53–57, 94–110):
redact()matches standard and quoted ASCII RFC 5321 emails, hyphen/space/en-dash US SSNs (excluding unassigned SSA prefixes000,666,900–999, group00, and serial0000),+-prefixed ITU-T E.164/E.123 international phones (7–15 digits verified inisValidIntlPhone, with optional(0)trunk markers andext/ext./extension/xsuffixes such as+44 20 7946 0958 ext. 12), 12–19 digit contiguous or4-4-4-1..7/4-4-4-4-1..3/4-6-5space/hyphen/dot-grouped card/account numbers, and 10/11-digit NANP phones—while bounding away ISO dates (2026-11-16), 4-part dotted software versions (1.314.555.0199), ISBNs, and currency amounts ($1,234,567,890,123.45). Pre-existing token-shaped strings are isolated as<LITERAL_n_nonce>; pass{ deterministic: true }only when bare<EMAIL_1>tokens without a random nonce are explicitly required. - Single-pass restoration (lines 112–118):
restore()runs a single callback pass overRESTORE_TOKEN_RE, replacing only tokens present in that session'stokenToValuemap so literal token text inside an original value never undergoes second-pass substitution.
5. Scope & Known Limitations
inbox-guard is a pre-triage screening layer; its exact boundaries match inbox-guard/README.md:
- Pattern-only PII redaction (
src/redact.mjs): Tokenization is strictly regex-based. It does not detect unstructured person or company names, street addresses, non-ASCII UTF-8/IDN email addresses (josé@example.com,user@bücher.de) unless converted to ASCII/Punycode upstream, alphanumeric IBANs, 8–11 digit domestic bank account numbers or contiguous 9-digit SSNs/ABA routing numbers (excluded to avoid false positives on order and invoice IDs; conversely, bare 12–19 digit integers such as 13-digit millisecond Unix timestamps are tokenized as<ACCOUNT>), or domestic non-NANP phone numbers written without a+country code. Token mappings exist only in in-process memory. - Leading-header attachment checks (
src/attachment.mjs):checkAttachmentinspects filenames and leading magic bytes at byte offset 0. It does not parse full container structures, unpack archives, run antivirus signatures, detect polyglot payloads appended after a valid%PDF-header, or inspect structurally valid PDF streams for/JavaScript//OpenActiondictionaries or OOXML.docx/.xlsxpackages for external template relationships. Archive extensions are flaggedUNINSPECTED_ARCHIVE_CONTAINER, and legacy binary Office extensions (.doc,.xls,.ppt) are blocked outright because macro streams inside OLE2 containers cannot be ruled out from header bytes alone. - Static header & HTML email screening (
src/email.mjs):inspectInboundEmailchecks RFC 5322From/Reply-Toheaders and static HTML/CSS hiding constructs, not cryptographic sender authentication (SPF,DKIM, andDMARCmust be verified by the receiving mail gateway) or full browser cascade inheritance across separate ancestor/descendant rules (for example,color:whiteon a child element whose white background is inherited from an outer table cell, orReply-Toacross authorized parent/child subdomains such asmail.vendor.examplevs.vendor.example, which still raises amedium-severity domain-mismatch signal for caller review).INSTRUCTION_OVERRIDE_PATTERNrules are static phrase heuristics that an adaptive attacker can paraphrase; never rely on them in place of privilege separation, tool allowlists, and mandatory human approval before external sends or financial actions. - CSV format and import settings (
src/csv.mjs,src/csv-file.mjs): Raw UTF-8 comma-separated CSV text is supported viacheckCsvText/sanitizeCsvTextand the CLI commandscheck-csv/sanitize-csv(alongsidesanitizeCsvRows/serializeCsvRowfor already-parsed 2Dstring[][]cell arrays). The raw-text commands read UTF-8 input in memory, require uniform column counts per record, reject NUL bytes andsep=directives, preserve a UTF-8 byte-order mark when present, and emit CRLF record separators (reporting 1-based spreadsheet coordinates, versus 0-based indexes insanitizeCsvRows). Prefixing dangerous cells with'leaves a literal leading apostrophe when read by non-spreadsheet consumers; spreadsheet type inference, display of the leading apostrophe, and behavior after re-saving depend on the spreadsheet application and its import settings.
npm test, including 200 KB linear-time anti-ReDoS timing checks) and GitHub CodeQL scanning. Report bypasses privately via GitHub Private Vulnerability Reporting (SECURITY.md).