Skip to main content
Developer & Creator Documentation

Offensive Security, Auth Hardening & Leaderboard Anti-Cheat Specification

Beyond untrusted HTML5/JS execution inside /runtime/:slug/index.html (covered in SANDBOX_AND_ON_SANITIZER.md), the public REST APIs of YourPlayground.games face seven high-priority Red-

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

Offensive Security, Auth Hardening & Leaderboard Anti-Cheat Specification

Document ID: YPG-SEC-012 | Index: docs/README.md | Companion: SANDBOX_AND_ON_SANITIZER.md

Security Classification: Red-Team Defense-in-Depth, Brute-Force & Quota Protection, Prototype Pollution Neutralization, and Leaderboard Integrity

Primary Modules: src/middleware/rateLimitMiddleware.mjs, src/services/scoreAntiCheatService.mjs, src/routes/authRouter.mjs, src/routes/apiGamesRouter.mjs, src/routes/apiAdsRouter.mjs


1. Threat Model & Adversarial Attack Surface

Beyond untrusted HTML5/JS execution inside /runtime/:slug/index.html (covered in SANDBOX_AND_ON_SANITIZER.md), the public REST APIs of YourPlayground.games face seven high-priority Red-Team threat classes:

Threat IDAttack VectorConcrete Adversary TechniqueMitigating Layer & Enforcement
RT-016-Digit OTP & Password Brute-ForceAutomating thousands of guesses against POST /api/auth/verify-email (10^6 space), GET /auth/verify-email?token=..., or POST /api/auth/login (scryptSync CPU exhaustion), including rotating X-Forwarded-For IPs across a botnet.Dual-keyed (acct:<email> + uid:<userId> + ip:<clientIp>) sliding-window failure shield (12 failed attempts / 10 min per account -> HTTP 429 RATE_LIMITED + Retry-After) evaluated before scryptSync and OTP verification. Resets cleanly on valid login/OTP for the authenticated account without clearing IP spray counters.
RT-02Memory Exhaustion (OOM) via IP Spoofing & Cross-Bucket LRU EvictionFlooding rate-limited endpoints with millions of forged X-Forwarded-For headers to exhaust Node.js heap memory, or flooding unauthenticated /scores to evict authenticated /generate quota keys.Zero-dependency SlidingWindowStore with strict O(1) LRU eviction hard-capped at <= 10,000 keys per isolated store. Security domains use separate stores (bruteForceStore, antiSpamStore, aiQuotaStore, scoreRateLimitStore, adRateLimitStore) so public traffic can never evict auth lockouts or Vertex AI quotas.
RT-03Account Registration & Email-Bombing SpamScripting POST /api/auth/signup or POST /api/auth/resend-verification to flood SMTP/Gmail quotas or harass victim inboxes.Anti-spam sliding-window shield on POST /api/auth/signup (20/15m per IP, 5/15m per email) and POST /api/auth/resend-verification (5/15m per account, 15/15m per IP) returning HTTP 429 RATE_LIMITED + Retry-After.
RT-04Vertex AI Cloud Compute / Quota DrainVerified accounts automating rapid calls to POST /api/games/generate, POST /api/games/:slug/iterate, POST /api/games/:slug/autofix, or POST /api/games/:slug/sprites to rack up paid gemini-4-neon / gemini-4-carbon / gemini-nano-banana-2.1 token and image charges.Unified hourly Vertex AI cost-pool shield (30/hour per verified userId, 60/hour per IP) shared across generate, iterate, autofix, and sprites, paired with a tight autofix burst guard (6/min per user+IP). Pre-checked before burning single-use adGrantToken credits.
RT-05Leaderboard Score Spoofing, Bidi/Control Injection & Score SpamPosting NaN, Infinity (1e309), negative numbers, non-integer floats, absurdly spoofed scores (999999999), Trojan Source RTL-override/control characters (\u202E, \x00, \r\n, \u200B) in playerName, or rapid-fire automated score flooding.Dedicated scoreAntiCheatService.mjs rejecting non-finite/non-numeric scores (400 INVALID_SCORE), negative/non-integer/out-of-bounds scores > 1,000,000 (400 SCORE_OUT_OF_BOUNDS), control/RTL/zero-width playerName payloads (400 INVALID_PLAYER_NAME), HTML tags stripped + length bounded to 32 chars, and actor-keyed sliding window (> 20 posts/min -> 429 RATE_LIMITED).
RT-06JSON Prototype Pollution & Deep Nesting DoSSending raw JSON bodies containing "__proto__", "constructor", or "prototype" keys (top-level or nested) or deeply nested objects (depth > 20) to pollute Object.prototype or crash the call stack.Iterative (stack-safe, maxDepth = 20, maxNodes = 10,000) prototypePollutionGuardMiddleware() executed immediately after express.json() across authRouter, apiGamesRouter, and apiAdsRouter (plus ZIP manifest.json inspection), defensively stripping forbidden keys and rejecting with HTTP 400 PROTOTYPE_POLLUTION_BLOCKED.
RT-07Unauthorized Creation, Unverified Bypass & Source Archive ExfiltrationAnonymous or unverified accounts calling creation/ad endpoints, or scraping raw game source code via /api/games/:slug/export.zip, /api/games/:slug/export, or /games/:slug/download.Mandatory assertVerifiedCreator() (401 AUTH_REQUIRED for anonymous, 403 EMAIL_VERIFICATION_REQUIRED for unverified accounts) on all creation and ad-session endpoints, plus hard 403 ZIP_EXPORT_DISABLED on all legacy archive download routes.

