HTTP REST API & YourPlaygroundSDK Runtime Bridge Reference
Document ID: YPG-API-009 | Index: docs/README.md
Base Local Origin: http://localhost:9033 | Canonical Public Origin: https://www.yourplayground.games
Primary Modules: src/routes/apiConfigRouter.mjs, src/routes/apiAdsRouter.mjs, src/routes/apiGamesRouter.mjs, src/routes/authRouter.mjs, src/routes/runtimeRouter.mjs, src/services/gameSanitizer.mjs
1. Global HTTP Wire Conventions, Envelopes & Guard Limits
All JSON endpoints under /api/* obey deterministic wire invariants enforced by src/app.mjs and individual domain routers:
- Response Headers: Every
/api/*response emitsContent-Type: application/json; charset=utf-8,Cache-Control: no-store, andX-Content-Type-Options: nosniff. - Standard Envelope:
- Success (
200 OK/201 Created):{ "ok": true, ...domainFields } - Error (
400/402/403/404/413/500/502):
{
"ok": false,
"code": "MACHINE_READABLE_CODE",
"error": "Human-readable English diagnostic message."
}
Stack traces and internal file paths are never serialized in error responses.
- Per-Router Request Body Caps:
/api/ads/*&/api/auth/*:64kb(express.json({ limit: '64kb' })→413 PAYLOAD_TOO_LARGEif exceeded)/api/games/*:512kb(express.json({ limit: '512kb' })→413 PAYLOAD_TOO_LARGEif exceeded)- Unmatched
/api/*fallback:1mb(400 INVALID_JSONon malformed JSON;404 NOT_FOUNDon unknown endpoint)
- Cookie Transport: Signed
HttpOnly; SameSite=Laxcookies (ypg_vid30d visitor identity;ypg_sid7d optional authenticated session) are attached automatically oncredentials: 'same-origin'browser requests. Stateless CLI/script callers without cookies are also supported seamlessly byresolveRequestAuthFallback().
2. Complete Endpoint Summary Matrix
| Method & Path | Auth Required | Body Cap | Success Status | Primary Responsibility |
|---|---|---|---|---|
GET /api/health | None | — | 200 OK | Liveness probe returning bound port and canonical siteUrl |
GET /api/config | Optional (ypg_sid) | — | 200 OK | Full public Studio bootstrap: 8 Vertex models, 6 Thinking Levels, 2 image models, 3 engines, AdSense/VAST, Consent Mode v2, IndexNow, Auth state, and 4 categories |
POST /api/ads/sessions | None (ypg_vid) | 64kb | 201 Created | Starts a server-timed watch-ad session (ads_<32-hex>) |
POST /api/ads/sessions/:sessionId/complete | Same Actor | 64kb | 200 OK | Verifies elapsed watch duration (≥ T_req - 250 ms) and issues single-use HMAC adGrantToken |
POST /api/ads/sessions/:sessionId/cancel | Same Actor | 64kb | 200 OK | Cancels active ad session and revokes any associated grant |
GET /api/games | None | — | 200 OK | Lists published games with optional ?category=, ?engine=, ?q=, ?featured=true filters |
POST /api/games/generate | Valid adGrantToken | 512kb | 201 Created | Validates input, burns single-use adGrantToken, synthesizes/repairs game via Vertex AI, saves bundle, and triggers async IndexNow |
GET /api/games/:slug | None | — | 200 OK | Fetches full game metadata, provenance, and top-25 leaderboard |
POST /api/games/:slug/sprites | None | 512kb | 201 Created | Synthesizes custom 1:1 sprite via Nano Banana 2.1 or Gemini 3 Pro Image into /runtime/:slug/assets/* |
POST /api/games/:slug/scores | Optional (ypg_sid) | 512kb | 201 Created | Records validated score (0 \dots 10^9) onto the game's top-25 leaderboard |
GET /api/games/:slug/export.zip (Portable Export Contract) | None | — | 200 OK | Streams self-contained offline-playable ZIP bundle (index.html, cover.png, assets/*, local vendor/*) |
GET /api/auth/session | Optional (ypg_sid) | — | 200 OK | Returns current authentication state, mode (google_oauth \ |
POST /api/auth/test-login | None (allowTestAuth) | 64kb | 200 OK | Creates/updates local test Gmail creator session (403 TEST_AUTH_DISABLED if live OAuth active without ALLOW_TEST_AUTH=true) |
POST / GET /api/auth/logout | Optional | 64kb | 200 OK | Deletes server session and clears ypg_sid cookie (JSON response) |
GET /auth/google | None | — | 302 Found | Mints ypg_oauth_state CSRF cookie and redirects to Google OAuth 2.0 (or /?authModal=test in test mode) |
GET /auth/google/callback | ypg_oauth_state | — | 302 Found | Verifies CSRF state, exchanges OAuth code, upserts user, sets ypg_sid, and redirects to sanitized returnTo |
GET /auth/logout | Optional | — | 302 Found | Clears session and redirects to sanitized returnTo (default /) |
GET /runtime/:slug/*assetPath | None | — | 200 OK | Serves isolated game HTML, cover, or sprite asset under RUNTIME_CSP_HEADER |
3. Detailed Endpoint Specifications & Schemas
3.1 System & Configuration (apiConfigRouter.mjs)
GET /api/health
{
"ok": true,
"status": "ok",
"port": 9033,
"siteUrl": "https://www.yourplayground.games"
}
GET /api/config
Returns the canonical platform capability registry consumed by Studio UI and mobile/tablet clients:
{
"ok": true,
"siteUrl": "https://www.yourplayground.games",
"vertexDefaultModel": "gemini-4-neon",
"vertexRepairModel": "gemini-4-carbon",
"vertex": {
"project": "ids-hybrid-model",
"location": "global",
"models": [ /* 8 TEXT_MODELS objects */ ],
"defaultModel": "gemini-4-neon",
"repairModel": "gemini-4-carbon",
"thinkingLevels": ["AUTO", "MINIMAL", "LOW", "MEDIUM", "HIGH", "XHIGH"],
"thinkingLevelOptions": [ /* 6 descriptive options */ ],
"imageModels": [ /* gemini-nano-banana-2.1, gemini-3-pro-image */ ],
"defaultImageModel": "gemini-nano-banana-2.1",
"engines": [ /* canvas2d, phaser, threejs */ ],
"defaultEngine": "canvas2d"
},
"adsense": {
"mode": "test",
"publisherId": null,
"rewardSlotId": null,
"slotId": null,
"displaySlotId": null,
"watchDurationSeconds": 5,
"vastRewardTagUrl": null,
"vastConfigured": false
},
"analytics": {
"consentMode": "v2",
"consentStorageKey": "ypg_consent_v2",
"gaMeasurementId": null,
"gtmContainerId": null,
"clarityProjectId": null
},
"indexing": { "indexNowEnabled": false },
"auth": { "mode": "test", "allowTestAuth": true, "authenticated": false, "user": null },
"categories": [ /* 4 CATEGORIES objects */ ]
}
3.2 Sponsored Ad-Gate Endpoints (apiAdsRouter.mjs)
POST /api/ads/sessions
- Request Body:
{ "intent": "generate_game" }(optional JSON object) - Response (
201 Created):
{
"ok": true,
"sessionId": "ads_4f2a8b1c9d0e3f4a5b6c7d8e9f0a1b2c",
"mode": "test",
"requiredSeconds": 5,
"expiresAt": "2026-11-21T18:20:00.000Z"
}
POST /api/ads/sessions/:sessionId/complete
- Response (
200 OK):
{
"ok": true,
"adGrantToken": "eyJ2IjoxLCJqdGkiOiJhZGdfLi4uIn0.HMAC_BASE64URL_SIG",
"expiresInSeconds": 300
}
- Error Statuses:
400 AD_INCOMPLETE: Elapsed time< requiredMs - 250 ms(non-destructive; retry after remaining countdown).400 AD_CANCELLED: Session was previously cancelled.400 AD_EXPIRED: Session TTL elapsed or session was already completed.404 AD_SESSION_NOT_FOUND: UnknownsessionIdor actor mismatch.
POST /api/ads/sessions/:sessionId/cancel
- Response (
200 OK):{ "ok": true, "sessionId": "ads_...", "status": "cancelled" }
3.3 Game Synthesis, Catalog, Sprites, Leaderboards & ZIP Export (apiGamesRouter.mjs)
GET /api/games
- Query Parameters:
category:arcade-action|3d-webgl|phaser-2d|puzzle-strategy|allengine:canvas2d|phaser|threejs|all(aliases supported viaresolveEngine)q: Multi-token case-insensitive search acrosstitle,summary,prompt,category,engine,model,modelLabel, andauthor.namefeatured/featuredOnly:true|1- Response (
200 OK):{ "ok": true, "games": [ ... ], "total": 4 }
POST /api/games/generate
- Token Delivery: Either
body.adGrantTokenor HTTP headerX-Ad-Grant-Token. - Request Schema:
{
"adGrantToken": "eyJ2Ijox...",
"prompt": "Create a 3D Three.js neon canyon glider racing through boost rings while dodging monoliths.",
"engine": "threejs",
"category": "3d-webgl",
"model": "gemini-4-neon",
"thinkingLevel": "XHIGH",
"imageModel": "gemini-nano-banana-2.1",
"generateCover": true,
"generateSprite": false,
"remixSlug": "prism-horizon-drifter"
}
- **Validation Rules (Evaluated Before Burning
adGrantToken):** prompt: Required string, trimmed length3..2000characters (400 INVALID_INPUTotherwise).model: Optional; must match one of the 8TEXT_MODELSIDs/labels/aliases (default: gemini-4-neon).thinkingLevel: Optional;AUTO|MINIMAL|LOW|MEDIUM|HIGH|XHIGH(default: MEDIUM).engine: Optional;canvas2d|phaser|threejs(default: canvas2d).imageModel: Optional;gemini-nano-banana-2.1|gemini-3-pro-image(default: gemini-nano-banana-2.1).category: Optional; valid category slug or'auto'.remixSlug(aliasremixOf): Optional; must match/^[a-z0-9]+(?:-[a-z0-9]+)*$/and exist ingameRepository(400 INVALID_INPUTif missing).- Response (
201 Created):{ "ok": true, "game": { ...savedGameRecord } } - Error Statuses:
402 AD_REQUIRED(missing/expired/replayed/wrong-actor token),400 INVALID_INPUT,502 GENERATION_FAILED/EMPTY_MODEL_OUTPUT.
POST /api/games/:slug/sprites
- Request Schema:
{
"prompt": "Glowing cybernetic phoenix starfighter top-down arcade sprite",
"imageModel": "gemini-nano-banana-2.1",
"filename": "sprite.png"
}
(prompt trimmed length 3..1000 chars; filename sanitized to [a-zA-Z0-9_-]{1,64}\.(png|jpe?g)).
- Response (
201 Created):
{
"ok": true,
"spriteUrl": "/runtime/neon-orbit-defender/assets/sprite.png",
"imageModel": "gemini-nano-banana-2.1"
}
POST /api/games/:slug/scores
- Request Schema:
{ "playerName": "NovaPilot", "score": 14850 } score: Finite number in[0, 10^9], rounded to nearest integer (400 INVALID_SCOREotherwise).playerName: Optional; defaults to authenticateduser.nameor'Anonymous Player', stripped of control/<>characters and clamped to32chars.- Response (
201 Created):{ "ok": true, "leaderboard": [ /* Top 25 sorted desc by score, asc by createdAt */ ] }
POST /api/games/import-zip
- Purpose: Imports a portable HTML5 Canvas, Phaser.js 3, or Three.js WebGL
.zipbundle (including Google Playground exports and YourPlayground.ziparchives) directly into the isolated OOPIF sandbox. - Request Formats:
- Raw binary upload (
Content-Type: application/ziporapplication/octet-stream, up to4 MB) with optionalX-Game-Titleheader or?title=...&category=...query parameters. - JSON envelope (
Content-Type: application/json):{ "zipBase64": "<base64>", "title": "Optional Title", "category": "3d-webgl", "engine": "threejs" }. - Archive & Sandbox Security Gates:
parseZipArchivesupportsSTORE(0) andDEFLATE(8, boundedzlib.inflateRawSync), enforces4 MBarchive cap,6 MBtotal uncompressed cap,32entry cap, CRC-32 verification, and rejects encrypted entries, symlinks, absolute paths, and..Zip-Slip traversal (400 INVALID_ZIP/413 PAYLOAD_TOO_LARGE).- Rewrites external Three.js / Phaser CDN
<script>tags to local air-gapped/vendor/three.min.jsand/vendor/phaser.min.js, then validatesindex.htmlthrough linear-timeO(N)sanitizeGameHtml(400 INVALID_GAME_HTMLon violation). - Response (
201 Created):{ "ok": true, "game": { /* Catalog Game Record */ } }
POST /api/games/:slug/iterate
- Purpose: Live Chat-to-Edit in-place refinement of an existing game (
iterateAndSaveGame) gated by a single-useadGrantToken. - Request Schema:
{ "adGrantToken": "<hmac-grant>", "prompt": "Add a boss wave at 500 points and rain reflections", "model": "gemini-4-neon", "thinkingLevel": "HIGH" } - Validation Order: Non-burning
verifyGrantToken(402 AD_REQUIRED)→slug existence (404 GAME_NOT_FOUND) &3..2000char instruction check (400 INVALID_INPUT)→atomicconsumeGrantToken→Vertex AI synthesis +O(N)sanitizeGameHtml. - Response (
200 OK):{ "ok": true, "game": { /* Updated Catalog Game Record */ } }
POST /api/games/:slug/autofix
- Purpose: 1-Click Runtime AI Auto-Fix (
autofixAndSaveGame) powered bygemini-4-carbon(VERTEX_REPAIR_MODEL) when the sandboxed stage emitsYPG_RUNTIME_ERROR. - Request Schema:
{ "errorMessage": "Uncaught TypeError: Cannot read properties of undefined", "line": 142 }(3..1500chars; rate-limited to6repairs/min per client IP). - Response (
200 OK):{ "ok": true, "game": { /* Repaired Catalog Game Record */ } }
Portable Self-Contained ZIP Export Specification (GET /api/games/:slug/export.zip)
To empower creators to download and host their generated games anywhere (itch.io, GitHub Pages, Netlify, desktop Electron wrappers—matching the ZIP Export · Download & publish anywhere pillar in docs/UI/your_playgrpound_games_design_1.png), a portable game export archive packages:
<slug>-yourplayground-export.zip
├── index.html # Sanitized game HTML with /vendor/* rewritten to ./vendor/*
├── cover.png # 16:9 key-art thumbnail (when present)
├── assets/
│ └── sprite.png # Custom synthesized sprite (when present)
├── vendor/
│ └── phaser.min.js # Included automatically when engine === 'phaser' (or three.min.js for 'threejs')
└── README.txt # Attribution, controls, and zero-dependency local launch guide
- Headers:
Content-Type: application/zip,Content-Disposition: attachment; filename="<slug>.zip",Cache-Control: no-store.
4. window.YourPlaygroundSDK & postMessage Bridge Reference
Injected automatically into <head> as <script id="ypg-sdk"> by src/services/gameSanitizer.mjs (lines 10–1364) with global alias window.PlaygroundSDK = window.YourPlaygroundSDK.
4.1 In-Game JavaScript SDK Surface
| Property / Method | Signature / Type | Runtime Behavior |
|---|---|---|
YourPlaygroundSDK.version | '1.0.0' | Semantic version of the injected sandbox runtime bridge |
YourPlaygroundSDK.keys | Record<string, boolean> | Live map updated synchronously by both real keydown/keyup events and synthetic YPG_INPUT touch-deck bridge events (ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Space, Enter, KeyA, KeyD, KeyW, KeyS, KeyR) |
YourPlaygroundSDK.state | { ready, score, highScore, gameOver, inputsReceived } | Live mutable telemetry state inside the sandbox |
YourPlaygroundSDK.ready(extra?) | (extra?: object) => void | Marks state.ready = true and posts YPG_READY (Game Ready lifecycle signal) to window.parent (also auto-triggered 350 ms after window.load if the game omits an explicit call) |
YourPlaygroundSDK.reportScore(score, extra?) | (score: number, extra?: object) => void | Clamps score to non-negative integer, updates state.score / state.highScore, and posts YPG_SCORE (Score Update lifecycle signal) |
YourPlaygroundSDK.gameOver(finalScore?, extra?) | (finalScore?: number, extra?: object) => void | Marks state.gameOver = true and posts YPG_GAME_OVER (Game Over lifecycle signal; alias submitScore()) |
YourPlaygroundSDK.reportError(message, extra?) | (message: string, extra?: object) => void | Automatically bound to window.error & unhandledrejection; posts YPG_RUNTIME_ERROR |
4.2 Bidirectional window.postMessage Wire Protocol
Because the sandboxed iframe runs in an opaque null origin (event.origin === "null"), playerStage.mjs authenticates incoming messages by verifying event.source === iframeEl.contentWindow and event.data.source === 'YourPlaygroundSDK':
| Direction | Lifecycle Concept | Wire type Value | JSON Message Envelope |
|---|---|---|---|
Iframe → Parent | GAME_READY | YPG_READY | { "source": "YourPlaygroundSDK", "type": "YPG_READY", "payload": { "score": 0, "engine": "phaser", "timestamp": 1795284001000 } } |
Iframe → Parent | SCORE_UPDATE | YPG_SCORE | { "source": "YourPlaygroundSDK", "type": "YPG_SCORE", "payload": { "score": 450, "highScore": 450, "timestamp": 1795284015000 } } |
Iframe → Parent | GAME_OVER | YPG_GAME_OVER | { "source": "YourPlaygroundSDK", "type": "YPG_GAME_OVER", "payload": { "score": 1280, "highScore": 1280, "timestamp": 1795284042000 } } |
Iframe → Parent | RUNTIME_ERROR | YPG_RUNTIME_ERROR | { "source": "YourPlaygroundSDK", "type": "YPG_RUNTIME_ERROR", "payload": { "message": "...", "lineno": 42, "timestamp": 1795284043000 } } |
Parent → Iframe | VIRTUAL_INPUT | YPG_INPUT | `{ "type": "YPG_INPUT", "key": "ArrowLeft" \ |