const path = require('path'); const dotenv = require('dotenv'); // Load environment variables dotenv.config(); // Error monitoring — a no-op if SENTRY_DSN isn't set, so this is safe in every // environment (dev, a fresh deploy that hasn't configured Sentry yet, etc.). // Must run before express/@prisma/client are required below — Sentry's // auto-instrumentation patches those modules via a require hook, which only // works if Sentry.init() runs before they're first required into the cache. if (process.env.SENTRY_DSN) { const Sentry = require('@sentry/node'); Sentry.init({ dsn: process.env.SENTRY_DSN, environment: process.env.NODE_ENV || 'development', // Small single-VM deployment, not high-traffic — start conservative and raise // this once real usage is visible in Sentry, rather than sampling every request. tracesSampleRate: 0.1, }); } const express = require('express'); const { version: API_VERSION } = require('../package.json'); const cors = require('cors'); const rateLimit = require('express-rate-limit'); const prisma = require('./config/db'); const { notFound, errorHandler } = require('./middleware/errorMiddleware'); const getRawBody = require('raw-body'); // Initialize Express app const app = express(); const PORT = process.env.PORT || 3000; // Express 5 parses query strings the simple way by default; keep Express 4's (qs) so // ?a[b]=1 style filters keep working. app.set('query parser', 'extended'); // Trust proxy — required when running behind a reverse proxy (e.g. nginx on a // separate server) so req.ip / X-Forwarded-For are read correctly by // express-rate-limit and friends. Accepts a hop count ("1"), "true"/"false", // or a comma-separated list of trusted proxy IPs/CIDRs. if (process.env.TRUST_PROXY) { const raw = process.env.TRUST_PROXY.trim(); let trustProxyValue; if (raw === 'true') trustProxyValue = true; else if (raw === 'false') trustProxyValue = false; else if (/^\d+$/.test(raw)) trustProxyValue = parseInt(raw, 10); else if (raw.includes(',')) trustProxyValue = raw.split(',').map((s) => s.trim()); else trustProxyValue = raw; app.set('trust proxy', trustProxyValue); console.log(`[startup] trust proxy set to: ${JSON.stringify(trustProxyValue)}`); } // CORS — allow only the configured frontend origin const allowedOrigins = (process.env.FRONTEND_URL || 'http://localhost:3000') .split(',') .map((o) => o.trim()); const isDev = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV; const isTesting = process.env.NODE_ENV === 'testing'; const isProd = process.env.NODE_ENV === 'production'; const modeLabel = isProd ? 'production' : isTesting ? 'testing' : 'development'; console.log(`Running in ${modeLabel} mode.`); // In testing or production, require all critical env vars to be set at startup if (isTesting || isProd) { const required = ['DATABASE_URL', 'JWT_SECRET']; const missing = required.filter(k => !process.env[k]); if (missing.length > 0) { console.error(`[startup] Missing required environment variables for ${modeLabel} mode: ${missing.join(', ')}`); process.exit(1); } } app.use(cors({ origin: (origin, callback) => { // Allow requests with no origin (e.g. mobile apps, curl, Postman) if (!origin) return callback(null, true); // Always allow configured origins if (allowedOrigins.includes(origin)) return callback(null, true); // In dev or testing, also allow any LAN origin on the same port (e.g. phone on 192.168.x.x:3000) if (isDev || isTesting) { try { const u = new URL(origin); const isLan = /^(192\.168\.|10\.|172\.(1[6-9]|2\d|3[01])\.)/.test(u.hostname); if (isLan) return callback(null, true); } catch {} } callback(new Error(`CORS: origin '${origin}' not allowed`)); }, credentials: true, })); // Global rate limiter — 5000 requests per 5 minutes per IP // Webhooks are excluded because they come from Yoco's servers and are already HMAC-verified const globalLimiter = rateLimit({ windowMs: 5 * 60 * 1000, max: 5000, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests, please try again later.' }, skip: (req) => RAW_BODY_PREFIXES.some(p => req.path.startsWith(p)), }); // Incoming webhooks and links in sent messages on v2 (1.51.16): see src/v2/links.ts. const { RAW_BODY_PREFIXES, webhooksRouter, linksRouter, legacyLinkRedirects, legacyV1Router, v1Removed } = require('./v2/links'); // /api/v2 answers every error as { error: { code, message } }, including the shared // middleware below (rate limits, read-only guards, auth) that writes v1's { message }. app.use('/api/v2', require('./v2/errors').legacyErrorsToV2); app.use(globalLimiter); // Impersonation is strictly read-only: refuse every write made with an impersonation // token before it can reach any route (see utils/impersonation.js). app.use(require('./utils/impersonation').readOnlyGuard); // Raw body parsing middleware for webhooks app.use((req, res, next) => { if (RAW_BODY_PREFIXES.some(p => req.path.startsWith(p))) { getRawBody(req, { length: req.headers['content-length'], encoding: 'utf-8' }, (err, rawBody) => { if (err) return next(err); req.rawBody = rawBody; next(); }); } else { next(); } }); const webhookRoutes = require('./routes/webhookRoutes'); // Mount webhook routes BEFORE JSON body parser to avoid double-reading the stream app.use('/api/webhooks', webhookRoutes); app.use('/api/v2/webhooks', webhooksRouter); // Apply JSON body parser for all non-webhook routes app.use(express.json()); // Express 5 leaves req.body undefined when a request has no JSON body; handlers expect {}. app.use((req, res, next) => { if (req.body === undefined) req.body = {}; next(); }); // Count server errors (any 5xx response) for the Hub heartbeat. app.use((req, res, next) => { res.on('finish', () => { if (res.statusCode >= 500) require('./utils/errorCounter').recordError(); }); next(); }); // Licence suspended, revoked or missing: no new or edited events, registrations or payments (src/hub/readOnly.js). app.use(require('./hub/readOnly').licenceReadOnly); // Everything the backend serves is under /api (2.2.0), so the site and its API can share one // address: the web server sends /api to the backend and everything else to the frontend. The old // paths (/, /health, /docs/v2, /uploads) still work for sites with a separate API address. // Health for monitoring (and the Hub): no secrets, no personal information. app.get(['/api/health', '/health'], async (req, res) => { const report = require('./hub/report'); let db = true; try { await prisma.$queryRaw`SELECT 1`; } catch { db = false; } const health = db ? await report.health().catch(() => null) : null; res.status(db ? 200 : 503).json({ status: db ? 'ok' : 'error', version: report.APP_VERSION, db, jobs: health?.jobs || null, lastBackupAt: health?.lastBackupAt || null, }); }); // Use routes // /api/v2 (1.51.0, TypeScript): consistent errors and paging, described by OpenAPI at /docs/v2. app.use('/api/v2', linksRouter); app.use('/api/v2', require('./v2').v2Router()); // Links in messages already sent: v1 addresses answer 308 with their v2 one. app.use(legacyLinkRedirects); app.use('/api/docs/v2', require('./v2').v2DocsRouter()); app.get('/api/docs', (req, res) => res.redirect(301, '/api/docs/v2')); // Before 2.2.0 the reference was at /docs/v2 (bookmarks, the old status page). app.use('/docs/v2', (req, res) => res.redirect(301, `/api${req.originalUrl}`)); app.get('/docs', (req, res) => res.redirect(301, '/api/docs/v2')); // Pre-warm the settings cache so synchronous helpers have DB values from startup const { getSettingSync, warmCache } = require('./utils/settingsCache'); warmCache().catch(() => {}); // Uploaded branding assets can include SVGs, which may embed