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 ID | Attack Vector | Concrete Adversary Technique | Mitigating Layer & Enforcement |
|---|---|---|---|
| RT-01 | 6-Digit OTP & Password Brute-Force | Automating 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-02 | Memory Exhaustion (OOM) via IP Spoofing & Cross-Bucket LRU Eviction | Flooding 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-03 | Account Registration & Email-Bombing Spam | Scripting 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-04 | Vertex AI Cloud Compute / Quota Drain | Verified 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-05 | Leaderboard Score Spoofing, Bidi/Control Injection & Score Spam | Posting 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-06 | JSON Prototype Pollution & Deep Nesting DoS | Sending 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-07 | Unauthorized Creation, Unverified Bypass & Source Archive Exfiltration | Anonymous 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
- Exact
O(1)LRU Eviction:SlidingWindowStoreleverages V8's insertion-orderedMap. Touching an existing key deletes and re-inserts it at the MRU tail inO(1). Inserting a new key whensize >= maxKeys(maxKeyshard-clamped to1..10,000) immediately evictsmap.keys().next().value(the LRU head) inO(1)time. - Bounded Per-Key Timestamp Arrays: Each key stores only active timestamps inside
[nowMs - windowMs, nowMs]capped atlimit + 1integers, preventing hot-key array bloat. - Cross-Domain Store Isolation:
authRouter:bruteForceStore(login, OTP, link-verify, Google ID token) is physically separate fromantiSpamStore(signup, resend-verification).apiGamesRouter:aiQuotaStore(hourly Vertex AI generate/iterate/autofix/sprites + autofix burst) is physically separate fromscoreRateLimitStore(public/scores).apiAdsRouter: dedicatedrateLimitStorefor rewarded-ad session lifecycle endpoints.
- Reset-Bypass Immunity: A valid login to
attacker@example.comresets onlyauth:login:acct:attacker@example.com—it NEVER resetsauth:login:ip:<attackerIp>, preventing attackers from resetting their IP spray counter by interleaving valid logins to their own throwaway account. - Unified Multi-Identifier OTP & Resend Binding (Zero 2x Bucket-Split Bypass): On
POST /api/auth/verify-emailandPOST /api/auth/resend-verification, the server always binds deduplicated keys acrossbody.email,auth.user.email(from the active session), ANDauth.user.id(uid), so alternating cookie-only ({ code }) and cookieless ({ email, code }) requests strictly shares one12-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 Mode | Default Threshold & Window | Keying Dimensions | Environment Overrides |
|---|---|---|---|---|
POST /api/auth/login | Failure-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-email | Failure-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-email | Failure-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/signup | Request-count anti-spam | 20 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-verification | Request-count anti-spam | 5 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/token | Failure-only | 30 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/sprites | Shared 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/autofix | Short burst + shared Vertex AI hourly cost guard | 6 req / 1 min (user & IP)<br/>+ shared 30/h user / 60/h IP | uid:<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 shield | 60 starts / 10 min (user), 120 (IP)<br/>120 actions / 10 min (actor), 240 (IP) | uid/vid/ip | RATE_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/scores | Rapid-fire score spam shield | 20 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 Cap | Memory ceiling per store | 10,000 keys max (hard upper bound) | All stores | RATE_LIMIT_MAX_KEYS (1..10000) |
All 429 RATE_LIMITED responses return:
HTTP 429 Too Many RequestsRetry-After: <seconds>X-RateLimit-Limit,X-RateLimit-Remaining: 0,X-RateLimit-ResetCache-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:
- Rapid-Fire Spam Gate (
429 RATE_LIMITED): Enforces<= 20score posts per60 secondsper actor (userId> establishedvisitorId>ip-anon), plus a per-IP ceiling (60/min) to stop cookie-rotation bots. - 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 JSON1e309) with400 INVALID_SCORE. - Rejects negative numbers (
< 0), non-integer floats (e.g.12.5), and absurdly spoofed values exceedingMAX_LEADERBOARD_SCORE(1,000,000, configurable viaLEADERBOARD_MAX_SCORE <= 1,000,000) with400 SCORE_OUT_OF_BOUNDS. - Normalizes
-0to0.
- Player Name Control & Bidi/RTL Spoof Rejection (
400 INVALID_PLAYER_NAME):
- Hard-rejects any
playerNamecontaining: - 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
playerNametypes (400 INVALID_PLAYER_NAME). - Strips HTML tags (
<[^>]*>) and angle brackets (<>), collapses whitespace, and bounds clean names to32characters (Anonymous Playerfallback 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:
- Distributed-IP 6-Digit OTP Brute-Force Lockout (
429 RATE_LIMITED+Retry-After) & Clean Reset: Proves12failed OTP attempts against an account across rotatingX-Forwarded-ForIPs trigger429 RATE_LIMITED+ numericRetry-Afteron attempt13(even with the valid OTP!), while a separate account with< 12failed attempts resets cleanly back to0upon valid verification. - Password Brute-Force Lockout & Clean Login Reset: Proves
12failedPOST /api/auth/loginattempts trigger429 RATE_LIMITED+Retry-After, and valid login resets per-account failures cleanly. - Signup & Resend-Verification Anti-Spam Shield: Proves automated
POST /api/auth/resend-verificationemail-bombing triggers429 RATE_LIMITEDafter5attempts. - Vertex AI Hourly Quota Shield: Proves
POST /api/games/generateenforces the configurable hourly per-user Vertex AI quota (429 RATE_LIMITED+Retry-After) without burning the user'sadGrantToken. - Bounded LRU Eviction Proof (
<= 10,000keys): FloodsSlidingWindowStorewith11,000distinct spoofed IPs and verifiesstore.size === 10_000,store.evictionCount === 1_000, and strict LRU ordering. - Leaderboard Anti-Cheat Suite: Proves
999999999,1000001,-10,42.5return400 SCORE_OUT_OF_BOUNDS;NaN/Infinity(1e309)/string return400 INVALID_SCORE; RTL-override\u202E, NUL\x00, CRLF\r\n, and ZWSP\u200BinplayerNamereturn400 INVALID_PLAYER_NAME; and21rapid score posts/min trigger429 RATE_LIMITED+Retry-After. - 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, asserting400 PROTOTYPE_POLLUTION_BLOCKEDand({}).polluted === undefined && ({}).pwned === undefined. - Zero-ZIP Export & Unverified Creator Enforcement: Verifies
GET /api/games/:slug/export.zipreturns403 ZIP_EXPORT_DISABLEDand unverified accounts attemptingPOST /api/games/generatereceive403 EMAIL_VERIFICATION_REQUIRED.