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

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;
}

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:

  1. 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) and parseSingleMailbox (lines 1197–1344) split mailboxes and parse quotes, (comment) blocks, <angle-addr> specifications, and bare addr-spec tokens on the raw header first—treating =?charset?B/Q?...?= atoms via scanRfc2047WordEnd (lines 1128–1145) as opaque—and decode RFC 2047 words strictly inside display-label and comment parts. Thus attacker@evil.example (ceo@company.com) resolves address = "attacker@evil.example" and exposes (ceo@company.com) in displayLabel. findSpoofedDisplayEmail (lines 1352–1374) decodes HTML entities (&#64;), 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-address Reply-To headers is checked against fromDomains.
  2. Invisible Unicode, Variation Selectors & Plane-14 Tag stripping (INVISIBLE_UNICODE_CHARS, lines 4–5, 1423–1432, 1462–1463): INVISIBLE_UNICODE_RE detects 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 (&#8203;, &#xE0041;)—escalating severity to high at 8+ characters and stripping them from sanitizedSubject and sanitizedText.
  3. 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, memoizes state.noTerminator, and skips consecutive unclosed <!-- openers in one sticky match so repeated unclosed comments stay O(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 (&#x000000000000000000003a;) and resolves named entities including &colon;, &semi;, &NewLine;, and &Tab;; 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;
  }

5. Scope & Known Limitations

inbox-guard is a pre-triage screening layer; its exact boundaries match inbox-guard/README.md:

Verification & Vulnerability Reporting Tested via Node's built-in runner (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).