secure-express-setup
Version:
Military-grade one-command security setup for Express.js applications
38 lines (30 loc) • 1.39 kB
JavaScript
// lib/apiKey.js
// Simple API key protector. Accepts options: { getKeys: fn|object, headerName, allowQuery }
function setupApiKeyProtection(options = {}) {
const headerName = options.headerName || 'x-api-key';
const allowQuery = options.allowQuery === true;
const getKeys = typeof options.getKeys === 'function'
? options.getKeys
: () => Promise.resolve(options.keys || {}); // keys: { "<key>": { owner, scopes: [...] } }
return async function apiKeyMiddleware(req, res, next) {
try {
const header = req.headers[headerName] || '';
const authHeader = req.headers.authorization || '';
let key = '';
if (authHeader.startsWith('ApiKey ')) key = authHeader.slice('ApiKey '.length);
else if (header) key = header;
else if (allowQuery && req.query && req.query.api_key) key = req.query.api_key;
if (!key) return res.status(401).json({ error: 'API key required' });
const keys = await getKeys();
const meta = keys[key];
if (!meta) return res.status(403).json({ error: 'Invalid API key' });
// Attach metadata for downstream usage
req.apiKey = { key, ...meta };
next();
} catch (err) {
console.error('API Key middleware error:', err);
res.status(500).json({ error: 'Internal error' });
}
};
}
module.exports = setupApiKeyProtection;