repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/web/extract.ts

Raw
File outline
// HTML semantic container extraction
// Extracts the main content area before feeding to pandoc
// Uses balanced tag counting for nested elements

// ── Prompt injection hardening ──────────────────────────────────────────
// Strip known injection vectors from HTML before content extraction.
// These are deterministic, zero-cost filters — no ML, no arms race.
// They remove delivery mechanisms, not payload content.

export function sanitizeInjectionVectors(html: string): string {
  let out = html;

  // 1. Remove <script> blocks (executable code, never content)
  out = out.replace(/<script[\s>][\s\S]*?<\/script>/gi, "");

  // 2. Remove <style> blocks (CSS can carry injection payloads)
  out = out.replace(/<style[\s>][\s\S]*?<\/style>/gi, "");

  // 3. Remove <iframe>/<object>/<embed> (nested contexts)
  out = out.replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi, "");
  out = out.replace(/<object[\s>][\s\S]*?<\/object>/gi, "");
  out = out.replace(/<embed[^>]*>/gi, "");

  // 4. Remove <template>/<noscript> — inert content abused for injection
  out = out.replace(/<template[\s>][\s\S]*?<\/template>/gi, "");
  out = out.replace(/<noscript[\s>][\s\S]*?<\/noscript>/gi, "");

  // 5. Remove hidden inputs — #1 injection vector per BrowseSafe research
  out = out.replace(/<input[^>]+type=["']hidden["'][^>]*>/gi, "");
  out = out.replace(/<input[^>]+value=["'][^"']*["'][^>]*>/gi, (m) => {
    if (/type=["']hidden["']/i.test(m)) return "";
    return m;
  });

  // 6. Remove elements with HTML hidden attribute (standalone, not inside attr values)
  out = out.replace(/<(\w+)([^>]*\shidden(?:\s[^>]*>|>|\/>))[\s\S]*?<\/\1>/gi, "");

  // 7. Remove HTML comments — common injection hiding spot
  out = out.replace(/<!--[\s\S]*?-->/g, "");

  // 8. Remove visually-hidden elements via inline styles
  //    Catches: display:none, visibility:hidden, opacity:0,
  //    font-size:0, color:white/transparent, position:offscreen
  const visualHidePatterns = [
    /display\s*:\s*none/i,
    /visibility\s*:\s*hidden/i,
    /opacity\s*:\s*0(?!\.)/i,       // opacity:0 but not opacity:0.5
    /font-size\s*:\s*0/i,           // font-size:0, font-size:0px
    /color\s*:\s*(white|#fff(?:fff)?|transparent)\s*(?:[;"']|$)/i,
    /left\s*:\s*-\d{4,}/i,          // left:-9999px (offscreen)
  ];
  out = out.replace(
    /<(\w+)([^>]*style=["'])([^"']*)(["'][^>]*)>([\s\S]*?)<\/\1>/gi,
    (_match, tag, before, styleVal, after, _content) => {
      const isHidden = visualHidePatterns.some((p) => p.test(styleVal));
      return isHidden ? "" : _match;
    },
  );

  // 9. Strip suspicious <meta> tags (can carry instructions in content attr)
  //    Keep charset and viewport — only remove those with long content values
  out = out.replace(/<meta[^>]+content=["'][^"']{50,}["'][^>]*>/gi, "");

  // 10. Strip aria-label, alt, title from non-image elements
  //     These attributes are invisible to humans but visible to LLMs
  out = out.replace(/<([^\s>]+)([^>]*?)\b(aria-label|alt|title)=["'][^"']*["']([^>]*?)>/gi,
    (_match, tag, before, _attr, after) => {
      if (/^(img|area|input)$/i.test(tag)) return _match; // keep alt on images
      return `<${tag}${before}${after}>`;
    }
  );

  return out;
}

export function extractMainContent(html: string): string {
  // Sanitize injection vectors before extraction
  html = sanitizeInjectionVectors(html);

  // Try <article> first (most semantic, usually cleanest)
  const article = matchTag(html, "article");
  if (article !== null) return article;

  // Try <div id="mw-content-text"> (Wikipedia article body)
  // Before <main> because Wikipedia's <main> includes nav chrome
  const mwContent = matchId(html, "mw-content-text", "div");
  if (mwContent) return mwContent;

  // Try <div id="docContent"> (PostgreSQL/Sphinx documentation)
  const docContent = matchId(html, "docContent", "div");
  if (docContent) return docContent;

  // Try <div id="content"> (generic, common)
  const contentDiv = matchId(html, "content", "div");
  if (contentDiv) return contentDiv;

  // Try <main>
  const main = matchTag(html, "main");
  if (main) return main;

  // Try role="main" on any element
  const roleMain = matchRoleMain(html);
  if (roleMain) return roleMain;

  // Fallback: full page
  return html;
}

function matchTag(html: string, tag: string): string | null {
  const openRe = new RegExp(`<${tag}(?:\\s[^>]*)?>`, "i");
  const openMatch = html.match(openRe);
  if (!openMatch) return null;

  const startIdx = openMatch.index! + openMatch[0].length;
  return extractBalanced(html, startIdx, tag);
}

function extractBalanced(
  html: string,
  startIdx: number,
  tagName: string,
): string | null {
  let depth = 1;
  let pos = startIdx;

  // Simple state machine: scan for open/close tags of the same name
  const openTag = `<${tagName}`;
  const closeTag = `</${tagName}`;

  while (depth > 0 && pos < html.length) {
    const nextOpen = html.indexOf(openTag, pos);
    const nextClose = html.indexOf(closeTag, pos);

    if (nextClose === -1) return null;

    if (nextOpen !== -1 && nextOpen < nextClose) {
      // Find the end of this open tag
      const tagEndIdx = html.indexOf(">", nextOpen);
      if (tagEndIdx === -1) return null;

      // Check if it's self-closing: <tag .../>
      if (html[tagEndIdx - 1] === "/") {
        // Self-closing — skip, don't change depth
        pos = tagEndIdx + 1;
        continue;
      }

      // Check it's a real open tag (not part of close or attribute)
      const afterOpen = html[nextOpen + openTag.length];
      if (afterOpen === ">" || afterOpen === " ") {
        depth++;
        pos = tagEndIdx + 1;
        continue;
      }
    }

    depth--;
    if (depth === 0) {
      return html.slice(startIdx, nextClose);
    }
    pos = html.indexOf(">", nextClose) + 1;
  }
  return null;
}

function matchRoleMain(html: string): string | null {
  const re = /<(\w+)([^>]*\srole=["']main["'][^>]*)>/i;
  const m = html.match(re);
  if (!m) return null;
  const tag = m[1];
  const startIdx = html.indexOf(m[0]) + m[0].length;
  return extractBalanced(html, startIdx, tag);
}

function matchId(html: string, id: string, tag: string): string | null {
  // Match tag with id= attribute (prefix and suffix can be empty)
  const re = new RegExp(`<${tag}[^>]*\\bid=["']${id}["'][^>]*>`, "i");
  const m = html.match(re);
  if (!m) return null;
  const startIdx = html.indexOf(m[0]) + m[0].length;
  return extractBalanced(html, startIdx, tag);
}