CognxSafeTrack
feat(security): API key auth, HMAC webhook verification, rate limiting, Zod validation
04b12d1 Download apps/api/src/plugins/auth.ts from safetrack/edtech: direct link, hf CLI and curl.
- Browser
- Download file 1.48 kB
-
https://huggingface.co/spaces/safetrack/edtech/resolve/main/apps/api/src/plugins/auth.ts
- Command line
-
hf download hf://spaces/safetrack/edtech/apps/api/src/plugins/auth.ts
-
curl -L -o auth.ts https://huggingface.co/spaces/safetrack/edtech/resolve/main/apps/api/src/plugins/auth.ts
1.48 kB
| 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; | |