Files
no-as-a-service/index.js
Rene Luria 271eb107a2 feat: add OpenAPI documentation and comprehensive test suite
- Add OpenAPI schema endpoint at /openapi.json with proper logging
- Make server exportable for testing by wrapping app.listen in module check
- Add Jest test suite covering all API endpoints
- Improve request logging with IP addresses and timestamps
- Add development dependencies for testing (jest, supertest)
2025-09-02 12:26:30 +02:00

59 lines
1.8 KiB
JavaScript

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;