const express = require('express'); const rateLimit = require('express-rate-limit'); const fs = require('fs'); const app = express(); app.set('trust proxy', true); const PORT = process.env.PORT || 3000; // Load reasons from JSON const reasons = JSON.parse(fs.readFileSync('./reasons.json', 'utf-8')); // Load OpenAPI schema const openapiSchema = JSON.parse(fs.readFileSync('./openapi.json', 'utf-8')); // Rate limiter: 120 requests per minute per IP const limiter = rateLimit({ windowMs: 60 * 1000, // 1 minute max: 120, keyGenerator: (req, res) => { return req.headers['cf-connecting-ip'] || req.ip; // Fallback if header missing (or for non-CF) }, message: { error: "Too many requests, please try again later. (120 reqs/min/IP)" } }); app.use(limiter); // Serve OpenAPI schema app.get('/openapi.json', (req, res) => { const ip = req.headers['x-forwarded-for'] || req.ip; const timestamp = new Date().toISOString(); console.log(`[${timestamp}] OpenAPI schema request from IP: ${ip}`); res.json(openapiSchema); }); // Random rejection reason endpoint app.get('/', (req, res) => { const ip = req.headers['x-forwarded-for'] || req.ip; const timestamp = new Date().toISOString(); console.log(`[${timestamp}] Request from IP: ${ip}`); const reason = reasons[Math.floor(Math.random() * reasons.length)]; res.json({ reason }); }); app.get('/health', (req, res) => { const ip = req.headers['x-forwarded-for'] || req.ip; const timestamp = new Date().toISOString(); console.log(`[${timestamp}] Request from IP: ${ip}`); res.json({"status": "ok"}); }); // Start server only if this file is run directly if (require.main === module) { app.listen(PORT, () => { console.log(`No-as-a-Service is running on port ${PORT}`); }); } module.exports = app;