- Hub client: register and heartbeat on protocol v2 with the site's Ed25519 key (sent on the heartbeat until the Hub has it); falls back to v1 for a day if the Hub refuses v2, so the licence always refreshes. - crosscode.link/1 Connect / Disconnect, both directions, trusted through the Hub's cached linkedProducts (ProductLink, LinkNonce). - GET /api/feed/v1/events from FeedEntry (go-live, closing and selling out are changes; deactivated events go in deleted), event.changed to connected products, and showing their events (ImportedEvent). - /api/v2/linked-products, /api/v2/linked-events; /events/:id/full gains crosscodeEvent and priceRangeCents for the JSON-LD. - Contracts: FEED_PATHS, typesVersions for @crosscode/contracts/signing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
483 lines
21 KiB
JavaScript
483 lines
21 KiB
JavaScript
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());
|
|
|
|
// 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 <script>/event
|
|
// handlers. Serving them inline lets a compromised/malicious upload run script
|
|
// in the site's origin if opened directly, so pin the safe response headers
|
|
// (no inline execution, no MIME-sniffing to HTML/script) on every asset here.
|
|
// 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 = express.static('public/uploads', {
|
|
setHeaders: (res) => {
|
|
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
},
|
|
});
|
|
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 `<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>${title}</title>
|
|
<style>
|
|
*{box-sizing:border-box;margin:0;padding:0}
|
|
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#f3f4f6;color:#1f2937;min-height:100vh;padding:24px 16px}
|
|
.wrap{max-width:960px;margin:0 auto}
|
|
h1{font-size:1.5rem;font-weight:700;color:#111827;margin-bottom:4px}
|
|
h2{font-size:1.1rem;font-weight:600;color:#111827;margin:24px 0 10px}
|
|
.subtitle{font-size:.85rem;color:#6b7280;margin-bottom:24px}
|
|
.card{background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:20px;margin-bottom:16px}
|
|
.stat-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin-bottom:16px}
|
|
.stat{background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:14px 16px}
|
|
.stat-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;color:#6b7280;margin-bottom:4px}
|
|
.stat-value{font-size:1.1rem;font-weight:600;color:#111827}
|
|
.badge{display:inline-block;padding:2px 8px;border-radius:999px;font-size:.75rem;font-weight:600}
|
|
.badge-ok{background:#d1fae5;color:#065f46}
|
|
.badge-warn{background:#fef3c7;color:#92400e}
|
|
.badge-err{background:#fee2e2;color:#991b1b}
|
|
table{width:100%;border-collapse:collapse;font-size:.82rem}
|
|
th{text-align:left;padding:6px 10px;background:#f9fafb;border-bottom:1px solid #e5e7eb;font-weight:600;color:#374151}
|
|
td{padding:6px 10px;border-bottom:1px solid #f3f4f6;color:#374151;vertical-align:top}
|
|
tr:last-child td{border-bottom:none}
|
|
.method{display:inline-block;padding:1px 7px;border-radius:4px;font-size:.7rem;font-weight:700;font-family:monospace}
|
|
.get{background:#dbeafe;color:#1e40af}
|
|
.post{background:#d1fae5;color:#065f46}
|
|
.put{background:#fef3c7;color:#92400e}
|
|
.patch{background:#ede9fe;color:#5b21b6}
|
|
.del{background:#fee2e2;color:#991b1b}
|
|
.auth-badge{font-size:.68rem;padding:1px 6px;border-radius:4px;background:#f3f4f6;color:#374151;font-family:monospace}
|
|
code{background:#f3f4f6;padding:1px 5px;border-radius:4px;font-family:monospace;font-size:.82rem}
|
|
.note{background:#eff6ff;border:1px solid #bfdbfe;border-radius:8px;padding:12px 16px;font-size:.82rem;color:#1e40af;margin-bottom:16px}
|
|
.accent{color:${accentColor}}
|
|
a{color:${accentColor};text-decoration:none}
|
|
a:hover{text-decoration:underline}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="wrap">
|
|
${bodyHtml}
|
|
</div>
|
|
</body>
|
|
</html>`;
|
|
}
|
|
|
|
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'
|
|
? `<span class="badge badge-ok">✓ ${dbMsg}</span>`
|
|
: `<span class="badge badge-err">✗ ${dbMsg}</span>`;
|
|
|
|
const envBadge = isProd
|
|
? `<span class="badge badge-ok">production</span>`
|
|
: isTesting
|
|
? `<span class="badge badge-warn">testing</span>`
|
|
: `<span class="badge badge-warn">development</span>`;
|
|
|
|
const orgName = getSettingSync('org_name', process.env.ORG_NAME || 'Cross Code');
|
|
const html = pageShell(`${orgName} Events API — Status`, '#2563eb', `
|
|
<h1>${orgName} Events API</h1>
|
|
<p class="subtitle">v${API_VERSION} — ${now}</p>
|
|
|
|
<div class="stat-grid">
|
|
<div class="stat">
|
|
<div class="stat-label">Status</div>
|
|
<div class="stat-value"><span class="badge badge-ok">✓ Online</span></div>
|
|
</div>
|
|
<div class="stat">
|
|
<div class="stat-label">Environment</div>
|
|
<div class="stat-value">${envBadge}</div>
|
|
</div>
|
|
<div class="stat">
|
|
<div class="stat-label">Database</div>
|
|
<div class="stat-value">${dbBadge}</div>
|
|
</div>
|
|
<div class="stat">
|
|
<div class="stat-label">Uptime</div>
|
|
<div class="stat-value">${formatUptime(uptimeSec)}</div>
|
|
</div>
|
|
<div class="stat">
|
|
<div class="stat-label">Heap Used</div>
|
|
<div class="stat-value">${formatBytes(mem.heapUsed)}</div>
|
|
</div>
|
|
<div class="stat">
|
|
<div class="stat-label">Heap Total</div>
|
|
<div class="stat-value">${formatBytes(mem.heapTotal)}</div>
|
|
</div>
|
|
<div class="stat">
|
|
<div class="stat-label">RSS</div>
|
|
<div class="stat-value">${formatBytes(mem.rss)}</div>
|
|
</div>
|
|
<div class="stat">
|
|
<div class="stat-label">Node</div>
|
|
<div class="stat-value">${process.version}</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="note">
|
|
API documentation (OpenAPI) is at <a href="/api/docs/v2">/api/docs/v2</a> — it needs an admin account token.
|
|
</div>
|
|
`);
|
|
|
|
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 }; |