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:
- 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@graphJSON-LD graphs, XML sitemaps, and LLM corpora under strictSSR_CSP_HEADER,X-Frame-Options: SAMEORIGIN, andCache-Control: no-store, no-cache, must-revalidate. - Plane B — Stateful Control & Synthesis API Plane (
src/routes/api*.mjs,src/routes/authRouter.mjs,src/services/*.mjs): Enforces per-route JSON payload caps (64kbfor auth/ads,512kbfor games), timing-safe HMAC-SHA256 cookie authentication (ypg_vid,ypg_sid), single-useadGrantTokenburn semantics, and Vertex AI orchestration (gemini-4-neon+gemini-4-carbon). - 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">withoutallow-same-origin. The browser assigns an opaquenullorigin (window.origin === "null"), severing access to parent DOM,document.cookie,IndexedDB, andlocalStorage. - 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.staticmountsenv.publicDir(c:\Berk\YourPlayGroundGames\public) withindex: false. Server source (src/), secrets, scripts (scripts/), and raw ledgers (storage/) are unmounted, and Stage 11 explicitly matchesASSET_OR_INTERNAL_PREFIX_REGEX(/storage,/src,/scripts,/tests,/.agents,/.git) to return a bare404 Resource not found.without invoking SSR view rendering. - Per-Route Body Limit Preservation (Stage 7 before Stage 8): Mounting
apiAdsRouter(64kb),authRouter(64kb), andapiGamesRouter(512kb) before the fallback/api1mbparser ensures tight memory bounds on unauthenticated endpoints while guaranteeing JSON400 INVALID_JSONresponses on malformed bodies sent to unknown/api/*routes. - Discovery Shadow Prevention (Stage 9): Mounting
createDiscoveryRouterbeforeINDEXNOW_FILE_REGEX(/^\/([a-zA-Z0-9-]{8,128})\.txt$/) guarantees that/robots.txt,/llms.txt,/llms-full.txt, and/ads.txtcan never be shadowed even ifINDEXNOW_KEYwere 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
- Absence of
allow-same-origin: Becausesandbox="allow-scripts allow-pointer-lock"omitsallow-same-origin, Chromium, WebKit, and Gecko serialize the iframe's origin as"null". Any attempt inside the game to readwindow.parent.documentthrows aSecurityError, anddocument.cookie/window.localStoragethrowDOMException(gracefully shimmed in-memory byYPG_SDK_SCRIPT_TAGvia an ESMapso games usinglocalStoragefor high-score persistence never crash). - Cross-Origin Subresource Loading (
CORP+CORS): Because anull-origin iframe requests/vendor/phaser.min.js,/vendor/three.min.js, or./assets/sprite.pngas cross-origin subrequests relative to"null",applyRuntimeSecurityHeaders()setsCross-Origin-Resource-Policy: cross-originandAccess-Control-Allow-Origin: *exclusively on/runtime/*while enforcingRUNTIME_CSP_HEADER(default-src 'self' 'unsafe-inline' data: blob:; img-src 'self' data: blob:; media-src 'self' data: blob:). - Filesystem & Symlink Traversal Hardening:
runtimeRouter.mjsrejects%00,%5c,\, and%2e%2ein raw URLs, blocks Windows device names (CON,PRN,AUX,NUL,COM1–COM9,LPT1–LPT9), restricts subpaths strictly toindex.html,cover.(png|jpe?g), orassets/<safe-name>.(png|jpe?g|svg|gif|mp3|wav|ogg|json), and resolvesfs.realpath(gameDir)vsfs.realpath(targetPath)prior to reading bytes. - Early Message Replay Buffer: Fast Canvas 2D games loaded from warm disk cache can emit
YPG_READYbefore<script type="module" src="/assets/js/playerStage.mjs">finishes module evaluation. An inline<head>listener inlayout.mjscaptures up to 20 earlyYourPlaygroundSDKmessages inwindow.__ypgEarlyMessagesand replays them deterministically uponinitPlayerStage()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:
- Snapshot Read: Reads and parses
F(or returnsstructuredClone(defaultValue)onENOENT). - Pure/Async State Transition: Applies
mutatorFn(currentState)to compute{ state: nextState, result }. - 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.
- Bounded Exponential-Backoff Atomic Rename: Executes
fs.rename(tmpPath, resolvedTarget). On Windows NTFS—where antivirus scanners or concurrent file-handle closures can transiently returnEPERM,EACCES, orEBUSY—renameWithWindowsRetry()retries up toM = 6attempts with delayΔ_a = 15 \cdot 2^a ms(15, 30, 60, 120, 240 ms; total worst-case wait465 ms) and unlinkstmpPathincatchif 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:
- Unconditional Non-Current Bucket Purge: On
activate,sw.jsenumerates allCacheStoragekeys and deletes every bucket wherekey !== 'ypg-shell-v2'(keys.filter((key) => key !== CACHE_NAME)), rather than using narrow prefix filters that leave legacy prototype caches orphaned, then immediately invokesself.clients.claim(). - Immediate Worker Promotion:
installprefetches only four immutable vector/icon brand assets (/brand/favicon.svg,/brand/logo-full.svg,/brand/logo-mark.svg,/brand/icon-192.png) viaPromise.allSettledand callsself.skipWaiting(). - Zero HTML Navigation Interception:
isCacheableShellAsset(url, request)explicitly returnsfalsewheneverrequest.mode === 'navigate',Acceptcontainstext/html, orpathnametargets/api/*,/auth/*, or/runtime/*. - Network-First Static Asset Strategy: Even for whitelisted static shell prefixes (
/brand/,/assets/,/creatives/,/vendor/,/manifest.webmanifest),sw.jsexecutesfetch(event.request)first, updatingypg-shell-v2in the background on HTTP200basicresponses and falling back to cache only when offline. - Origin No-Store Headers:
src/app.mjsserves/sw.jsand every SSR HTML response withCache-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:
| Layer | System Surface | Canonical Modules | Cross-Layer Invariants & Failure Modes Prevented |
|---|---|---|---|
| L1. Entrypoints & Callers | HTTP daemon, CLI scripts, router factories | server.mjs, src/app.mjs, scripts/*.mjs | createApp(options) must support dependency injection (env, getEnv, adsDeps, gamesDeps, authDeps, discoveryDeps, pagesDeps) for isolated multi-tier testing without port collisions. |
| L2. HTTP & Bridge Wire Contracts | REST JSON envelopes, OAuth redirects, postMessage | src/routes/*.mjs, playerStage.mjs, gameSanitizer.mjs | Every 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 & Validation | Prompt/model/slug/score validators | src/config/models.mjs, gameGeneratorService.mjs, gameRepository.mjs | Validate inputs before burning single-use adGrantToken (verifyGrantToken → validateGenerateGameInput → consumeGrantToken). |
| L4. Persistence & Locking | Atomic JSON & binary asset files | src/storage/atomicJson.mjs, gameRepository.mjs, authRepository.mjs | Never bypass withFileLock or writeBinaryAtomic; preserve Windows NTFS EPERM/EBUSY exponential retry loop. |
| L5. Async Workers & External Calls | Vertex AI calls, gcloud CLI token refresh, IndexNow | vertexAiService.mjs, indexNowService.mjs | Deduplicate 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 UX | SSR templates, CSS tokens, client ES modules | src/views/*.mjs, public/assets/css/*.css, public/assets/js/*.mjs | Maintain 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 Paths | Environment parsing, Windows/POSIX path guards | src/config/env.mjs, runtimeRouter.mjs, gameRepository.mjs | Normalize path.resolve + path.sep checks and reject Windows reserved filenames (CON, NUL, AUX, COM1..LPT9) across slugs and sprite filenames. |
| L8. Concurrency & Ordering | Ad session timers, leaderboard sorting, early SDK messages | adGateService.mjs, gameRepository.mjs, layout.mjs | Apply 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 & Isolation | Sanitizer, CSP, HMAC cookies, Consent Mode v2 | gameSanitizer.mjs, sessionMiddleware.mjs, app.mjs | Maintain 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 & Verification | Vendor bundles, Vertex spend, 5-rung test suites | public/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. |