import fs from 'fs';
import path from 'path';
import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import rateLimit from 'express-rate-limit';
import historyApiFallback from 'connect-history-api-fallback';
// Load environment variables from .env file
dotenv.config();
// Create the Express app
const app = express();
const __filename = new URL(import.meta.url).pathname;
const __dirname = path.dirname(__filename);
const port = process.env.PORT || 3000; // The port to run the server on
const API_DIR = '/api'; // Name of the dir containing the lambda functions
const dirPath = path.join(__dirname, API_DIR); // Path to the lambda functions dir
const guiPath = path.join(__dirname, 'dist', 'client');
const placeholderFilePath = path.join(__dirname, 'public', 'placeholder.html');
const handlers = {}; // Will store list of API endpoints
process.env.WC_SERVER = 'true'; // Tells middleware to return in non-lambda mode
// Enable CORS
app.use(cors({
origin: process.env.API_CORS_ORIGIN || '*',
}));
// Define max requests within each time frame
const limits = [
{ timeFrame: 10 * 60, max: 100, messageTime: '10 minutes' },
{ timeFrame: 60 * 60, max: 250, messageTime: '1 hour' },
{ timeFrame: 12 * 60 * 60, max: 500, messageTime: '12 hours' },
];
// Construct a message to be returned if the user has been rate-limited
const makeLimiterResponseMsg = (retryAfter) => {
const why = 'This keeps the service running smoothly for everyone. '
+ 'You can get around these limits by running your own instance of Web Check.';
return `You've been rate-limited, please try again in ${retryAfter} seconds.\n${why}`;
};
// Create rate limiters for each time frame
const limiters = limits.map(limit => rateLimit({
windowMs: limit.timeFrame * 1000,
max: limit.max,
standardHeaders: true,
legacyHeaders: false,
message: { error: makeLimiterResponseMsg(limit.messageTime) }
}));
// If rate-limiting enabled, then apply the limiters to the /api endpoint
if (process.env.API_ENABLE_RATE_LIMIT === 'true') {
app.use(API_DIR, limiters);
}
// Read and register each API function as an Express routes
fs.readdirSync(dirPath, { withFileTypes: true })
.filter(dirent => dirent.isFile() && dirent.name.endsWith('.js'))
.forEach(async dirent => {
const routeName = dirent.name.split('.')[0];
const route = `${API_DIR}/${routeName}`;
// const handler = require(path.join(dirPath, dirent.name));
const handlerModule = await import(path.join(dirPath, dirent.name));
const handler = handlerModule.default || handlerModule;
handlers[route] = handler;
app.get(route, async (req, res) => {
try {
await handler(req, res);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
});
const renderPlaceholderPage = async (res, msgId, logs) => {
const errorMessages = {
notCompiled: 'Looks like the GUI app has not yet been compiled.
'
+ 'Run yarn build
to continue, then restart the server.',
notCompiledSsrHandler: 'Server-side rendering failed to initiate, as SSR handler not found.
'
+ 'This can be fixed by running yarn build
, then restarting the server.
',
disabledGui: 'Web-Check API is up and running!
Access the endpoints at '
+ `${API_DIR}
`,
};
const logOutput = logs ? `
${logs}