| 1 | import { HttpError } from '../errors/http-error'; |
| 2 | |
| 3 | import type { RequestHandler } from 'express'; |
| 4 | |
| 5 | export interface InternalAuthOptions { |
| 6 | headerName?: string; |
| 7 | exemptPaths?: string[]; |
| 8 | } |
| 9 | |
| 10 | const DEFAULT_HEADER_NAME = 'x-internal-token'; |
| 11 | |
| 12 | export const createInternalAuthMiddleware = ( |
| 13 | expectedToken: string, |
| 14 | options: InternalAuthOptions = {}, |
| 15 | ): RequestHandler => { |
| 16 | const headerName = options.headerName?.toLowerCase() ?? DEFAULT_HEADER_NAME; |
| 17 | const exemptPaths = new Set(options.exemptPaths ?? []); |
| 18 | |
| 19 | return (req, _res, next) => { |
| 20 | if (exemptPaths.has(req.path)) { |
| 21 | next(); |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | const provided = req.headers[headerName]; |
| 26 | const token = Array.isArray(provided) ? provided[0] : provided; |
| 27 | |
| 28 | if (typeof token !== 'string' || token !== expectedToken) { |
| 29 | next(new HttpError(401, 'Unauthorized')); |
| 30 | return; |
| 31 | } |
| 32 | |
| 33 | next(); |
| 34 | }; |
| 35 | }; |