From 3a8a61487a5de7daacdbdd75a22f30bf839d9499 Mon Sep 17 00:00:00 2001 From: xiaomai Date: Sun, 3 May 2026 19:22:38 +0800 Subject: [PATCH] feat(config): support multiple CORS origins and dynamic docker env vars Parse comma-separated origins in FRONTEND_ORIGIN for Fastify CORS Use host environment variables with fallbacks in docker-compose Add Cloudflared tunnel deployment examples to .env.example --- .env.example | 9 ++++++++- backend/src/server.ts | 16 +++++++++++++++- docker-compose.yml | 6 +++--- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/.env.example b/.env.example index 154c044..7237db3 100644 --- a/.env.example +++ b/.env.example @@ -6,8 +6,15 @@ BACKEND_PORT=3001 TRUST_PROXY=false FRONTEND_ORIGIN=http://localhost:20015 APP_ORIGIN=http://localhost:20015 -VITE_API_BASE_URL=http://localhost:3001 +BACKEND_PUBLIC_ORIGIN=http://localhost:20016 +VITE_API_BASE_URL=http://localhost:20016 VITE_SITE_URL=https://pokopiawiki.tootaio.com RESEND_API_KEY= EMAIL_FROM="Pokopia Wiki " AI_MODERATION_API_KEY= + +# Cloudflared tunnel deployment example: +# FRONTEND_ORIGIN=https://pokopiawiki.tootaio.com,http://localhost:20015 +# APP_ORIGIN=https://pokopiawiki.tootaio.com +# BACKEND_PUBLIC_ORIGIN=https://api-pokopiawiki.tootaio.com +# VITE_API_BASE_URL=https://api-pokopiawiki.tootaio.com diff --git a/backend/src/server.ts b/backend/src/server.ts index 977677f..e9700a3 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -128,10 +128,24 @@ const app = Fastify({ trustProxy: process.env.TRUST_PROXY === 'true' }); +function configuredCorsOrigin(): true | string | string[] { + const rawOrigin = process.env.FRONTEND_ORIGIN?.trim(); + if (!rawOrigin) { + return true; + } + + const origins = rawOrigin + .split(',') + .map((origin) => origin.trim()) + .filter(Boolean); + + return origins.length <= 1 ? (origins[0] ?? true) : origins; +} + await app.register(cors, { allowedHeaders: ['Authorization', 'Content-Type', 'X-Locale'], methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], - origin: process.env.FRONTEND_ORIGIN ?? true + origin: configuredCorsOrigin() }); await app.register(rateLimit, { diff --git a/docker-compose.yml b/docker-compose.yml index 70d1769..65a60a5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -21,10 +21,10 @@ services: DATABASE_URL: postgres://pokopia:pokopia@postgres:5432/pokopia BACKEND_PORT: 3001 TRUST_PROXY: ${TRUST_PROXY:-false} - FRONTEND_ORIGIN: http://localhost:20015 - APP_ORIGIN: http://localhost:20015 + FRONTEND_ORIGIN: ${FRONTEND_ORIGIN:-http://localhost:20015} + APP_ORIGIN: ${APP_ORIGIN:-http://localhost:20015} UPLOAD_DIR: /app/uploads - BACKEND_PUBLIC_ORIGIN: http://localhost:20016 + BACKEND_PUBLIC_ORIGIN: ${BACKEND_PUBLIC_ORIGIN:-http://localhost:20016} RESEND_API_KEY: ${RESEND_API_KEY:-} EMAIL_FROM: "${EMAIL_FROM:-Pokopia Wiki }" ports: