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); // The church's other products (2.4.0): the event feed, event.changed and Connect // (/api/feed/v1, /api/links/v1; src/links/routes.ts). Its own parsers (raw for the webhook). app.use('/api', require('./links/routes').crossProductRouter()); // 3.0.0: signing in through the church's Accounts (/api/auth/*, Accounts' calls at // /api/accounts/v1/events; src/accounts/signin.ts). Its own parsers (raw for Accounts' calls). app.use('/api', require('./accounts/signin').accountsRouter(require('./middleware/authMiddleware').protect)); // 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(); }); // 3.0.0: once sign-in goes through Accounts, Events' own sign-in, password and 2FA endpoints say // where to go instead, and profile changes go to Accounts (src/accounts/guard.ts). app.use((req, res, next) => { require('./accounts/guard').signInGuard(req, res, next).catch(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 files, with safe headers (utils/uploads.js): served from the folder they're saved in // (3.3.0; before, from one relative to where the process started, so a new logo could be "missing"). // Stored paths stay "/uploads/…"; they're given out as /api/uploads/… (v2/schemas.ts absoluteUrl). // /uploads still answers for links made before 2.2.0. const uploads = require('./utils/uploads').serveUploads(); app.use('/api/uploads', uploads, notFound); // a missing file is 404, not "API v1 removed" app.use('/uploads', uploads); // ── Shared page helpers ──────────────────────────────────────────────────────── function pageShell(title, accentColor, bodyHtml) { return ` ${title}
${bodyHtml}
`; } function formatUptime(seconds) { const d = Math.floor(seconds / 86400); const h = Math.floor((seconds % 86400) / 3600); const m = Math.floor((seconds % 3600) / 60); const s = Math.floor(seconds % 60); if (d > 0) return `${d}d ${h}h ${m}m`; if (h > 0) return `${h}h ${m}m ${s}s`; if (m > 0) return `${m}m ${s}s`; return `${s}s`; } function formatBytes(bytes) { if (bytes < 1024) return `${bytes} B`; if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / 1048576).toFixed(1)} MB`; } // ── Favicon ────────────────────────────────────────────────────────────────── app.get('/favicon.ico', (req, res) => { // From src/ either way (the build in dist/ copies only code). res.sendFile(path.join(__dirname, '..', 'src', 'favicon.ico')); }); // ── Status page, at /api (2.2.0); / sends you there ───────────────────────── app.get('/', (req, res) => res.redirect(302, '/api')); app.get('/api', async (req, res) => { const mem = process.memoryUsage(); const uptimeSec = process.uptime(); const now = new Date().toISOString(); // Database health check let dbStatus = 'ok'; let dbMsg = 'Connected'; try { await prisma.$queryRaw`SELECT 1`; } catch (e) { dbStatus = 'error'; dbMsg = 'Unreachable'; } const dbBadge = dbStatus === 'ok' ? `✓ ${dbMsg}` : `✗ ${dbMsg}`; const envBadge = isProd ? `production` : isTesting ? `testing` : `development`; const orgName = getSettingSync('org_name', process.env.ORG_NAME || 'Cross Code'); const html = pageShell(`${orgName} Events API — Status`, '#2563eb', `

${orgName} Events API

v${API_VERSION} — ${now}

