diff --git a/server/index.js b/server/index.js index fc819c0..243bca3 100644 --- a/server/index.js +++ b/server/index.js @@ -12,10 +12,10 @@ dotenv.config({ path: path.join(__dirname, '.env') }); const app = express(); const server = require('http').createServer(app); const io = require('socket.io')(server, { - cors: { - origin: "*", - methods: ["GET", "POST"] - } + cors: { + origin: '*', + methods: ['GET', 'POST'], + }, }); // Initialize Simulation Service @@ -23,61 +23,72 @@ const simulation = new SimulationService(io); simulation.start(); io.on('connection', (socket) => { - console.log('Client connected for IoT stream:', socket.id); + console.log('Client connected for IoT stream:', socket.id); }); // Middleware app.use(cors()); + +// Stripe Webhook Endpoint (requires raw unparsed Buffer before global express.json) +app.use('/api/webhooks', express.raw({ type: 'application/json' }), require('./routes/webhooks')); + app.use(express.json()); // Hybrid Connection Logic const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/traffitech'; -mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 4000 }) - .then(() => console.log('✅ Connected to MongoDB Atlas (Production Cloud DB)')) - .catch((err) => { - console.warn('⚠️ MongoDB Atlas connection error details:', err?.message || err); - console.warn('⚠️ Using Local JSON DB fallback.'); - if (process.env.NODE_ENV === 'production' || process.env.RENDER === 'true') { - console.warn('🚨 PRODUCTION PERSISTENCE WARNING: MONGODB_URI is not connected in production mode. Data written to JSON fallback DB will be ephemeral across server restarts on Render. Ensure MONGODB_URI is configured in Render environment variables for cloud persistence.'); - } else { - console.log('✅ Zero-Dependency Fallback Mode Active'); - } - }); +mongoose + .connect(MONGODB_URI, { serverSelectionTimeoutMS: 4000 }) + .then(() => console.log('✅ Connected to MongoDB Atlas (Production Cloud DB)')) + .catch((err) => { + console.warn('⚠️ MongoDB Atlas connection error details:', err?.message || err); + console.warn('⚠️ Using Local JSON DB fallback.'); + if (process.env.NODE_ENV === 'production' || process.env.RENDER === 'true') { + console.warn( + '🚨 PRODUCTION PERSISTENCE WARNING: MONGODB_URI is not connected in production mode. Data written to JSON fallback DB will be ephemeral across server restarts on Render. Ensure MONGODB_URI is configured in Render environment variables for cloud persistence.' + ); + } else { + console.log('✅ Zero-Dependency Fallback Mode Active'); + } + }); // Routes app.use('/api/auth', require('./routes/auth')); app.use('/api/bookings', require('./routes/bookings')); app.use('/api/payments', require('./routes/payments')); -app.use('/api/webhooks', require('./routes/webhooks')); app.use('/api/rapids-analytics', require('./routes/rapidsAnalytics')); // Basic Route app.get('/', (req, res) => { - res.json({ - message: 'TraffiTech API is running', - mode: mongoose.connection.readyState === 1 ? 'Production (Cloud DB)' : 'Development (Fallback JSON DB)' - }); + res.json({ + message: 'TraffiTech API is running', + mode: + mongoose.connection.readyState === 1 + ? 'Production (Cloud DB)' + : 'Development (Fallback JSON DB)', + }); }); // Port Configuration const PORT = process.env.PORT || 5000; server.listen(PORT, '0.0.0.0', () => { - console.log(`🚀 Server running on port ${PORT} (0.0.0.0 interface bound)`); + console.log(`🚀 Server running on port ${PORT} (0.0.0.0 interface bound)`); - // Environment Variables Audit Log on Boot - const isProdEnv = process.env.NODE_ENV === 'production' || process.env.RENDER === 'true'; - if (isProdEnv) { - const missingKeys = []; - if (!process.env.JWT_SECRET) missingKeys.push('JWT_SECRET'); - if (!process.env.ADMIN_SECRET_KEY) missingKeys.push('ADMIN_SECRET_KEY'); - if (!process.env.STRIPE_SECRET_KEY) missingKeys.push('STRIPE_SECRET_KEY'); - if (!process.env.STRIPE_WEBHOOK_SECRET) missingKeys.push('STRIPE_WEBHOOK_SECRET'); - if (!process.env.MONGODB_URI) missingKeys.push('MONGODB_URI'); + // Environment Variables Audit Log on Boot + const isProdEnv = process.env.NODE_ENV === 'production' || process.env.RENDER === 'true'; + if (isProdEnv) { + const missingKeys = []; + if (!process.env.JWT_SECRET) missingKeys.push('JWT_SECRET'); + if (!process.env.ADMIN_SECRET_KEY) missingKeys.push('ADMIN_SECRET_KEY'); + if (!process.env.STRIPE_SECRET_KEY) missingKeys.push('STRIPE_SECRET_KEY'); + if (!process.env.STRIPE_WEBHOOK_SECRET) missingKeys.push('STRIPE_WEBHOOK_SECRET'); + if (!process.env.MONGODB_URI) missingKeys.push('MONGODB_URI'); - if (missingKeys.length > 0) { - console.warn(`⚠️ PRODUCTION ENV CONFIG NOTICE: Missing Render environment variables: ${missingKeys.join(', ')}`); - } else { - console.log('✅ Production Environment Audit Passed: All production secrets configured.'); - } + if (missingKeys.length > 0) { + console.warn( + `⚠️ PRODUCTION ENV CONFIG NOTICE: Missing Render environment variables: ${missingKeys.join(', ')}` + ); + } else { + console.log('✅ Production Environment Audit Passed: All production secrets configured.'); } + } }); diff --git a/server/routes/payments.js b/server/routes/payments.js index 97902cd..f39cf68 100644 --- a/server/routes/payments.js +++ b/server/routes/payments.js @@ -5,54 +5,64 @@ const Booking = require('../models/Booking'); const router = express.Router(); const toPlain = (doc) => { - if (!doc) return null; - if (doc.data) return doc.data; - if (typeof doc.toObject === 'function') return doc.toObject(); - return doc; + if (!doc) return null; + if (doc.data) return doc.data; + if (typeof doc.toObject === 'function') return doc.toObject(); + return doc; }; // Create Payment Intent router.post('/create-payment-intent', auth, async (req, res) => { - try { - const { bookingId, currency = 'inr' } = req.body; - - if (!bookingId) { - return res.status(400).json({ message: 'Booking ID is required' }); - } - - // Fetch booking from database to get verified server-computed price - const booking = await Booking.findById(bookingId); - if (!booking) { - return res.status(404).json({ message: 'Booking not found' }); - } - - const plain = toPlain(booking); - // Ensure user owns the booking - const userId = String(plain.user || ''); - if (userId !== String(req.user.id)) { - return res.status(403).json({ message: 'Unauthorized access to this booking' }); - } - - const totalPrice = plain.totalPrice || 50; - - const paymentIntent = await stripe.paymentIntents.create({ - amount: Math.round(Number(totalPrice) * 100), // Secure verified amount - currency, - automatic_payment_methods: { - enabled: true, - }, - metadata: { - bookingId: String(plain._id || bookingId) // Inject metadata for Webhooks - } - }); - - res.json({ - clientSecret: paymentIntent.client_secret, - }); - } catch (err) { - console.error("Stripe Backend Error:", err); - res.status(500).json({ message: err.message || 'Failed to create Stripe PaymentIntent', error: err.stack }); + try { + const { bookingId, currency = 'inr' } = req.body; + + if (!bookingId) { + return res.status(400).json({ message: 'Booking ID is required' }); + } + + // Fetch booking from database to get verified server-computed price + const booking = await Booking.findById(bookingId); + if (!booking) { + return res.status(404).json({ message: 'Booking not found' }); + } + + const plain = toPlain(booking); + // Ensure user owns the booking + const userId = String(plain.user || ''); + if (userId !== String(req.user.id)) { + return res.status(403).json({ message: 'Unauthorized access to this booking' }); + } + + // Prevent charging already paid bookings + if (plain.paymentStatus === 'paid' || plain.paymentStatus === 'completed') { + return res.status(400).json({ message: 'Booking is already paid' }); + } + + // Prevent charging cancelled or refunded bookings + if (plain.paymentStatus === 'cancelled' || plain.paymentStatus === 'refunded') { + return res.status(400).json({ message: 'Booking is cancelled' }); } + + const totalPrice = plain.totalPrice || 50; + + const paymentIntent = await stripe.paymentIntents.create({ + amount: Math.round(Number(totalPrice) * 100), // Secure verified amount + currency, + automatic_payment_methods: { + enabled: true, + }, + metadata: { + bookingId: String(plain._id || bookingId), // Inject metadata for Webhooks + }, + }); + + res.json({ + clientSecret: paymentIntent.client_secret, + }); + } catch (err) { + console.error('Stripe Backend Error:', err); + res.status(500).json({ message: err.message || 'Failed to create Stripe PaymentIntent' }); + } }); module.exports = router; diff --git a/server/tests/paymentsAndWebhooks.test.js b/server/tests/paymentsAndWebhooks.test.js new file mode 100644 index 0000000..3e6ffb2 --- /dev/null +++ b/server/tests/paymentsAndWebhooks.test.js @@ -0,0 +1,299 @@ +/* global jest */ +const request = require('supertest'); +const express = require('express'); +const jwt = require('jsonwebtoken'); + +// Mock Stripe before requiring routes +const mockPaymentIntentsCreate = jest.fn(); +const mockConstructEvent = jest.fn(); + +jest.mock('stripe', () => { + return jest.fn().mockImplementation(() => ({ + paymentIntents: { + create: mockPaymentIntentsCreate, + }, + webhooks: { + constructEvent: mockConstructEvent, + }, + })); +}); + +const Booking = require('../models/Booking'); +const { getJwtSecret } = require('../config/jwt'); +const paymentsRouter = require('../routes/payments'); +const webhooksRouter = require('../routes/webhooks'); + +describe('Payments & Webhooks Routes', () => { + let app; + let validToken; + const testUserId = 'user_test_123'; + const otherUserId = 'user_other_456'; + + beforeAll(() => { + validToken = jwt.sign({ id: testUserId, role: 'user' }, getJwtSecret(), { expiresIn: '1h' }); + + app = express(); + // Mirror server/index.js: Mount webhooks with raw parsing before express.json() + app.use('/api/webhooks', express.raw({ type: 'application/json' }), webhooksRouter); + app.use(express.json()); + app.use('/api/payments', paymentsRouter); + }); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('POST /api/payments/create-payment-intent', () => { + it('should return 401 if unauthenticated (no x-auth-token)', async () => { + const res = await request(app) + .post('/api/payments/create-payment-intent') + .send({ bookingId: 'bk_1' }); + + expect(res.status).toBe(401); + expect(res.body.message).toMatch(/No token/); + }); + + it('should return 400 if bookingId is missing', async () => { + const res = await request(app) + .post('/api/payments/create-payment-intent') + .set('x-auth-token', validToken) + .send({}); + + expect(res.status).toBe(400); + expect(res.body.message).toBe('Booking ID is required'); + }); + + it('should return 404 if booking is not found', async () => { + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(null); + + const res = await request(app) + .post('/api/payments/create-payment-intent') + .set('x-auth-token', validToken) + .send({ bookingId: 'nonexistent_id' }); + + expect(res.status).toBe(404); + expect(res.body.message).toBe('Booking not found'); + }); + + it('should return 403 if user does not own the booking', async () => { + const mockBooking = { + _id: 'bk_1', + user: otherUserId, + totalPrice: 100, + paymentStatus: 'pending', + }; + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(mockBooking); + + const res = await request(app) + .post('/api/payments/create-payment-intent') + .set('x-auth-token', validToken) + .send({ bookingId: 'bk_1' }); + + expect(res.status).toBe(403); + expect(res.body.message).toBe('Unauthorized access to this booking'); + }); + + it('should return 400 if booking is already paid', async () => { + const mockBooking = { + _id: 'bk_1', + user: testUserId, + totalPrice: 100, + paymentStatus: 'paid', + }; + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(mockBooking); + + const res = await request(app) + .post('/api/payments/create-payment-intent') + .set('x-auth-token', validToken) + .send({ bookingId: 'bk_1' }); + + expect(res.status).toBe(400); + expect(res.body.message).toBe('Booking is already paid'); + expect(mockPaymentIntentsCreate).not.toHaveBeenCalled(); + }); + + it('should return 400 if booking is marked completed', async () => { + const mockBooking = { + _id: 'bk_1', + user: testUserId, + totalPrice: 100, + paymentStatus: 'completed', + }; + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(mockBooking); + + const res = await request(app) + .post('/api/payments/create-payment-intent') + .set('x-auth-token', validToken) + .send({ bookingId: 'bk_1' }); + + expect(res.status).toBe(400); + expect(res.body.message).toBe('Booking is already paid'); + expect(mockPaymentIntentsCreate).not.toHaveBeenCalled(); + }); + + it('should return 400 if booking is cancelled', async () => { + const mockBooking = { + _id: 'bk_1', + user: testUserId, + totalPrice: 100, + paymentStatus: 'cancelled', + }; + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(mockBooking); + + const res = await request(app) + .post('/api/payments/create-payment-intent') + .set('x-auth-token', validToken) + .send({ bookingId: 'bk_1' }); + + expect(res.status).toBe(400); + expect(res.body.message).toBe('Booking is cancelled'); + expect(mockPaymentIntentsCreate).not.toHaveBeenCalled(); + }); + + it('should return 400 if booking is refunded', async () => { + const mockBooking = { + _id: 'bk_1', + user: testUserId, + totalPrice: 100, + paymentStatus: 'refunded', + }; + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(mockBooking); + + const res = await request(app) + .post('/api/payments/create-payment-intent') + .set('x-auth-token', validToken) + .send({ bookingId: 'bk_1' }); + + expect(res.status).toBe(400); + expect(res.body.message).toBe('Booking is cancelled'); + expect(mockPaymentIntentsCreate).not.toHaveBeenCalled(); + }); + + it('should create PaymentIntent and return 200 with clientSecret for valid pending booking', async () => { + const mockBooking = { + _id: 'bk_1', + user: testUserId, + totalPrice: 75, + paymentStatus: 'pending', + }; + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(mockBooking); + mockPaymentIntentsCreate.mockResolvedValueOnce({ + client_secret: 'pi_test_secret_123', + }); + + const res = await request(app) + .post('/api/payments/create-payment-intent') + .set('x-auth-token', validToken) + .send({ bookingId: 'bk_1', currency: 'inr' }); + + expect(res.status).toBe(200); + expect(res.body.clientSecret).toBe('pi_test_secret_123'); + expect(mockPaymentIntentsCreate).toHaveBeenCalledWith({ + amount: 7500, + currency: 'inr', + automatic_payment_methods: { enabled: true }, + metadata: { bookingId: 'bk_1' }, + }); + }); + + it('should not leak err.stack in 500 error responses', async () => { + const mockBooking = { + _id: 'bk_1', + user: testUserId, + totalPrice: 50, + paymentStatus: 'pending', + }; + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(mockBooking); + mockPaymentIntentsCreate.mockRejectedValueOnce(new Error('Stripe API unavailable')); + + const res = await request(app) + .post('/api/payments/create-payment-intent') + .set('x-auth-token', validToken) + .send({ bookingId: 'bk_1' }); + + expect(res.status).toBe(500); + expect(res.body.message).toBe('Stripe API unavailable'); + expect(res.body.error).toBeUndefined(); + }); + }); + + describe('POST /api/webhooks', () => { + it('should return 400 if Stripe signature verification fails', async () => { + mockConstructEvent.mockImplementationOnce(() => { + throw new Error('Invalid signature'); + }); + + const res = await request(app) + .post('/api/webhooks') + .set('stripe-signature', 'invalid_sig') + .set('Content-Type', 'application/json') + .send(JSON.stringify({ id: 'evt_1' })); + + expect(res.status).toBe(400); + expect(res.text).toContain('Webhook Error: Invalid signature'); + }); + + it('should receive raw Buffer and update booking to paid on payment_intent.succeeded', async () => { + const rawEvent = { + type: 'payment_intent.succeeded', + data: { + object: { + id: 'pi_success_999', + amount: 7500, + metadata: { bookingId: 'bk_100' }, + }, + }, + }; + + mockConstructEvent.mockImplementationOnce((rawBody) => { + expect(Buffer.isBuffer(rawBody)).toBe(true); + return rawEvent; + }); + + const mockSave = jest.fn().mockResolvedValue(true); + const mockBookingInstance = { + paymentStatus: 'pending', + paymentId: null, + save: mockSave, + }; + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(mockBookingInstance); + + const res = await request(app) + .post('/api/webhooks') + .set('stripe-signature', 'valid_test_sig') + .set('Content-Type', 'application/json') + .send(JSON.stringify(rawEvent)); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ received: true }); + expect(mockBookingInstance.paymentStatus).toBe('paid'); + expect(mockBookingInstance.paymentId).toBe('pi_success_999'); + expect(mockSave).toHaveBeenCalled(); + }); + + it('should handle webhook event gracefully if booking is not found', async () => { + const rawEvent = { + type: 'payment_intent.succeeded', + data: { + object: { + id: 'pi_success_888', + amount: 5000, + metadata: { bookingId: 'bk_nonexistent' }, + }, + }, + }; + + mockConstructEvent.mockReturnValueOnce(rawEvent); + jest.spyOn(Booking, 'findById').mockResolvedValueOnce(null); + + const res = await request(app) + .post('/api/webhooks') + .set('stripe-signature', 'valid_test_sig') + .set('Content-Type', 'application/json') + .send(JSON.stringify(rawEvent)); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ received: true }); + }); + }); +}); diff --git a/vite.config.js b/vite.config.js index 43fd531..01b646f 100644 --- a/vite.config.js +++ b/vite.config.js @@ -25,6 +25,7 @@ export default defineConfig({ environment: 'jsdom', setupFiles: ['./src/__tests__/setup.js'], css: true, + include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], coverage: { provider: 'v8', reporter: ['text', 'json', 'html'], @@ -32,4 +33,3 @@ export default defineConfig({ }, }, }); -