2. Bounded LRU Sliding-Window Architecture (src/middleware/rateLimitMiddleware.mjs)

flowchart LR
    Req["Incoming HTTP Request"] --> JsonP["express.json (64KB / 512KB)"]
    JsonP --> ProtoG["prototypePollutionGuardMiddleware()<br/>(Blocks __proto__ / constructor / prototype -> 400)"]
    ProtoG --> AuthZ["Auth / Verified Creator Check<br/>(401 AUTH_REQUIRED / 403 EMAIL_VERIFICATION_REQUIRED)"]
    AuthZ --> RL["Isolated SlidingWindowStore<br/>(LRU Cap <= 10,000 keys · O(1) eviction)"]
    RL -- "Quota Exhausted" --> Deny429["HTTP 429 RATE_LIMITED<br/>Retry-After + X-RateLimit-* + Cache-Control: no-store"]
    RL -- "Allowed" --> Handler["Domain Service<br/>(scrypt / OTP / Vertex AI / Score Anti-Cheat)"]
    Handler -- "Valid Login / OTP" --> Reset["Reset Per-Account Failure Keys Only<br/>(Preserve IP Spray Counter)"]
    Handler -- "Failed Login / OTP" --> Record["Record Failure Timestamp Across Account + IP Buckets"]

2.1 Zero-OOM Complexity & Isolation Guarantees

  1. Exact O(1) LRU Eviction: SlidingWindowStore leverages V8's insertion-ordered Map. Touching an existing key deletes and re-inserts it at the MRU tail in O(1). Inserting a new key when size >= maxKeys (maxKeys hard-clamped to 1..10,000) immediately evicts map.keys().next().value (the LRU head) in O(1) time.
  2. Bounded Per-Key Timestamp Arrays: Each key stores only active timestamps inside [nowMs - windowMs, nowMs] capped at limit + 1 integers, preventing hot-key array bloat.
  3. Cross-Domain Store Isolation:
  • authRouter: bruteForceStore (login, OTP, link-verify, Google ID token) is physically separate from antiSpamStore (signup, resend-verification).
  • apiGamesRouter: aiQuotaStore (hourly Vertex AI generate/iterate/autofix/sprites + autofix burst) is physically separate from scoreRateLimitStore (public /scores).
  • apiAdsRouter: dedicated rateLimitStore for rewarded-ad session lifecycle endpoints.
  1. Reset-Bypass Immunity: A valid login to attacker@example.com resets only auth:login:acct:attacker@example.com—it NEVER resets auth:login:ip:<attackerIp>, preventing attackers from resetting their IP spray counter by interleaving valid logins to their own throwaway account.
  2. Unified Multi-Identifier OTP & Resend Binding (Zero 2x Bucket-Split Bypass): On POST /api/auth/verify-email and POST /api/auth/resend-verification, the server always binds deduplicated keys across body.email, auth.user.email (from the active session), AND auth.user.id (uid), so alternating cookie-only ({ code }) and cookieless ({ email, code }) requests strictly shares one 12-attempt OTP / 5-attempt resend budget.

3. Endpoint Protection & Environment Configuration Matrix

Every rate-limit window and threshold is dynamically configurable via environment variables without modifying code, ensuring safe production tuning and deterministic unit/integration/E2E testing:

