( opts: OriginHookOptions, )
| 95 | * fails closed without leaking headers. |
| 96 | */ |
| 97 | export function createOriginHook( |
| 98 | opts: OriginHookOptions, |
| 99 | ): (req: FastifyRequest, reply: FastifyReply) => Promise<FastifyReply | void> { |
| 100 | const allowed = opts.allowedOrigins ?? []; |
| 101 | return async (req, reply) => { |
| 102 | const origin = req.headers.origin; |
| 103 | if (origin === undefined) { |
| 104 | return; |
| 105 | } |
| 106 | if (isOriginAllowed(origin, req.headers.host, allowed)) { |
| 107 | reply.header('Access-Control-Allow-Origin', origin); |
| 108 | reply.header('Access-Control-Allow-Methods', CORS_ALLOW_METHODS); |
| 109 | reply.header('Access-Control-Allow-Headers', CORS_ALLOW_HEADERS); |
| 110 | reply.header('Vary', 'Origin'); |
| 111 | if (req.method === 'OPTIONS') { |
| 112 | return reply.code(204).send(); |
| 113 | } |
| 114 | return; |
| 115 | } |
| 116 | // Origin present but not allowed: emit no CORS headers so the browser |
| 117 | // blocks the response. Short-circuit the preflight to fail closed. |
| 118 | if (req.method === 'OPTIONS') { |
| 119 | return reply.code(204).send(); |
| 120 | } |
| 121 | }; |
| 122 | } |
no test coverage detected