CognxSafeTrack
feat(security): API key auth, HMAC webhook verification, rate limiting, Zod validation
04b12d1
import { FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify';
/**
* API Key Authentication Plugin
*
* Validates the `Authorization: Bearer <ADMIN_API_KEY>` header on all routes
* where this plugin is registered. Register only on private route prefixes
* (/v1/admin, /v1/ai, /v1/payments). The public webhook route (/v1/whatsapp)
* must NOT have this plugin applied.
*
* No external dependencies β€” uses Fastify's built-in addHook API.
*/
const authPlugin: FastifyPluginAsync = async (fastify) => {
fastify.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {
const apiKey = process.env.ADMIN_API_KEY;
if (!apiKey) {
// If the env var is missing, fail safe β€” don't allow any access
request.log.error('ADMIN_API_KEY environment variable is not set!');
return reply.code(503).send({ error: 'Service misconfigured' });
}
const authHeader = request.headers['authorization'];
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return reply.code(401).send({ error: 'Unauthorized', message: 'Missing Authorization header' });
}
const token = authHeader.slice(7); // Remove 'Bearer ' prefix
if (token !== apiKey) {
return reply.code(401).send({ error: 'Unauthorized', message: 'Invalid API key' });
}
// Authenticated β€” continue to handler
});
};
export default authPlugin;