Endpoint(s)Protection ModeDefault Threshold & WindowKeying DimensionsEnvironment Overrides
POST /api/auth/loginFailure-only (resets on valid login)12 failures / 10 min (account)<br/>36 failures / 10 min (IP)acct:<email> (or anon:<ip>) + ip:<ip>RATE_LIMIT_LOGIN_MAX, RATE_LIMIT_LOGIN_IP_MAX, RATE_LIMIT_AUTH_WINDOW_MS
POST /api/auth/verify-emailFailure-only (resets on valid OTP)12 failures / 10 min (account/uid)<br/>36 failures / 10 min (IP)acct:<email> + uid:<userId> + ip:<ip>RATE_LIMIT_VERIFY_EMAIL_MAX, RATE_LIMIT_VERIFY_EMAIL_IP_MAX, RATE_LIMIT_AUTH_WINDOW_MS
GET /auth/verify-emailFailure-only (resets on valid link)12 failures / 10 min (IP)ip:<ip>RATE_LIMIT_VERIFY_EMAIL_MAX, RATE_LIMIT_AUTH_WINDOW_MS
POST /api/auth/signupRequest-count anti-spam20 req / 15 min (IP)<br/>5 req / 15 min (email)ip:<ip> + acct:<email>RATE_LIMIT_SIGNUP_MAX, RATE_LIMIT_SIGNUP_ACCOUNT_MAX, RATE_LIMIT_SIGNUP_WINDOW_MS
POST /api/auth/resend-verificationRequest-count anti-spam5 req / 15 min (account/uid)<br/>15 req / 15 min (IP)acct:<email> + uid:<userId> + ip:<ip>RATE_LIMIT_RESEND_MAX, RATE_LIMIT_RESEND_IP_MAX, RATE_LIMIT_RESEND_WINDOW_MS
POST /api/auth/google/tokenFailure-only30 failures / 10 min (IP)ip:<ip>RATE_LIMIT_GOOGLE_TOKEN_MAX, RATE_LIMIT_AUTH_WINDOW_MS
POST /api/games/generate<br/>POST /api/games/:slug/iterate<br/>POST /api/games/:slug/spritesShared Vertex AI hourly cost guard (checked pre-burn, consumed post-validation)30 AI calls / 1 hour (user)<br/>60 AI calls / 1 hour (IP)uid:<userId> + ip:<ip>RATE_LIMIT_AI_HOURLY_MAX, RATE_LIMIT_AI_HOURLY_IP_MAX, RATE_LIMIT_AI_HOURLY_WINDOW_MS
POST /api/games/:slug/autofixShort burst + shared Vertex AI hourly cost guard6 req / 1 min (user & IP)<br/>+ shared 30/h user / 60/h IPuid:<userId> + ip:<ip>RATE_LIMIT_AUTOFIX_BURST_MAX, RATE_LIMIT_AUTOFIX_BURST_WINDOW_MS, RATE_LIMIT_AI_HOURLY_*
POST /api/ads/sessions<br/>POST /api/ads/sessions/:id/{complete,cancel}Memory/session flood shield60 starts / 10 min (user), 120 (IP)<br/>120 actions / 10 min (actor), 240 (IP)uid/vid/ipRATE_LIMIT_AD_SESSION_MAX, RATE_LIMIT_AD_SESSION_IP_MAX, RATE_LIMIT_AD_ACTION_MAX, RATE_LIMIT_AD_SESSION_WINDOW_MS
POST /api/games/:slug/scoresRapid-fire score spam shield20 posts / 1 min (actor)<br/>60 posts / 1 min (IP)uid:<userId> or vid:<visitorId> or ip-anon:<ip> + ip:<ip>RATE_LIMIT_SCORE_MAX, RATE_LIMIT_SCORE_IP_MAX, RATE_LIMIT_SCORE_WINDOW_MS
Global LRU CapMemory ceiling per store10,000 keys max (hard upper bound)All storesRATE_LIMIT_MAX_KEYS (1..10000)

All 429 RATE_LIMITED responses return:

  • HTTP 429 Too Many Requests
  • Retry-After: <seconds>
  • X-RateLimit-Limit, X-RateLimit-Remaining: 0, X-RateLimit-Reset
  • Cache-Control: no-store
  • JSON payload: { "ok": false, "code": "RATE_LIMITED", "error": "...", "retryAfterSeconds": <n> }

4. Leaderboard Score Anti-Cheat Specification (src/services/scoreAntiCheatService.mjs)

