GCP Cloud Run Deployment, Cloud CDN, Zero-SQL GCS Persistence & Multi-Domain SSL Runbook
Production infrastructure and SRE runbook for YourPlayground.games (https://www.yourplayground.games).
1. Dedicated GCP Project Split & Live Provisioned Edge Resources
Hosting, edge TLS, Cloud CDN, Artifact Registry, Secret Manager, and Zero-SQL persistent state run in the dedicated yourplaygroundgames GCP project, while Vertex AI generative inference continues targeting ids-hybrid-model (location: global) where Gemini 4 (gemini-4-neon, gemini-4-carbon) and gemini-nano-banana-2.1 preview quotas live:
| Concern | GCP Project ID | Details |
|---|---|---|
| Hosting, Cloud Run, Cloud CDN, GCS, Cert Manager, Secrets | yourplaygroundgames (GCP_PROJECT_ID) | Name: YourPlayGroundGames, Project Number: 345233859084, Billing Account: 0133C4-DC9328-F1E137. |
| Vertex AI Text/Code/Image Inference | ids-hybrid-model (VERTEX_PROJECT_ID) | VERTEX_LOCATION=global, VERTEX_DEFAULT_MODEL=gemini-4-neon, VERTEX_REPAIR_MODEL=gemini-4-carbon, gemini-nano-banana-2.1. Cross-project IAM: ypg-cloudrun-sa@yourplaygroundgames.iam.gserviceaccount.com holds roles/aiplatform.user on ids-hybrid-model. |
Live Provisioned GCP Edge Resources (yourplaygroundgames / #345233859084)
The following production edge resources are already provisioned on yourplaygroundgames and are reused idempotently by scripts/gcp/provision-cert-and-cloudrun.ps1:
| Resource Type | Resource Name | Live Value / Target |
|---|---|---|
| Global Static Anycast IPv4 | ypg-global-ip | 34.111.159.207 |
| DNS Authorization (Apex) | ypg-dns-auth-apex (yourplayground.games) | _acme-challenge.yourplayground.games. CNAME f9ed2b18-8bbd-4ed9-aa9b-fa8fcb594664.10.authorize.certificatemanager.goog. |
| DNS Authorization (WWW) | ypg-dns-auth-www (www.yourplayground.games) | _acme-challenge.www.yourplayground.games. CNAME 934b2970-4b98-4078-868a-b0226a0e1858.10.authorize.certificatemanager.goog. |
| Google-Managed Certificate | ypg-prod-cert | Multi-domain TLS 1.3 cert bound to ypg-dns-auth-apex + ypg-dns-auth-www |
| Certificate Map | ypg-cert-map | Entries: ypg-entry-apex (yourplayground.games), ypg-entry-www (www.yourplayground.games) |
Authoritative DNS Cutover Records (yourplayground.games)
| Type | Host / Name | Target / Value | Purpose |
|---|---|---|---|
A | @ (yourplayground.games) | 34.111.159.207 | Routes apex domain to Global External ALB (301 -> www) |
A | www (www.yourplayground.games) | 34.111.159.207 | Routes canonical primary origin to Cloud CDN + Cloud Run |
CNAME | _acme-challenge.yourplayground.games. | f9ed2b18-8bbd-4ed9-aa9b-fa8fcb594664.10.authorize.certificatemanager.goog. | Google Certificate Manager DNS-01 validation (ypg-dns-auth-apex) |
CNAME | _acme-challenge.www.yourplayground.games. | 934b2970-4b98-4078-868a-b0226a0e1858.10.authorize.certificatemanager.goog. | Google Certificate Manager DNS-01 validation (ypg-dns-auth-www) |
Strict Managed Edge TLS Law (scar-gcp-no-sslip-nginx)
All production traffic terminates TLS 1.3 exclusively at Google's managed edge:
Client DNS A -> ypg-global-ip (34.111.159.207, Global Anycast IPv4)
-> Global External Application Load Balancer (HTTPS:443 + HTTP:80->443 301)
-> Google Certificate Manager (ypg-cert-map / ypg-prod-cert)
-> Cloud CDN Backend Service (ypg-backend-service, --enable-cdn, --cache-mode=USE_ORIGIN_HEADERS)
-> Serverless NEG (ypg-cloudrun-neg)
-> Cloud Run Service (yourplayground-games, --ingress=internal-and-cloud-load-balancing)
Raw VM reverse proxies and wildcard IP-to-DNS shortcuts are strictly prohibited.
2. Domain Canonicalization & Certificate Scope
| Hostname | Role | Behavior |
|---|---|---|
www.yourplayground.games | Primary Canonical Origin | Serves SSR HTML (no-store), APIs (no-store), static assets (Cloud CDN cached), and isolated /runtime/* sandboxes (HTTP 200). |
yourplayground.games | Apex Alias | Permanent HTTP 301 redirect to https://www.yourplayground.games<originalUrl>. |
playground.games (optional -IncludeLegacyPlaygroundDomains) | Legacy Alias | Permanent HTTP 301 redirect to https://www.yourplayground.games<originalUrl>. |
www.playground.games (optional -IncludeLegacyPlaygroundDomains) | Legacy WWW Alias | Permanent HTTP 301 redirect to https://www.yourplayground.games<originalUrl>. |
src/app.mjs (app.set('trust proxy', trustProxyHops), configured to TRUST_PROXY_HOPS=2 in production for Google Global External ALB + Cloud Run GFE) inspects X-Forwarded-Host / Host and parses the client IP strictly from the right side of X-Forwarded-For so clients can never spoof arbitrary leftmost IP headers to bypass rate limits. It emits canonical 301 redirects automatically while never redirecting localhost or 127.0.0.1. Cloud CDN uses --cache-mode=USE_ORIGIN_HEADERS so SSR HTML (Cache-Control: no-store, no-cache, must-revalidate) and authenticated APIs are never cached at the edge, while immutable/public assets (/brand/*, /creatives/*, /vendor/*, /api/syndication/121games) accelerate globally.
3. Zero-SQL Cloud Run Persistent Storage (src/storage/cloudStorageSync.mjs)
Cloud Run container filesystems are ephemeral across revisions and cold starts. To maintain 0% relational database dependencies while persisting user accounts, sessions, catalog updates, leaderboards, and newly generated games:
- Activation Gate: Controlled solely by
GCS_STATE_BUCKET(e.g.,GCS_STATE_BUCKET=yourplaygroundgames-statein Cloud Run; optionalGCS_STATE_PREFIX). WhenGCS_STATE_BUCKETis unset locally or in unit/integration tests, the adapter is a 100% zero-overhead synchronous no-op with zero network or disk calls. - Boot Hydration (
server.mjs->hydrateFromCloudStorage): Before binding the HTTP port on Cloud Run startup, listsgs://$GCS_STATE_BUCKETover the native GCS JSON REST API (storage.googleapis.com, zero external npm dependencies) and atomically writesstorage/users.json,storage/catalog.json,storage/sessions.json,storage/ai-budget.json, andstorage/games/<slug>/*viawriteBinaryAtomic. If the bucket is empty on initial deployment, the container's bundled seeded showcase catalog is preserved intact. - Async Write-Through Mirroring: Atomic mutations in
src/storage/authRepository.mjs(upsertUser,createPasswordUser,updateUserVerification,createSession,deleteSession),src/storage/gameRepository.mjs(saveGame,saveGameSprite,recordScore,incrementPlays), andsrc/services/aiBudgetGuardService.mjs(acquireAiExecutionSlot->storage/ai-budget.json) invokescheduleMirrorFile/scheduleMirrorGame, which coalesce and serialize uploads per object key (preventing out-of-order races and GCS 1-write/sec rate-limit saturation) with bounded retry backoff and graceful flush onSIGTERM(flushPendingSyncs). - Authentication: Uses the Cloud Run Metadata Server (
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/tokenwithMetadata-Flavor: Google) first, falling back to Application Default Credentials (Authorized User refresh token or Service Account RS256 JWT) andgcloud auth print-access-tokenfor staging workstations.
4. Container Build & Local Parity
The root Dockerfile packages Node.js 22 slim with non-root node execution, PORT=8080 for Cloud Run (local node server.mjs remains PORT=9033), GCP_PROJECT_ID=yourplaygroundgames, VERTEX_PROJECT_ID=ids-hybrid-model, and an integrated /api/health container healthcheck.
# Local container verification (offline / ephemeral local storage — GCS_STATE_BUCKET unset)
docker build -t yourplayground-games:local .
docker run --rm -p 9033:8080 -e PORT=8080 yourplayground-games:local
5. Production Secrets & Environment Variables (Secret Manager)
scripts/gcp/provision-cert-and-cloudrun.ps1 automatically provisions high-entropy 64-byte CSPRNG HMAC secrets (ypg-session-secret, ypg-ad-hmac-secret) in Google Cloud Secret Manager (without echoing secret bytes to stdout) and binds them to Cloud Run via --set-secrets=SESSION_SECRET=ypg-session-secret:latest,AD_HMAC_SECRET=ypg-ad-hmac-secret:latest. In NODE_ENV=production, server.mjs and src/app.mjs fail closed (CONFIG_SECRET_REQUIRED) at boot if either secret is missing, shorter than 32 characters, or matches the local dev fallback.
| Variable | Purpose |
|---|---|
GCP_PROJECT_ID | yourplaygroundgames (hosting, Cloud Run, GCS state bucket, Certificate Manager, Cloud Armor, Secret Manager). |
VERTEX_PROJECT_ID | ids-hybrid-model (Vertex AI Gemini 4 + Nano Banana 2.1 inference; overridable). |
GCS_STATE_BUCKET | yourplaygroundgames-state (enables Zero-SQL GCS boot hydration & coalesced async write mirroring, including ai-budget.json). |
SESSION_SECRET | 64-byte CSPRNG hex HMAC secret from Secret Manager (ypg-session-secret:latest) for signed ypg_sid / ypg_vid cookies and OAuth state tokens. |
AD_HMAC_SECRET | Independent 64-byte CSPRNG hex HMAC secret from Secret Manager (ypg-ad-hmac-secret:latest) for single-use Watch-Ad-to-Generate tokens. |
GLOBAL_DAILY_AI_CAP | Durable UTC-day global Vertex AI hard cap (50 operations/UTC day in production; persists in storage/ai-budget.json mirrored to GCS). Returns HTTP 503 DAILY_AI_BUDGET_REACHED with Retry-After to 00:00 UTC. |
RATE_LIMIT_AI_HOURLY_MAX | Per-verified-creator hourly AI cap (3/hour default; per-IP cap 6/hour). |
RATE_LIMIT_AI_DAILY_USER_MAX | Per-verified-creator durable UTC-day AI cap (5/day default; returns HTTP 429 USER_DAILY_AI_QUOTA_REACHED). |
MAX_CONCURRENT_AI_JOBS | Per-instance in-flight Vertex AI concurrency cap (3 default; returns HTTP 503 AI_STUDIO_BUSY with Retry-After: 15). |
TRUST_PROXY_HOPS | Exact trusted reverse-proxy hop count (2 in production for Global External ALB + Cloud Run GFE) so X-Forwarded-For is parsed strictly from the right. |
ALLOW_ZIP_IMPORT | Set to false in production (returns HTTP 403 ZIP_IMPORT_DISABLED on POST /api/games/import-zip). |
GOOGLE_CLIENT_ID | GCP OAuth 2.0 Web Client ID (authorized redirect URI: https://www.yourplayground.games/auth/google/callback). |
GOOGLE_CLIENT_SECRET | GCP OAuth 2.0 Web Client Secret. |
GOOGLE_REDIRECT_URI | https://www.yourplayground.games/auth/google/callback. |
SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM | Outbound transactional SMTP credentials for 6-digit email verification codes and 1-click links (or configure GMAIL_OAUTH_CLIENT_ID, GMAIL_OAUTH_CLIENT_SECRET, GMAIL_OAUTH_REFRESH_TOKEN). |
ADSENSE_PUBLISHER_ID, ADSENSE_SLOT_ID | Live Google AdSense publisher (ca-pub-9167883877537692) and rewarded ad slot ID. |
ALLOW_TEST_AUTH | Set to false in production (also mechanically enforced when NODE_ENV=production). |
6. Zero-Surprise-Bill & Anti-Botnet Production Armor
Five defense-in-depth layers cap Vertex AI spend, protect all 15 official showcase games, and neutralize botnet/XFF-spoofing attacks before requests ever reach Gemini 4 or Nano Banana 2.1:
- Google Cloud Armor Edge Policy (
ypg-armor-policy): Provisioned idempotently byscripts/gcp/provision-cert-and-cloudrun.ps1and attached toypg-backend-service(--security-policy=ypg-armor-policy):
- Rule
1000(API Shield): Matchesrequest.path.matches('^/api/(games|auth|ads)'), appliesrate-based-banat60requests /60sper clientIP, enforcing a600sHTTP429(deny-429) ban at Google's Anycast edge. - Rule
2000(Global Flood Shield): Matchestrue, appliesrate-based-banat300requests /60sper clientIP, enforcing a600sHTTP429(deny-429) ban.
- XFF Spoofing Immunity (
TRUST_PROXY_HOPS=2): Expressapp.set('trust proxy', 2)andextractClientIp()select the client IP strictly from the right side ofX-Forwarded-For(parts[length - 2]). Rotating fake leftmostX-Forwarded-Forheaders can never bypass per-IP rate limits. - Durable Global Daily AI Cap & Concurrency Guard (
src/services/aiBudgetGuardService.mjs):
- Persists UTC-day counters in
storage/ai-budget.json(synced withgs://yourplaygroundgames-state/ai-budget.json). - Enforces
GLOBAL_DAILY_AI_CAP=50(503 DAILY_AI_BUDGET_REACHED),RATE_LIMIT_AI_DAILY_USER_MAX=5(429 USER_DAILY_AI_QUOTA_REACHED), andMAX_CONCURRENT_AI_JOBS=3(503 AI_STUDIO_BUSY) before burningadGrantTokenor invoking Vertex AI, while keeping all free arcade gameplay routes100%open. - Atomically ties single-use
adGrantTokenburn to budget increment insideupdateJsonAtomicso replay attacks (402) can never drain the platform daily budget.
- Strict Ownership, Ad-Gated Sprites & Auto-Fix Caps (
src/routes/apiGamesRouter.mjs):
- All 15 official showcase games (
PROTECTED_SHOWCASE_SLUGS) and all non-owner user games return HTTP403 FORBIDDEN_NOT_OWNERon/iterate,/autofix, and/sprites. POST /api/games/:slug/spritesrequires a verified creator session, game ownership, and a single-useadGrantToken(402 AD_REQUIREDif missing).POST /api/games/:slug/autofixpermits up to2free repairs per game (autofixCount), after which HTTP429 AUTOFIX_LIMIT_REACHEDrequires a validadGrantToken.POST /api/games/import-zipreturns HTTP403 ZIP_IMPORT_DISABLEDin production (ALLOW_ZIP_IMPORT=false).
- Cloud Provider Hard Quotas & Billing Budget Alerts (Manual Operator Gate — Billing Account
0133C4-DC9328-F1E137):
6A. Vertex AI Per-Minute Quota Cap (ids-hybrid-model)
Set hard per-minute quotas on aiplatform.googleapis.com inside ids-hybrid-model so Google Cloud itself rejects any anomalous burst even if all application layers were misconfigured:
# Inspect current Vertex AI generate_content / image generation quotas on ids-hybrid-model
gcloud alpha services quota list `
--service=aiplatform.googleapis.com `
--consumer=projects/ids-hybrid-model `
--filter="metric:generate_content OR metric:online_prediction"
In Google Cloud Console -> IAM & Admin -> Quotas & System Limits (Project: ids-hybrid-model, Service: Vertex AI API / aiplatform.googleapis.com), cap:
Generate content requests per minute per project per base model(gemini-4-neon,gemini-4-carbon):10RPM (supports burst generation + 1-shot repair while keeping worst-case spend strictly bounded).Generate content requests per minute per project per base model(gemini-nano-banana-2.1,gemini-3-pro-image):6RPM.
6B. GCP Billing Budget Alerts (0133C4-DC9328-F1E137)
Create monthly billing budget alerts on Billing Account 0133C4-DC9328-F1E137 with 50%, 80%, 100% actual-spend and 100% forecasted-spend alerts (attach a Cloud Monitoring email notification channel or Pub/Sub kill-switch topic as needed):
# 1. Hosting Project Budget Alert (yourplaygroundgames / projects/345233859084)
gcloud billing budgets create `
--billing-account=0133C4-DC9328-F1E137 `
--display-name="YourPlayground.games Hosting Monthly Cap ($30)" `
--budget-amount=30USD `
--filter-projects=projects/345233859084 `
--threshold-rule=percent=0.50 `
--threshold-rule=percent=0.80 `
--threshold-rule=percent=1.00 `
--threshold-rule=percent=1.00,basis=forecasted-spend
# 2. Vertex AI Project Budget Alert (ids-hybrid-model — look up project number first)
$VertexProjectNumber = (gcloud projects describe ids-hybrid-model --format="value(projectNumber)")
gcloud billing budgets create `
--billing-account=0133C4-DC9328-F1E137 `
--display-name="YourPlayground.games Vertex AI Monthly Cap ($50)" `
--budget-amount=50USD `
--filter-projects="projects/$VertexProjectNumber" `
--threshold-rule=percent=0.50 `
--threshold-rule=percent=0.80 `
--threshold-rule=percent=1.00 `
--threshold-rule=percent=1.00,basis=forecasted-spend
7. Idempotent Dry-Run Provisioning
Inspect every gcloud command in safe dry-run mode before requesting Tier-2 release approval:
# Safe dry-run preview (prints every idempotent describe+create gcloud command without modifying GCP)
pwsh scripts/gcp/provision-cert-and-cloudrun.ps1
Every create step executes Invoke-IdempotentCreate (describe first -> reuse if already present), safely preserving live ypg-dns-auth-apex, ypg-dns-auth-www, ypg-prod-cert, ypg-cert-map (ypg-entry-apex, ypg-entry-www), ypg-global-ip (34.111.159.207), Secret Manager secrets (ypg-session-secret, ypg-ad-hmac-secret), and Cloud Armor policy ypg-armor-policy.
8. Post-Cutover Verification Checklist
curl -I https://www.yourplayground.games/api/healthreturnsHTTP/2 200with valid Google Trust Services TLS certificate (ypg-prod-cert).curl -I https://yourplayground.games/studioreturnsHTTP/2 301withlocation: https://www.yourplayground.games/studio.curl -I http://www.yourplayground.games/returnsHTTP/1.1 301->https://www.yourplayground.games/.GET /api/games/neon-odyssey/export.zipreturnsHTTP/2 403(ZIP_EXPORT_DISABLED) andPOST /api/games/import-zipreturnsHTTP/2 403(ZIP_IMPORT_DISABLED).- Anonymous
POST /api/ads/sessionsandPOST /api/games/generatereturnHTTP/2 401(AUTH_REQUIRED); verified Email or Google OAuth users cannot mutate official showcase games (HTTP/2 403 FORBIDDEN_NOT_OWNER), succeed on their own games, and newly saved users/games/ai-budget.jsonappear ings://yourplaygroundgames-state/. gcloud compute backend-services describe ypg-backend-service --global --project=yourplaygroundgames --format="value(securityPolicy)"confirmsypg-armor-policyis attached.- Restarting a Cloud Run revision hydrates
users.json,catalog.json,ai-budget.json, andgames/*cleanly fromgs://yourplaygroundgames-state/with zero data loss and preserved daily AI budget counters.