Skip to main content
Developer & Creator Documentation

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).

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

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:

ConcernGCP Project IDDetails
Hosting, Cloud Run, Cloud CDN, GCS, Cert Manager, Secretsyourplaygroundgames (GCP_PROJECT_ID)Name: YourPlayGroundGames, Project Number: 345233859084, Billing Account: 0133C4-DC9328-F1E137.
Vertex AI Text/Code/Image Inferenceids-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 TypeResource NameLive Value / Target
Global Static Anycast IPv4ypg-global-ip34.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 Certificateypg-prod-certMulti-domain TLS 1.3 cert bound to ypg-dns-auth-apex + ypg-dns-auth-www
Certificate Mapypg-cert-mapEntries: ypg-entry-apex (yourplayground.games), ypg-entry-www (www.yourplayground.games)

Authoritative DNS Cutover Records (yourplayground.games)

TypeHost / NameTarget / ValuePurpose
A@ (yourplayground.games)34.111.159.207Routes apex domain to Global External ALB (301 -> www)
Awww (www.yourplayground.games)34.111.159.207Routes 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

HostnameRoleBehavior
www.yourplayground.gamesPrimary Canonical OriginServes SSR HTML (no-store), APIs (no-store), static assets (Cloud CDN cached), and isolated /runtime/* sandboxes (HTTP 200).
yourplayground.gamesApex AliasPermanent HTTP 301 redirect to https://www.yourplayground.games<originalUrl>.
playground.games (optional -IncludeLegacyPlaygroundDomains)Legacy AliasPermanent HTTP 301 redirect to https://www.yourplayground.games<originalUrl>.
www.playground.games (optional -IncludeLegacyPlaygroundDomains)Legacy WWW AliasPermanent 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-state in Cloud Run; optional GCS_STATE_PREFIX). When GCS_STATE_BUCKET is 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, lists gs://$GCS_STATE_BUCKET over the native GCS JSON REST API (storage.googleapis.com, zero external npm dependencies) and atomically writes storage/users.json, storage/catalog.json, storage/sessions.json, storage/ai-budget.json, and storage/games/<slug>/* via writeBinaryAtomic. 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), and src/services/aiBudgetGuardService.mjs (acquireAiExecutionSlot -> storage/ai-budget.json) invoke scheduleMirrorFile / 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 on SIGTERM (flushPendingSyncs).
  • Authentication: Uses the Cloud Run Metadata Server (http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token with Metadata-Flavor: Google) first, falling back to Application Default Credentials (Authorized User refresh token or Service Account RS256 JWT) and gcloud auth print-access-token for 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.

VariablePurpose
GCP_PROJECT_IDyourplaygroundgames (hosting, Cloud Run, GCS state bucket, Certificate Manager, Cloud Armor, Secret Manager).
VERTEX_PROJECT_IDids-hybrid-model (Vertex AI Gemini 4 + Nano Banana 2.1 inference; overridable).
GCS_STATE_BUCKETyourplaygroundgames-state (enables Zero-SQL GCS boot hydration & coalesced async write mirroring, including ai-budget.json).
SESSION_SECRET64-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_SECRETIndependent 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_CAPDurable 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_MAXPer-verified-creator hourly AI cap (3/hour default; per-IP cap 6/hour).
RATE_LIMIT_AI_DAILY_USER_MAXPer-verified-creator durable UTC-day AI cap (5/day default; returns HTTP 429 USER_DAILY_AI_QUOTA_REACHED).
MAX_CONCURRENT_AI_JOBSPer-instance in-flight Vertex AI concurrency cap (3 default; returns HTTP 503 AI_STUDIO_BUSY with Retry-After: 15).
TRUST_PROXY_HOPSExact 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_IMPORTSet to false in production (returns HTTP 403 ZIP_IMPORT_DISABLED on POST /api/games/import-zip).
GOOGLE_CLIENT_IDGCP OAuth 2.0 Web Client ID (authorized redirect URI: https://www.yourplayground.games/auth/google/callback).
GOOGLE_CLIENT_SECRETGCP OAuth 2.0 Web Client Secret.
GOOGLE_REDIRECT_URIhttps://www.yourplayground.games/auth/google/callback.
SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROMOutbound 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_IDLive Google AdSense publisher (ca-pub-9167883877537692) and rewarded ad slot ID.
ALLOW_TEST_AUTHSet 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:

  1. Google Cloud Armor Edge Policy (ypg-armor-policy): Provisioned idempotently by scripts/gcp/provision-cert-and-cloudrun.ps1 and attached to ypg-backend-service (--security-policy=ypg-armor-policy):
  • Rule 1000 (API Shield): Matches request.path.matches('^/api/(games|auth|ads)'), applies rate-based-ban at 60 requests / 60s per client IP, enforcing a 600s HTTP 429 (deny-429) ban at Google's Anycast edge.
  • Rule 2000 (Global Flood Shield): Matches true, applies rate-based-ban at 300 requests / 60s per client IP, enforcing a 600s HTTP 429 (deny-429) ban.
  1. XFF Spoofing Immunity (TRUST_PROXY_HOPS=2): Express app.set('trust proxy', 2) and extractClientIp() select the client IP strictly from the right side of X-Forwarded-For (parts[length - 2]). Rotating fake leftmost X-Forwarded-For headers can never bypass per-IP rate limits.
  2. Durable Global Daily AI Cap & Concurrency Guard (src/services/aiBudgetGuardService.mjs):
  • Persists UTC-day counters in storage/ai-budget.json (synced with gs://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), and MAX_CONCURRENT_AI_JOBS=3 (503 AI_STUDIO_BUSY) before burning adGrantToken or invoking Vertex AI, while keeping all free arcade gameplay routes 100% open.
  • Atomically ties single-use adGrantToken burn to budget increment inside updateJsonAtomic so replay attacks (402) can never drain the platform daily budget.
  1. 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 HTTP 403 FORBIDDEN_NOT_OWNER on /iterate, /autofix, and /sprites.
  • POST /api/games/:slug/sprites requires a verified creator session, game ownership, and a single-use adGrantToken (402 AD_REQUIRED if missing).
  • POST /api/games/:slug/autofix permits up to 2 free repairs per game (autofixCount), after which HTTP 429 AUTOFIX_LIMIT_REACHED requires a valid adGrantToken.
  • POST /api/games/import-zip returns HTTP 403 ZIP_IMPORT_DISABLED in production (ALLOW_ZIP_IMPORT=false).
  1. 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): 10 RPM (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): 6 RPM.

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

  1. curl -I https://www.yourplayground.games/api/health returns HTTP/2 200 with valid Google Trust Services TLS certificate (ypg-prod-cert).
  2. curl -I https://yourplayground.games/studio returns HTTP/2 301 with location: https://www.yourplayground.games/studio.
  3. curl -I http://www.yourplayground.games/ returns HTTP/1.1 301 -> https://www.yourplayground.games/.
  4. GET /api/games/neon-odyssey/export.zip returns HTTP/2 403 (ZIP_EXPORT_DISABLED) and POST /api/games/import-zip returns HTTP/2 403 (ZIP_IMPORT_DISABLED).
  5. Anonymous POST /api/ads/sessions and POST /api/games/generate return HTTP/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.json appear in gs://yourplaygroundgames-state/.
  6. gcloud compute backend-services describe ypg-backend-service --global --project=yourplaygroundgames --format="value(securityPolicy)" confirms ypg-armor-policy is attached.
  7. Restarting a Cloud Run revision hydrates users.json, catalog.json, ai-budget.json, and games/* cleanly from gs://yourplaygroundgames-state/ with zero data loss and preserved daily AI budget counters.