Skip to main content
Developer & Creator Documentation

System Architecture — Multi-Surface Web, Sandbox Runtime, Atomic Storage & Mobile Ecosystem

YourPlayground.games partitions execution into four strictly isolated planes so that untrusted AI-synthesized game code, high-crawlability SSR HTML discovery pages, stateful HMAC-authen

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

System Architecture — Multi-Surface Web, Sandbox Runtime, Atomic Storage & Mobile Ecosystem

Document ID: YPG-ARCH-001 | Index: docs/README.md

Runtime Baseline: Node.js >= 22.0.0 (ESM), Express ^5.1.0, @google/genai ^3.6.1, Phaser 3.90.0, Three.js 0.160.1

Canonical Origin: https://www.yourplayground.games | Local Port: http://localhost:9033


1. Architectural Overview & Separation of Planes

YourPlayground.games partitions execution into four strictly isolated planes so that untrusted AI-synthesized game code, high-crawlability SSR HTML discovery pages, stateful HMAC-authenticated API transactions, and native mobile/tablet clients coexist without privilege escalation or state corruption:

  1. Plane A — Server-Side Rendered (SSR) Discovery & Studio Shell Plane (src/routes/pagesRouter.mjs, src/routes/discoveryRouter.mjs, src/views/*.mjs): Serves complete, zero-JS-required HTML5 pages, Schema.org @graph JSON-LD graphs, XML sitemaps, and LLM corpora under strict SSR_CSP_HEADER, X-Frame-Options: SAMEORIGIN, and Cache-Control: no-store, no-cache, must-revalidate.
  2. Plane B — Stateful Control & Synthesis API Plane (src/routes/api*.mjs, src/routes/authRouter.mjs, src/services/*.mjs): Enforces per-route JSON payload caps (64kb for auth/ads, 512kb for games), timing-safe HMAC-SHA256 cookie authentication (ypg_vid, ypg_sid), single-use adGrantToken burn semantics, and Vertex AI orchestration (gemini-4-neon + gemini-4-carbon).
  3. Plane C — Null-Origin OOPIF Game Execution Plane (src/routes/runtimeRouter.mjs, src/services/gameSanitizer.mjs): Serves pre-sanitized single-file game bundles under /runtime/:slug/* inside <iframe sandbox="allow-scripts allow-pointer-lock"> without allow-same-origin. The browser assigns an opaque null origin (window.origin === "null"), severing access to parent DOM, document.cookie, IndexedDB, and localStorage.
  4. Plane D — Crash-Safe Persistence & Cloud Sync Plane (src/storage/atomicJson.mjs, Firebase Mobile Backend): Provides serialized in-process promise-queue locking plus POSIX/NTFS write-fsync-rename copy-on-write durability on the web origin, complemented by Firebase (Auth, Firestore, Storage, Remote Config, App Check) for universal iOS and Android phone/tablet apps.

2. Express 5 HTTP Engine & Deterministic 12-Stage Middleware Pipeline

The HTTP server entrypoint in server.mjs constructs the Express 5 application via createApp(options) in src/app.mjs and binds strictly to port 9033 (configurable via PORT), registering idempotent SIGINT/SIGTERM graceful shutdown handlers with a 4000 ms .unref() drain timer.

Ordering inside createApp() is a critical security and protocol invariant. Changing middleware order alters CSP headers, body-size limits, or route shadowing:

flowchart TD
    Req["Incoming HTTP Request (:9033)"] --> M1["1. Malformed URL Guard<br/>decodeURIComponent(req.path) check<br/>(skips /runtime/*; returns 400 JSON/text)"]
    M1 --> M2["2. Security Header Layer<br/>X-Content-Type-Options: nosniff<br/>Outside /runtime/*: X-Frame-Options: SAMEORIGIN + SSR_CSP_HEADER"]
    M2 --> M3["3. Service Worker Endpoint (GET /sw.js)<br/>Cache-Control: no-store, no-cache, must-revalidate<br/>Service-Worker-Allowed: /"]
    M3 --> M4["4. Favicon Handler (GET /favicon.ico)<br/>Serves public/brand/favicon.svg (max-age=3600)"]
    M4 --> M5["5. Static Asset Server<br/>express.static(publicDir, { index: false, maxAge: '1h' })<br/>Strictly scoped to public/ — NEVER ROOT_DIR"]
    M5 --> M6["6. HMAC Session Middleware<br/>Parses/mints signed ypg_vid (30d) & verifies ypg_sid (7d)"]
    M6 --> M7["7. Domain & Runtime Routers<br/>runtimeRouter -> apiConfigRouter -> apiAdsRouter (64kb)<br/>-> apiGamesRouter (512kb) -> authRouter (64kb)"]
    M7 --> M8["8. Fallback /api JSON Parser (1mb)<br/>Catches malformed JSON on unmounted /api/* paths"]
    M8 --> M9["9. Discovery & IndexNow Endpoints<br/>discoveryRouter (/robots.txt, /sitemap.xml, /llms*.txt, /.well-known/*, /ads.txt)<br/>followed by /indexnow.txt & /:indexNowKey.txt"]
    M9 --> M10["10. SSR No-Store Header & Pages Router<br/>Sets Cache-Control: no-store, no-cache, must-revalidate<br/>Mounts /, /showcase, /categories/*, /games/:slug, /faq & 301s"]
    M10 --> M11["11. Context-Aware 404 Catch-All<br/>JSON 404 for /api/* & /.well-known/*<br/>Plaintext 404 for asset prefixes/extensions; SSR HTML 404 for pages"]
    M11 --> M12["12. 4-Argument Error Boundary<br/>Maps entity.parse.failed->400, entity.too.large->413, URIError->400, 500<br/>Zero stack-trace leakage"]

Key Pipeline Design Decisions

  • Public Directory Confinement (Stage 5): express.static mounts env.publicDir (c:\Berk\YourPlayGroundGames\public) with index: false. Server source (src/), secrets, scripts (scripts/), and raw ledgers (storage/) are unmounted, and Stage 11 explicitly matches ASSET_OR_INTERNAL_PREFIX_REGEX (/storage, /src, /scripts, /tests, /.agents, /.git) to return a bare 404 Resource not found. without invoking SSR view rendering.
  • Per-Route Body Limit Preservation (Stage 7 before Stage 8): Mounting apiAdsRouter (64kb), authRouter (64kb), and apiGamesRouter (512kb) before the fallback /api 1mb parser ensures tight memory bounds on unauthenticated endpoints while guaranteeing JSON 400 INVALID_JSON responses on malformed bodies sent to unknown /api/* routes.
  • Discovery Shadow Prevention (Stage 9): Mounting createDiscoveryRouter before INDEXNOW_FILE_REGEX (/^\/([a-zA-Z0-9-]{8,128})\.txt$/) guarantees that /robots.txt, /llms.txt, /llms-full.txt, and /ads.txt can never be shadowed even if INDEXNOW_KEY were misconfigured.

3. Null-Origin OOPIF Sandbox Runtime Architecture

AI-generated games execute inside an isolated <iframe id="ypg-game-iframe" sandbox="allow-scripts allow-pointer-lock" allow="fullscreen"> rendered by renderPlayableStage() in src/views/layout.mjs and served by src/routes/runtimeRouter.mjs.

sequenceDiagram
    autonumber
    participant Parent as Parent Studio Shell<br/>(https://www.yourplayground.games)
    participant Router as runtimeRouter.mjs<br/>(/runtime/:slug/*)
    participant OOPIF as Sandboxed Game Iframe<br/>(origin: "null", RUNTIME_CSP_HEADER)
    participant SDK as Injected YourPlaygroundSDK<br/>(<script id="ypg-sdk">)

    Parent->>Router: GET /runtime/:slug/index.html
    Note over Router: Validate slug regex + Windows reserved names<br/>Verify path containment + fs.realpath() anti-symlink<br/>Increment plays asynchronously
    Router-->>OOPIF: 200 text/html + RUNTIME_CSP_HEADER + X-Robots-Tag: noindex
    OOPIF->>SDK: Synchronous <head> bootstrap (shimming Storage, fetch, XHR, WebSocket, Worker, DOM sinks)
    OOPIF->>Router: GET /vendor/phaser.min.js or /vendor/three.min.js (if 2D/3D engine)
    Router-->>OOPIF: 200 text/javascript (local same-origin static bundle)
    OOPIF->>SDK: Game initializes active loop & calls YourPlaygroundSDK.ready({ engine })
    SDK-->>Parent: postMessage({ source: 'YourPlaygroundSDK', type: 'YPG_READY', payload }, '*')
    Parent->>OOPIF: Virtual Touch Deck / Keyboard -> postMessage({ type: 'YPG_INPUT', key, action }, '*')
    SDK->>OOPIF: Updates sdk.keys[code] & dispatches synthetic KeyboardEvent('keydown'/'keyup')
    OOPIF->>SDK: Score increment -> YourPlaygroundSDK.reportScore(score)
    SDK-->>Parent: postMessage({ source: 'YourPlaygroundSDK', type: 'YPG_SCORE', payload: { score, highScore } }, '*')
    OOPIF->>SDK: Match end -> YourPlaygroundSDK.gameOver(finalScore)
    SDK-->>Parent: postMessage({ source: 'YourPlaygroundSDK', type: 'YPG_GAME_OVER', payload: { score, highScore } }, '*')

Multi-Layer Runtime Containment

  1. Absence of allow-same-origin: Because sandbox="allow-scripts allow-pointer-lock" omits allow-same-origin, Chromium, WebKit, and Gecko serialize the iframe's origin as "null". Any attempt inside the game to read window.parent.document throws a SecurityError, and document.cookie / window.localStorage throw DOMException (gracefully shimmed in-memory by YPG_SDK_SCRIPT_TAG via an ES Map so games using localStorage for high-score persistence never crash).
  2. Cross-Origin Subresource Loading (CORP + CORS): Because a null-origin iframe requests /vendor/phaser.min.js, /vendor/three.min.js, or ./assets/sprite.png as cross-origin subrequests relative to "null", applyRuntimeSecurityHeaders() sets Cross-Origin-Resource-Policy: cross-origin and Access-Control-Allow-Origin: * exclusively on /runtime/* while enforcing RUNTIME_CSP_HEADER (default-src 'self' 'unsafe-inline' data: blob:; img-src 'self' data: blob:; media-src 'self' data: blob:).
  3. Filesystem & Symlink Traversal Hardening: runtimeRouter.mjs rejects %00, %5c, \, and %2e%2e in raw URLs, blocks Windows device names (CON, PRN, AUX, NUL, COM1–COM9, LPT1–LPT9), restricts subpaths strictly to index.html, cover.(png|jpe?g), or assets/<safe-name>.(png|jpe?g|svg|gif|mp3|wav|ogg|json), and resolves fs.realpath(gameDir) vs fs.realpath(targetPath) prior to reading bytes.
  4. Early Message Replay Buffer: Fast Canvas 2D games loaded from warm disk cache can emit YPG_READY before <script type="module" src="/assets/js/playerStage.mjs"> finishes module evaluation. An inline <head> listener in layout.mjs captures up to 20 early YourPlaygroundSDK messages in window.__ypgEarlyMessages and replays them deterministically upon initPlayerStage() hydration.

4. Crash-Safe Copy-on-Write Persistence (src/storage/atomicJson.mjs)

All local state resides under storage/ (catalog.json, users.json, sessions.json, and storage/games/<slug>/{index.html,cover.png,assets/sprite.png}), engineered in src/storage/atomicJson.mjs for zero partial-write corruption and deterministic concurrency without requiring external local postgres or redis-server daemons.

Concurrency & Durability Protocol

Let F be a canonical normalized file path (path.resolve(filePath).toLowerCase()). Concurrent read-modify-write operations T_1, T_2, \dots, T_k on F are serialized through an in-memory FIFO promise chain fileLocks.get(F):

$$

\text{Gate}_i = \text{Gate}_{i-1} \xrightarrow{\text{finally}} \text{execute}(T_i)

$$

Each mutating transaction updateJsonAtomic(filePath, defaultValue, mutatorFn) executes four atomic steps inside the critical section:

  1. Snapshot Read: Reads and parses F (or returns structuredClone(defaultValue) on ENOENT).
  2. Pure/Async State Transition: Applies mutatorFn(currentState) to compute { state: nextState, result }.
  3. Fsync Temporary Write: Writes serialized UTF-8 bytes to a unique sibling temporary path:

F.<pid>.<timestamp>.<uuid8>.tmp, invokes handle.writeFile(bytes) followed by handle.sync() (fsync / FlushFileBuffers), and closes the file descriptor.

  1. Bounded Exponential-Backoff Atomic Rename: Executes fs.rename(tmpPath, resolvedTarget). On Windows NTFS—where antivirus scanners or concurrent file-handle closures can transiently return EPERM, EACCES, or EBUSY—renameWithWindowsRetry() retries up to M = 6 attempts with delay Δ_a = 15 \cdot 2^a ms (15, 30, 60, 120, 240 ms; total worst-case wait 465 ms) and unlinks tmpPath in catch if all retries fail.
erDiagram
    CATALOG_JSON ||--o{ GAME_RECORD : contains
    GAME_RECORD ||--o{ LEADERBOARD_ENTRY : ranks
    GAME_RECORD ||--|| AUTHOR_EMBED : attributed_to
    USERS_JSON ||--o{ USER_RECORD : stores
    SESSIONS_JSON ||--o{ SESSION_RECORD : tracks
    USER_RECORD ||--o{ SESSION_RECORD : authenticates

    GAME_RECORD {
        string slug PK "1..80 lowercase alphanumeric-hyphen"
        string title "Globally deduplicated across sitemap"
        string summary "Max 220 chars, globally deduplicated"
        string prompt "3..2000 chars user prompt"
        string category "arcade-action | 3d-webgl | phaser-2d | puzzle-strategy"
        string engine "canvas2d | phaser | threejs"
        string model "gemini-4-neon | gemini-4-carbon | ..."
        string thinkingLevel "AUTO | MINIMAL | LOW | MEDIUM | HIGH | XHIGH"
        string imageModel "gemini-nano-banana-2.1 | gemini-3-pro-image"
        string coverUrl "/runtime/:slug/cover.png or category fallback"
        string spriteUrl "/runtime/:slug/assets/sprite.png or null"
        string runtimeUrl "/runtime/:slug/index.html"
        string permalink "/games/:slug"
        int plays "Monotonic counter incremented on runtime GET"
        boolean featured "Curated showcase flag"
        string remixOf "Optional parent game slug"
        string createdAt "ISO-8601 UTC"
        string updatedAt "ISO-8601 UTC"
    }

    LEADERBOARD_ENTRY {
        string playerName "Sanitized 1..32 chars"
        int score "0 .. 1,000,000,000 (top 25 retained)"
        string createdAt "ISO-8601 UTC tie-breaker (FIFO)"
    }

    USER_RECORD {
        string id PK "usr_<16-hex>"
        string email UK "Normalized RFC-compliant lowercase"
        string name "Sanitized 1..80 chars"
        string avatarUrl "Optional validated HTTPS/path URL"
        string provider "google | test"
        string createdAt "ISO-8601 UTC"
        string updatedAt "ISO-8601 UTC"
    }

    SESSION_RECORD {
        string id PK "ses_<48-hex>"
        string userId FK "References USER_RECORD.id"
        string createdAt "ISO-8601 UTC"
        string expiresAt "ISO-8601 UTC (default +7 days)"
    }

5. Service Worker Cache-Purge Protocol (ypg-shell-v2)

Stale Service Worker caches are a notorious failure mode in rapid AI web studios ("Ghost UI", where an older cached HTML shell continues rendering even after server updates or restarts). public/sw.js and src/app.mjs enforce the Zero Ghost-UI Invariant through five coupled rules:

  1. Unconditional Non-Current Bucket Purge: On activate, sw.js enumerates all CacheStorage keys and deletes every bucket where key !== 'ypg-shell-v2' (keys.filter((key) => key !== CACHE_NAME)), rather than using narrow prefix filters that leave legacy prototype caches orphaned, then immediately invokes self.clients.claim().
  2. Immediate Worker Promotion: install prefetches only four immutable vector/icon brand assets (/brand/favicon.svg, /brand/logo-full.svg, /brand/logo-mark.svg, /brand/icon-192.png) via Promise.allSettled and calls self.skipWaiting().
  3. Zero HTML Navigation Interception: isCacheableShellAsset(url, request) explicitly returns false whenever request.mode === 'navigate', Accept contains text/html, or pathname targets /api/*, /auth/*, or /runtime/*.
  4. Network-First Static Asset Strategy: Even for whitelisted static shell prefixes (/brand/, /assets/, /creatives/, /vendor/, /manifest.webmanifest), sw.js executes fetch(event.request) first, updating ypg-shell-v2 in the background on HTTP 200 basic responses and falling back to cache only when offline.
  5. Origin No-Store Headers: src/app.mjs serves /sw.js and every SSR HTML response with Cache-Control: no-store, no-cache, must-revalidate.

6. Universal Cross-Platform Mobile & Tablet Ecosystem Integration

As detailed in docs/mobile/MOBILE_AND_TABLET_ARCHITECTURE.md, the web platform shares canonical domain contracts, visual design tokens (docs/UI/*.png), and YourPlaygroundSDK bridge events with universal iOS (SwiftUI + WKWebView) and Android (Jetpack Compose + android.webkit.WebView) applications:

  • Adaptive Form-Factor Ergonomics: Compact single-column thumb-zone navigation and collapsible prompt sheet on phones (< 600dp), expanding into a split-pane Studio Prompt Inspector + 60 FPS Landscape Stage + Live Leaderboard drawer on iPadOS and Android tablets (>= 840dp).
  • Hybrid Identity & Sync: Native apps authenticate via Firebase Auth (Google Sign-In + Apple Sign-In + Anonymous Auth), synchronize cross-device creator libraries and leaderboards via Cloud Firestore, enforce request attestation via Firebase App Check, and monetize native sessions via Google AdMob Rewarded & Rewarded Interstitial units while executing the exact same sanitized HTML5/Phaser/Three.js game bundles inside isolated hardware-accelerated WebViews.

7. 10-Layer Butterfly-Effect Dependency Matrix

Every modification across the repository propagates through ten architectural layers. Engineers and autonomous agents must trace all ten layers prior to mutating any module:

LayerSystem SurfaceCanonical ModulesCross-Layer Invariants & Failure Modes Prevented
L1. Entrypoints & CallersHTTP daemon, CLI scripts, router factoriesserver.mjs, src/app.mjs, scripts/*.mjscreateApp(options) must support dependency injection (env, getEnv, adsDeps, gamesDeps, authDeps, discoveryDeps, pagesDeps) for isolated multi-tier testing without port collisions.
L2. HTTP & Bridge Wire ContractsREST JSON envelopes, OAuth redirects, postMessagesrc/routes/*.mjs, playerStage.mjs, gameSanitizer.mjsEvery API error returns { ok: false, code, error }; YourPlaygroundSDK emits YPG_READY, YPG_SCORE, YPG_GAME_OVER, YPG_RUNTIME_ERROR and consumes YPG_INPUT.
L3. Schemas & ValidationPrompt/model/slug/score validatorssrc/config/models.mjs, gameGeneratorService.mjs, gameRepository.mjsValidate inputs before burning single-use adGrantToken (verifyGrantToken → validateGenerateGameInput → consumeGrantToken).
L4. Persistence & LockingAtomic JSON & binary asset filessrc/storage/atomicJson.mjs, gameRepository.mjs, authRepository.mjsNever bypass withFileLock or writeBinaryAtomic; preserve Windows NTFS EPERM/EBUSY exponential retry loop.
L5. Async Workers & External CallsVertex AI calls, gcloud CLI token refresh, IndexNowvertexAiService.mjs, indexNowService.mjsDeduplicate concurrent gcloud token refreshes via state.inflightPromise; fire notifyGamePublished() asynchronously (4000 ms AbortSignal.timeout) so publishing latency is never blocked.
L6. SSR Views, CSS & Client UXSSR templates, CSS tokens, client ES modulessrc/views/*.mjs, public/assets/css/*.css, public/assets/js/*.mjsMaintain 100% English copy, 1:1 docs/UI fidelity, non-overlapping consent bar, and functional SSR rendering even when client JS is disabled.
L7. Config, Env & OS PathsEnvironment parsing, Windows/POSIX path guardssrc/config/env.mjs, runtimeRouter.mjs, gameRepository.mjsNormalize path.resolve + path.sep checks and reject Windows reserved filenames (CON, NUL, AUX, COM1..LPT9) across slugs and sprite filenames.
L8. Concurrency & OrderingAd session timers, leaderboard sorting, early SDK messagesadGateService.mjs, gameRepository.mjs, layout.mjsApply 250 ms clock-skew tolerance on ad completion; sort leaderboards descending by score then ascending by ISO timestamp; buffer early iframe postMessage events.
L9. Security, Privacy & IsolationSanitizer, CSP, HMAC cookies, Consent Mode v2gameSanitizer.mjs, sessionMiddleware.mjs, app.mjsMaintain crypto.timingSafeEqual on all HMAC verifications, strict separation of SSR_CSP_HEADER vs RUNTIME_CSP_HEADER, and default-denied Consent Mode v2 in <head>.
L10. Packaging, Cost & VerificationVendor bundles, Vertex spend, 5-rung test suitespublic/vendor/*, tests/unit/*, tests/integration/*, tests/e2e/*Keep Phaser/Three vendored locally for offline/sandbox determinism; enforce maxOutputTokens >= 32768 to prevent truncated HTML synthesis; verify all 5 rungs before release.