| … | … | @@ -285,9 +285,43 @@ function withRateLimit(handler) { |
| 285 | 285 | } |
| 286 | 286 | } |
| 287 | 287 | |
| 288 | | // CORS headers |
| 289 | | function setCORS(res) { |
| 290 | | res.setHeader('Access-Control-Allow-Origin', '*') |
| 288 | // CORS Configuration |
| 289 | // Define allowed origins (whitelist) |
| 290 | const ALLOWED_ORIGINS = [ |
| 291 | 'http://localhost:4004', |
| 292 | 'http://127.0.0.1:4004', |
| 293 | 'http://0.0.0.0:4004' |
| 294 | // Add production origins here when deploying: |
| 295 | // 'https://your-production-domain.com' |
| 296 | ] |
| 297 | |
| 298 | // If running under Pear, add the Pear protocol origin |
| 299 | if (isPear && typeof Pear !== 'undefined' && Pear.config?.key) { |
| 300 | ALLOWED_ORIGINS.push(`pear://${Pear.config.key}`) |
| 301 | } |
| 302 | |
| 303 | /** |
| 304 | * Set CORS headers with origin whitelist |
| 305 | * @param {ServerResponse} res - HTTP response |
| 306 | * @param {IncomingMessage} req - HTTP request |
| 307 | */ |
| 308 | function setCORS(res, req) { |
| 309 | const origin = req.headers.origin || req.headers.referer |
| 310 | |
| 311 | // Check if origin is in whitelist |
| 312 | if (origin && ALLOWED_ORIGINS.some(allowed => origin.startsWith(allowed))) { |
| 313 | res.setHeader('Access-Control-Allow-Origin', origin) |
| 314 | res.setHeader('Access-Control-Allow-Credentials', 'true') |
| 315 | } else if (!origin) { |
| 316 | // No origin header (e.g., same-origin request or API client) |
| 317 | // Allow localhost by default for development |
| 318 | res.setHeader('Access-Control-Allow-Origin', ALLOWED_ORIGINS[0]) |
| 319 | } else { |
| 320 | // Origin not in whitelist - log warning but still set a default |
| 321 | console.warn(`⚠️ CORS: Blocked origin: ${origin}`) |
| 322 | res.setHeader('Access-Control-Allow-Origin', ALLOWED_ORIGINS[0]) |
| 323 | } |
| 324 | |
| 291 | 325 | res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, DELETE, PUT') |
| 292 | 326 | res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization') |
| 293 | 327 | } |
| … | … | @@ -1498,7 +1532,7 @@ async function startServer() { |
| 1498 | 1532 | |
| 1499 | 1533 | // Main HTTP server |
| 1500 | 1534 | server = http.createServer(async (req, res) => { |
| 1501 | | setCORS(res) |
| 1535 | setCORS(res, req) |
| 1502 | 1536 | |
| 1503 | 1537 | // Handle OPTIONS (CORS preflight) |
| 1504 | 1538 | if (req.method === 'OPTIONS') { |