File size: 8,942 Bytes
f4656a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c54363c
 
f4656a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bca05f4
f4656a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
'use strict';

require('dotenv').config();

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const compression = require('compression');
const cron = require('node-cron');
const cookieParser = require('cookie-parser');

const { initDatabase } = require('./config/database');
const SessionModel = require('./models/session.model');
const WebhookController = require('./controllers/webhook.controller');
const SessionController = require('./controllers/session.controller');
const { apiKeyAuth, verifyTwilioSignature, verifyMetaSignature, requireAuth } = require('./middleware/auth');
const AuthController = require('./controllers/auth.controller');
const { generalLimiter, webhookLimiter } = require('./middleware/rateLimiter');
const { validate, schemas } = require('./middleware/validation');
// Passport must be required after dotenv so GOOGLE_* env vars are available
const passport = require('./config/passport');
// eslint-disable-next-line no-unused-vars
const logger = require('./utils/logger');

const app = express();
const PORT = process.env.PORT || 3000;

// ─────────────────────────────────────────────
//  Security & Middleware
// ─────────────────────────────────────────────

app.set('trust proxy', 1);

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc:    ["'self'"],
      scriptSrc:     ["'self'", "'unsafe-inline'", 'https://www.gstatic.com', 'https://apis.google.com'],
      scriptSrcElem: ["'self'", "'unsafe-inline'", 'https://www.gstatic.com', 'https://apis.google.com'],
      styleSrc:      ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
      fontSrc:       ["'self'", 'https://fonts.gstatic.com'],
      imgSrc:        ["'self'", 'data:', 'https:'],
      connectSrc:    ["'self'"],
      frameSrc:      ['https://accounts.google.com'],
    },
  },
}));

const allowedOrigins = (process.env.ALLOWED_ORIGINS || 'http://localhost:3000,http://localhost:3001,https://oxinto.vercel.app').split(',').map(o => o.trim());
app.use(cors({
  origin: (origin, callback) => {
    if (!origin || allowedOrigins.includes(origin) || process.env.NODE_ENV === 'development') {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true,
}));

app.use(compression());
app.use(cookieParser());
app.use(morgan('combined', { stream: { write: (msg) => logger.info(msg.trim()) } }));
// Initialize Passport (no session middleware β€” stateless JWT only)
app.use(passport.initialize());

// Capture raw body ONLY for signature-verified channels (WhatsApp, Instagram).
// The web chat route does NOT need this β€” it uses standard express.json() parsing.
app.use((req, res, next) => {
  if (req.path === '/api/webhook/whatsapp' || req.path === '/api/webhook/instagram') {
    let data = '';
    req.on('data', (chunk) => { data += chunk; });
    req.on('end', () => {
      req.rawBody = data;
      try { req.body = JSON.parse(data); } catch { /* urlencoded or empty body β€” ok */ }
      next();
    });
  } else {
    next();
  }
});

app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: true, limit: '1mb' }));

// Apply general rate limiting
app.use('/api/', generalLimiter);

// ─────────────────────────────────────────────
//  Routes
// ─────────────────────────────────────────────

// ── Google OAuth routes (Passport redirect flow, no session) ─────────────────
app.get('/auth/google',          AuthController.redirectToGoogle);
app.get('/auth/google/callback',
  passport.authenticate('google', { session: false, failWithError: true }),
  AuthController.handleGoogleCallback
);

// ── Auth routes ──────────────────────────────────────────
app.post('/api/auth/send-otp',         validate(schemas.sendOtp),        AuthController.sendOtp);
app.post('/api/auth/verify-otp',       validate(schemas.verifyOtp),      AuthController.verifyOtp);
app.post('/api/auth/resend-otp',       validate(schemas.resendOtp),      AuthController.resendOtp);
app.post('/api/auth/login',            validate(schemas.login),          AuthController.login);
app.post('/api/auth/logout',           requireAuth,                      AuthController.logout);
app.get('/api/auth/me',                requireAuth,                      AuthController.me);
app.post('/api/auth/forgot-password',  validate(schemas.forgotPassword), AuthController.forgotPassword);
app.post('/api/auth/reset-password',   validate(schemas.resetPassword),  AuthController.resetPassword);

// Health check (no auth required)
app.get('/api/health', SessionController.healthCheck);

// WhatsApp Webhook (Twilio signature verification)
app.post(
  '/api/webhook/whatsapp',
  webhookLimiter,
  verifyTwilioSignature,
  WebhookController.handleWhatsApp
);

// Instagram Webhook (Meta verification + signature)
app.get('/api/webhook/instagram', WebhookController.verifyInstagram);
app.post(
  '/api/webhook/instagram',
  webhookLimiter,
  verifyMetaSignature,
  WebhookController.handleInstagram
);

// Web Chat (no external auth needed β€” rate limited)
app.post(
  '/api/webhook/web',
  validate(schemas.webMessage),
  WebhookController.handleWeb
);

// Session endpoints (require API key)
app.get('/api/session/:id', apiKeyAuth, validate(schemas.sessionId), SessionController.getSession);
app.post('/api/session/reset/:id', apiKeyAuth, validate(schemas.sessionId), SessionController.resetSession);

// Product catalog (public read)
app.get('/api/products', validate(schemas.productFilter), SessionController.getProducts);

// Unknown API routes β€” return 404 JSON. UI routing is handled by Next.js frontend.
app.use((req, res) => {
  res.status(404).json({ error: 'Not found' });
});

// ─────────────────────────────────────────────
//  Global Error Handler
// ─────────────────────────────────────────────

app.use((err, req, res, next) => {
  logger.error('Unhandled error:', err);
  const status = err.status || 500;
  res.status(status).json({
    error: status === 500 ? 'Internal server error' : err.message,
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
  });
});

// ─────────────────────────────────────────────
//  Cron: Session Cleanup
// ─────────────────────────────────────────────

function startCleanupJob() {
  const interval = parseInt(process.env.SESSION_CLEANUP_INTERVAL_MINUTES || '10');
  cron.schedule(`*/${interval} * * * *`, async () => {
    try {
      const deleted = await SessionModel.deleteExpired();
      if (deleted > 0) logger.info(`Session cleanup: removed ${deleted} expired sessions`);
    } catch (err) {
      logger.error('Session cleanup error:', err);
    }
  });
  logger.info(`Session cleanup job scheduled every ${interval} minutes`);
}

// ─────────────────────────────────────────────
//  Startup
// ─────────────────────────────────────────────

async function start() {
  try {
    await initDatabase();
    logger.info('Database initialized');

    startCleanupJob();

    const server = app.listen(PORT, () => {
      logger.info(`Smart AI Recommendation System running on port ${PORT}`);
      logger.info(`Environment: ${process.env.NODE_ENV || 'development'}`);
      logger.info(`DB type: ${process.env.DB_TYPE || 'sqlite'}`);
    });

    // Graceful shutdown
    const shutdown = (signal) => {
      logger.info(`Received ${signal}, shutting down gracefully...`);
      server.close(() => {
        logger.info('Server closed');
        process.exit(0);
      });
    };

    process.on('SIGTERM', () => shutdown('SIGTERM'));
    process.on('SIGINT', () => shutdown('SIGINT'));

  } catch (err) {
    logger.error('Failed to start server:', err);
    process.exit(1);
  }
}

// Only auto-start when run directly; tests import and call start() themselves
if (require.main === module) {
  start();
}

module.exports = app;
module.exports.start = start;