Status
✓ Online
Environment
${envBadge}
Database
${dbBadge}
Uptime
${formatUptime(uptimeSec)}
Heap Used
${formatBytes(mem.heapUsed)}
Heap Total
${formatBytes(mem.heapTotal)}
RSS
${formatBytes(mem.rss)}
Node
${process.version}
API documentation (OpenAPI) is at /api/docs/v2 — it needs an admin account token.
`); res.send(html); }); // v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old // address) and links in messages already sent (308s above, a mail app's one-click POST here). // Mounted after everything else under /api, since v1Removed answers 410 for any other /api path. app.use('/api', legacyV1Router); app.use('/api', v1Removed); // Error middleware app.use(notFound); // Sentry captures the error here, then passes it through unchanged — errorHandler // below remains the sole source of what's actually sent back to the client. if (process.env.SENTRY_DSN) { const Sentry = require('@sentry/node'); Sentry.setupExpressErrorHandler(app); } app.use(errorHandler); // Start server app.listen(PORT, () => { console.log(`Server is running at http://localhost:${PORT}`); // Attempt a one-time background sync of attachment manifests into DB try { const { syncManifestsToDb } = require('./utils/attachmentsSync'); const prismaShared = require('./config/db'); setTimeout(async () => { try { const summary = await syncManifestsToDb(prismaShared, { dryRun: false }); if ((summary.imported || 0) > 0) { console.log(`[attachments sync] Imported ${summary.imported} attachments from manifests (skipped ${summary.skipped}).`); } else { console.log('[attachments sync] No attachments imported (either none found or already in DB).'); } } catch (e) { console.warn('[attachments sync] Failed:', e?.message || e); } }, 1000); } catch (e) { console.warn('[attachments sync] Not scheduled:', e?.message || e); } // Timed background jobs (daily summary, waitlist, feedback, sessions, consent, analytics, // backup, temp cleanup) run on the pg-boss job queue — see src/jobs/index.js. require('./jobs').startJobs().catch(e => console.warn('[jobs] Not started:', e?.message || e)); // Installs made from the Hub register by themselves (HUB_LICENCE_KEY), then check in with the // Hub 30 s after starting, so the licence is fresh without waiting 15 minutes. require('./hub/client').connectFromEnv().catch(() => {}); require('./hub/client').heartbeatSoon(); // Scheduled emails worker (polling) try { const enabled = String(process.env.SCHEDULED_EMAILS_ENABLED || 'true').toLowerCase() !== 'false'; if (enabled) { const { getDueJobs, updateJob, purgeSentJobs } = require('./utils/scheduledEmails'); const { emailEventAttendees, whatsappEventAttendees } = require('./controllers/eventController'); const { sendBroadcast } = require('./controllers/broadcastController'); const { sendWhatsAppBroadcast } = require('./controllers/whatsappBroadcastController'); const intervalMs = parseInt(process.env.SCHEDULED_EMAILS_INTERVAL_MS || '30000', 10); setInterval(async () => { try { try { purgeSentJobs(24 * 60 * 60 * 1000); } catch (e) { console.warn('[scheduled emails] purge failed:', e?.message || e); } const due = getDueJobs(new Date()); if (!due || due.length === 0) return; for (const job of due) { try { updateJob(job.id, { status: 'sending', attempts: (job.attempts || 0) + 1, lastError: null }); let responseBody = null; let code = 200; const mockRes = { status: (c) => { code = c; return mockRes; }, json: (b) => { responseBody = b; return mockRes; } }; if (job.broadcast && job.channel === 'whatsapp') { const mockReq = { body: job.payload }; await sendWhatsAppBroadcast(mockReq, mockRes); } else if (job.broadcast) { const mockReq = { body: job.payload }; await sendBroadcast(mockReq, mockRes); } else if (job.channel === 'whatsapp') { const mockReq = { params: { id: job.eventId }, body: job.payload }; await whatsappEventAttendees(mockReq, mockRes); } else { const mockReq = { params: { id: job.eventId }, body: job.payload }; await emailEventAttendees(mockReq, mockRes); } if (code >= 200 && code < 300) { updateJob(job.id, { status: 'sent', sentAt: new Date().toISOString(), lastResult: responseBody || null }); } else { updateJob(job.id, { status: 'error', lastError: (responseBody && responseBody.message) ? responseBody.message : `HTTP ${code}` }); } } catch (e) { updateJob(job.id, { status: 'error', lastError: String(e?.message || e) }); } } } catch (e) { console.warn('[scheduled emails] poll failed:', e?.message || e); } }, isNaN(intervalMs) ? 30000 : intervalMs); console.log('[scheduled emails] Worker initialized. Set SCHEDULED_EMAILS_ENABLED=false to disable.'); } else { console.log('[scheduled emails] Worker disabled by env SCHEDULED_EMAILS_ENABLED=false'); } } catch (e) { console.warn('[scheduled emails] Worker not started:', e?.message || e); } }); // Log unhandled promise rejections without killing the server, since a single // missed .catch() on fire-and-forget notification code (email/WhatsApp sends) // would otherwise take the whole app down. // On restart/stop (PM2 sends SIGINT), let a running background job finish first. for (const signal of ['SIGINT', 'SIGTERM']) { process.once(signal, async () => { try { await require('./jobs').stopJobs(); } catch { /* exiting anyway */ } process.exit(0); }); } process.on('unhandledRejection', (err) => { console.error('UNHANDLED REJECTION!', err?.name, err?.message); console.error(err?.stack || err); if (process.env.SENTRY_DSN) { try { require('@sentry/node').captureException(err); } catch {} } }); module.exports = { app, prisma };