Skip to main content
Developer & Creator Documentation

HTTP REST API & YourPlaygroundSDK Runtime Bridge Reference

All JSON endpoints under /api/ obey deterministic wire invariants enforced by src/app.mjs and individual domain routers:

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

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:

  1. Response Headers: Every /api/* response emits Content-Type: application/json; charset=utf-8, Cache-Control: no-store, and X-Content-Type-Options: nosniff.
  2. 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.

  1. Per-Router Request Body Caps:
  • /api/ads/* & /api/auth/*: 64kb (express.json({ limit: '64kb' }) → 413 PAYLOAD_TOO_LARGE if exceeded)
  • /api/games/*: 512kb (express.json({ limit: '512kb' }) → 413 PAYLOAD_TOO_LARGE if exceeded)
  • Unmatched /api/* fallback: 1mb (400 INVALID_JSON on malformed JSON; 404 NOT_FOUND on unknown endpoint)
  1. Cookie Transport: Signed HttpOnly; SameSite=Lax cookies (ypg_vid 30d visitor identity; ypg_sid 7d optional authenticated session) are attached automatically on credentials: 'same-origin' browser requests. Stateless CLI/script callers without cookies are also supported seamlessly by resolveRequestAuthFallback().

2. Complete Endpoint Summary Matrix

Method & PathAuth RequiredBody CapSuccess StatusPrimary Responsibility
GET /api/healthNone—200 OKLiveness probe returning bound port and canonical siteUrl
GET /api/configOptional (ypg_sid)—200 OKFull 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/sessionsNone (ypg_vid)64kb201 CreatedStarts a server-timed watch-ad session (ads_<32-hex>)
POST /api/ads/sessions/:sessionId/completeSame Actor64kb200 OKVerifies elapsed watch duration (≥ T_req - 250 ms) and issues single-use HMAC adGrantToken
POST /api/ads/sessions/:sessionId/cancelSame Actor64kb200 OKCancels active ad session and revokes any associated grant
GET /api/gamesNone—200 OKLists published games with optional ?category=, ?engine=, ?q=, ?featured=true filters
POST /api/games/generateValid adGrantToken512kb201 CreatedValidates input, burns single-use adGrantToken, synthesizes/repairs game via Vertex AI, saves bundle, and triggers async IndexNow
GET /api/games/:slugNone—200 OKFetches full game metadata, provenance, and top-25 leaderboard
POST /api/games/:slug/spritesNone512kb201 CreatedSynthesizes custom 1:1 sprite via Nano Banana 2.1 or Gemini 3 Pro Image into /runtime/:slug/assets/*
POST /api/games/:slug/scoresOptional (ypg_sid)512kb201 CreatedRecords validated score (0 \dots 10^9) onto the game's top-25 leaderboard
GET /api/games/:slug/export.zip (Portable Export Contract)None—200 OKStreams self-contained offline-playable ZIP bundle (index.html, cover.png, assets/*, local vendor/*)
GET /api/auth/sessionOptional (ypg_sid)—200 OKReturns current authentication state, mode (google_oauth \
POST /api/auth/test-loginNone (allowTestAuth)64kb200 OKCreates/updates local test Gmail creator session (403 TEST_AUTH_DISABLED if live OAuth active without ALLOW_TEST_AUTH=true)
POST / GET /api/auth/logoutOptional64kb200 OKDeletes server session and clears ypg_sid cookie (JSON response)
GET /auth/googleNone—302 FoundMints ypg_oauth_state CSRF cookie and redirects to Google OAuth 2.0 (or /?authModal=test in test mode)
GET /auth/google/callbackypg_oauth_state—302 FoundVerifies CSRF state, exchanges OAuth code, upserts user, sets ypg_sid, and redirects to sanitized returnTo
GET /auth/logoutOptional—302 FoundClears session and redirects to sanitized returnTo (default /)
GET /runtime/:slug/*assetPathNone—200 OKServes 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: Unknown sessionId or 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 | all
  • engine: canvas2d | phaser | threejs | all (aliases supported via resolveEngine)
  • q: Multi-token case-insensitive search across title, summary, prompt, category, engine, model, modelLabel, and author.name
  • featured / featuredOnly: true | 1
  • Response (200 OK): { "ok": true, "games": [ ... ], "total": 4 }

POST /api/games/generate

  • Token Delivery: Either body.adGrantToken or HTTP header X-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 length 3..2000 characters (400 INVALID_INPUT otherwise).
  • model: Optional; must match one of the 8 TEXT_MODELS IDs/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 (alias remixOf): Optional; must match /^[a-z0-9]+(?:-[a-z0-9]+)*$/ and exist in gameRepository (400 INVALID_INPUT if 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_SCORE otherwise).
  • playerName: Optional; defaults to authenticated user.name or 'Anonymous Player', stripped of control/<> characters and clamped to 32 chars.
  • 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 .zip bundle (including Google Playground exports and YourPlayground .zip archives) directly into the isolated OOPIF sandbox.
  • Request Formats:
  • Raw binary upload (Content-Type: application/zip or application/octet-stream, up to 4 MB) with optional X-Game-Title header 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:
  • parseZipArchive supports STORE (0) and DEFLATE (8, bounded zlib.inflateRawSync), enforces 4 MB archive cap, 6 MB total uncompressed cap, 32 entry 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.js and /vendor/phaser.min.js, then validates index.html through linear-time O(N) sanitizeGameHtml (400 INVALID_GAME_HTML on 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-use adGrantToken.
  • 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..2000 char instruction check (400 INVALID_INPUT) → atomic consumeGrantToken → 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 by gemini-4-carbon (VERTEX_REPAIR_MODEL) when the sandboxed stage emits YPG_RUNTIME_ERROR.
  • Request Schema: { "errorMessage": "Uncaught TypeError: Cannot read properties of undefined", "line": 142 } (3..1500 chars; rate-limited to 6 repairs/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 / MethodSignature / TypeRuntime Behavior
YourPlaygroundSDK.version'1.0.0'Semantic version of the injected sandbox runtime bridge
YourPlaygroundSDK.keysRecord<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) => voidMarks 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) => voidClamps 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) => voidMarks state.gameOver = true and posts YPG_GAME_OVER (Game Over lifecycle signal; alias submitScore())
YourPlaygroundSDK.reportError(message, extra?)(message: string, extra?: object) => voidAutomatically 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':

DirectionLifecycle ConceptWire type ValueJSON Message Envelope
Iframe → ParentGAME_READYYPG_READY{ "source": "YourPlaygroundSDK", "type": "YPG_READY", "payload": { "score": 0, "engine": "phaser", "timestamp": 1795284001000 } }
Iframe → ParentSCORE_UPDATEYPG_SCORE{ "source": "YourPlaygroundSDK", "type": "YPG_SCORE", "payload": { "score": 450, "highScore": 450, "timestamp": 1795284015000 } }
Iframe → ParentGAME_OVERYPG_GAME_OVER{ "source": "YourPlaygroundSDK", "type": "YPG_GAME_OVER", "payload": { "score": 1280, "highScore": 1280, "timestamp": 1795284042000 } }
Iframe → ParentRUNTIME_ERRORYPG_RUNTIME_ERROR{ "source": "YourPlaygroundSDK", "type": "YPG_RUNTIME_ERROR", "payload": { "message": "...", "lineno": 42, "timestamp": 1795284043000 } }
Parent → IframeVIRTUAL_INPUTYPG_INPUT`{ "type": "YPG_INPUT", "key": "ArrowLeft" \