import express from 'express'; import cors from 'cors'; import cookieParser from 'cookie-parser'; import dotenv from 'dotenv'; import { initializeDatabase } from './db'; import { requireApiToken } from './middleware/auth'; import { deviceIdMiddleware } from './middleware/device'; import authRoutes from './routes/authRoutes'; import listRoutes from './routes/listRoutes'; import fieldRoutes from './routes/fieldRoutes'; import itemRoutes from './routes/itemRoutes'; import syncRoutes from './routes/syncRoutes'; import webRoutes from './routes/webRoutes'; import notificationRoutes from './routes/notificationRoutes'; import { startNotificationCleanup } from './notifications'; dotenv.config(); const app = express(); const PORT = process.env.PORT || 3000; const DB_INIT_RETRY_INTERVAL_MS = Math.max(250, Number(process.env.DB_INIT_RETRY_INTERVAL_MS || 5000)); const DB_INIT_RETRY_MAX_ATTEMPTS = Math.max(0, Number(process.env.DB_INIT_RETRY_MAX_ATTEMPTS || 0)); function sleep(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)); } async function initializeDatabaseWithRetry() { let attempt = 0; for (;;) { attempt += 1; try { await initializeDatabase(); if (attempt > 1) { console.log(`[DB] Connected after ${attempt} attempt(s)`); } return; } catch (error) { const reachedLimit = DB_INIT_RETRY_MAX_ATTEMPTS > 0 && attempt >= DB_INIT_RETRY_MAX_ATTEMPTS; console.error(`[DB] Initialization attempt ${attempt} failed`, error); if (reachedLimit) { throw error; } console.log(`[DB] Retrying in ${DB_INIT_RETRY_INTERVAL_MS}ms...`); await sleep(DB_INIT_RETRY_INTERVAL_MS); } } } // Middleware app.use(cors({ credentials: true, origin: true })); app.use(express.json()); app.use(cookieParser()); // Health check (no auth required) app.get('/health', (req, res) => { res.json({ status: 'ok', timestamp: Date.now() }); }); // Auth bootstrap routes (status/setup/login/logout/credentials/token) - must stay // reachable without a token or session, mounted before the API-token gate below. app.use('/api', authRoutes); // Sync/collaboration API: gated by a long-lived API token shared by every collaborating // device (see middleware/auth.ts) - this replaces the old optional SERVER_PASSWORD scheme, // which silently disabled auth entirely when unset. app.use('/api', requireApiToken); // Attach device id for downstream routes app.use('/api', deviceIdMiddleware); // Routes (protected by the API token above) app.use('/api/lists', listRoutes); app.use('/api/fields', fieldRoutes); app.use('/api/items', itemRoutes); app.use('/api', syncRoutes); app.use('/api', notificationRoutes); // Web UI (static SPA shell is public; its /web/info and /web/data JSON endpoints require // the admin session - see webRoutes.ts. Mounted last to not interfere with API routes.) app.use('/', webRoutes); // Initialize database and start server (async () => { try { await initializeDatabaseWithRetry(); console.log('Database synchronized successfully'); console.log('Database models loaded:'); console.log('- Lists'); console.log('- Fields'); console.log('- Items'); console.log('- ItemValues'); // Start retention cleanup for notifications startNotificationCleanup(); // Start HTTP server (WebSocket removed) app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); console.log(`Environment: ${process.env.NODE_ENV || 'development'}`); console.log('Database: PostgreSQL (DATABASE_URL)'); }); } catch (error) { console.error('Database initialization error:', error); process.exit(1); } })(); export default app;