Every request to POST /api/games/:slug/scores passes through three deterministic gates before touching storage/catalog.json:

  1. Rapid-Fire Spam Gate (429 RATE_LIMITED): Enforces <= 20 score posts per 60 seconds per actor (userId > established visitorId > ip-anon), plus a per-IP ceiling (60/min) to stop cookie-rotation bots.
  2. Numeric Bounds & Integrity Gate (400 INVALID_SCORE / 400 SCORE_OUT_OF_BOUNDS):
  • Rejects non-number types (string, boolean, null, undefined, object, array), NaN, Infinity, and -Infinity (including JSON 1e309) with 400 INVALID_SCORE.
  • Rejects negative numbers (< 0), non-integer floats (e.g. 12.5), and absurdly spoofed values exceeding MAX_LEADERBOARD_SCORE (1,000,000, configurable via LEADERBOARD_MAX_SCORE <= 1,000,000) with 400 SCORE_OUT_OF_BOUNDS.
  • Normalizes -0 to 0.
  1. Player Name Control & Bidi/RTL Spoof Rejection (400 INVALID_PLAYER_NAME):
  • Hard-rejects any playerName containing:
  • ASCII C0 & DEL control characters (\u0000-\u001F, \u007F) — null bytes, ESC/ANSI sequences, CR/LF log injection
  • C1 control characters (\u0080-\u009F)
  • Unicode Bidi / RTL override & isolate characters (\u061C, \u200E, \u200F, \u202A-\u202E, \u2066-\u2069) — Trojan Source visual spoofing
  • Zero-width / invisible spoofing characters (\u200B-\u200D, \u2060, \uFEFF)
  • Rejects non-string playerName types (400 INVALID_PLAYER_NAME).
  • Strips HTML tags (<[^>]*>) and angle brackets (<>), collapses whitespace, and bounds clean names to 32 characters (Anonymous Player fallback on blank names).

5. Adversarial Red-Team Verification Coverage

Continuous automated proof lives inside tests/integration/full-platform.test.mjs and executes under node .agents/scripts/agent-ctl.cjs verify --full-gate:

  1. Distributed-IP 6-Digit OTP Brute-Force Lockout (429 RATE_LIMITED + Retry-After) & Clean Reset: Proves 12 failed OTP attempts against an account across rotating X-Forwarded-For IPs trigger 429 RATE_LIMITED + numeric Retry-After on attempt 13 (even with the valid OTP!), while a separate account with < 12 failed attempts resets cleanly back to 0 upon valid verification.
  2. Password Brute-Force Lockout & Clean Login Reset: Proves 12 failed POST /api/auth/login attempts trigger 429 RATE_LIMITED + Retry-After, and valid login resets per-account failures cleanly.
  3. Signup & Resend-Verification Anti-Spam Shield: Proves automated POST /api/auth/resend-verification email-bombing triggers 429 RATE_LIMITED after 5 attempts.
  4. Vertex AI Hourly Quota Shield: Proves POST /api/games/generate enforces the configurable hourly per-user Vertex AI quota (429 RATE_LIMITED + Retry-After) without burning the user's adGrantToken.
  5. Bounded LRU Eviction Proof (<= 10,000 keys): Floods SlidingWindowStore with 11,000 distinct spoofed IPs and verifies store.size === 10_000, store.evictionCount === 1_000, and strict LRU ordering.
  6. Leaderboard Anti-Cheat Suite: Proves 999999999, 1000001, -10, 42.5 return 400 SCORE_OUT_OF_BOUNDS; NaN/Infinity (1e309)/string return 400 INVALID_SCORE; RTL-override \u202E, NUL \x00, CRLF \r\n, and ZWSP \u200B in playerName return 400 INVALID_PLAYER_NAME; and 21 rapid score posts/min trigger 429 RATE_LIMITED + Retry-After.
  7. Prototype-Pollution JSON Body Defense: Sends raw {"__proto__":{"polluted":true},"constructor":{"prototype":{"pwned":true}}} across /api/games/:slug/scores, /api/auth/login, and /api/ads/sessions, asserting 400 PROTOTYPE_POLLUTION_BLOCKED and ({}).polluted === undefined && ({}).pwned === undefined.
  8. Zero-ZIP Export & Unverified Creator Enforcement: Verifies GET /api/games/:slug/export.zip returns 403 ZIP_EXPORT_DISABLED and unverified accounts attempting POST /api/games/generate receive 403 EMAIL_VERIFICATION_REQUIRED.