File size: 1,480 Bytes
04b12d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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;