Skip to main content
Developer & Creator Documentation

Sandbox Isolation & Linear-Time $\mathcal{O}(N)$ Sanitizer — Formal Security Specification

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:

Open AI Studio Direct-Answer FAQ Hub Machine-Readable Corpus (/llms-full.txt)

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:

  1. T1 — Cross-Site Scripting (XSS) & Parent Session Theft: Malicious or hallucinated game scripts attempting to read window.parent.document, steal ypg_sid / ypg_vid cookies, or mutate studio UI DOM.
  2. 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">.
  3. T3 — Regular Expression Denial of Service (ReDoS): Crafted pathological HTML attributes, deeply nested CSS image-set() calls, unclosed JS regex literals, or multi-kilobyte data:image/svg+xml payloads stalling the Node.js event loop via O(2^N) or O(N^2) backtracking.
  4. 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>-->).
  5. T5 — Path Traversal, Symlink Escape & Cookie Forgery: Crafting /runtime/../../storage/users.json requests, 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

StageSubsystemFormal StandardSecurity Transformation
01extractHtmlDocument()HTML5 Document EnvelopeExtracts exact <!DOCTYPE html>...</html> (or <html>...</html>) span from markdown code fences; rejects incomplete envelopes immediately.
02parseHtmlTokenAt() + createForeignTracker()WHATWG HTML5 §13.2.5 & §13.2.6Tokenizes 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.
03Forbidden Tag EliminationHTML5 Subdocument & Plugin SinksStrips 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> ScrubbingHTML5 Metadata & Resource HintsDrops <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).
05RCDATA CanonicalizationHTML5 RCDATA (<title>, <textarea>)Scans to exact closing tag via findClosingRawOrRcdataTag and escapes < / > inside body so <!-- comment smuggling cannot desynchronize downstream parsers.
06sanitizeCssExternalUrls()W3C CSS Syntax Module Level 3Zero-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.
07findClosingScriptTag()WHATWG HTML5 §13.2.5.19–36Exact 7-state DFA (DATA \leftrightarrow ESCAPED \leftrightarrow DOUBLE_ESCAPED) locating the true browser </script> boundary; drops unclosed <script> blocks and <script type="importmap">.
08Vendor CDN RewriteSame-Origin Engine WhitelistRewrites 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.
09healInlineModuleCode()ECMA-262 Module-to-Classic HealingConverts 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.
10sanitizeInlineJsUrls()ECMA-262 String & Template LexerBitmask-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).
11sanitizeCommonAndElementAttrs()HTML5 & SVG Attribute PolicyDeduplicates 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 '#'.
12SDK Injection & validateInlineScripts()Node.js node:vm V8 CompilerInjects <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 ComponentInput Size ParameterWorst-Case Time ComplexityAuxiliary SpaceBacktracking / Recursion
HTML5 & Foreign TokenizerDocument length NΘ(N)O(D_foreign + N)Zero backtracking; iterative foreign stack
7-State <script> Boundary ScannerScript 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 LookaheadScript 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 ValidatorPayload length SO(S) for depth d ≤ 3O(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 SinkAllowed TargetsAction on Disallowed / External Target
<script src>/vendor/phaser.min.js, /vendor/three.min.jsStripped 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 onlyStripped (null-origin iframes cannot cross-origin-reference external SVG sprites)
fetch() / XMLHttpRequestSame-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 / sendBeaconNone (100% offline single-player sandbox)Neutralized by SDK shim + blocked by RUNTIME_CSP_HEADER (default-src 'self' 'unsafe-inline' data: blob:)
Worker / SharedWorkerblob:null/* or whitelisted local vendor scriptReturns inert no-op worker stub on external URLs
window.localStorage / sessionStorageEphemeral per-load ES Map shimPrevents 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 HeaderParent Studio & SSR Pages (/* except /runtime/*)Isolated Game Sandbox (/runtime/:slug/*)
Content-Security-Policydefault-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-OptionsSAMEORIGIN (prevents clickjacking of studio/auth UI)Omitted on /runtime/* so <iframe sandbox="allow-scripts allow-pointer-lock"> embeds cleanly
X-Content-Type-Optionsnosniffnosniff
X-Robots-TagIndexed via SSR <meta name="robots"> (index, follow)noindex (prevents raw iframe URLs from competing with canonical /games/:slug pages)
Cross-Origin-Resource-PolicyDefault same-origincross-origin + Access-Control-Allow-Origin: * (allows null-origin OOPIF to load its own /runtime/:slug/assets/*)
Iframe sandbox AttributeN/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 / CookieFormatSecret KeyTTLSecurity Attributes & Anti-Tamper Controls
ypg_vid (Visitor Cookie)vis_<32-hex>.<base64url-hmac>SESSION_SECRET30 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_SECRET7 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_SECRET10 min (600 s)Double-submit cookie + signed nonce + sanitizeReturnTo() open-redirect guard (blocks //, /\, /auth/*).
adGrantToken (Ad Unlock Grant)<base64url-json>.<base64url-hmac>AD_HMAC_SECRET5 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:

  1. ReDoS Pathological Input Timing Gate: 100 KB+ payloads of repeated unclosed <script><!--, nested url(url(url(, thousands of / division/regex ambiguities, and malformed srcset attributes complete sanitization in < 25 ms (linear scaling verified empirically).
  2. 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)">.
  3. Filesystem Traversal & Null-Byte Injection: Verified HTTP 400/404 rejection on /runtime/neon-orbit-defender/..%2f..%2fcatalog.json, /runtime/con/index.html, /runtime/neon-orbit-defender/index.html%00.png, and symlink-escape probes.