( req: Request, response: Response, allowedHosts: ReadonlySet<string>, )
| 256 | } as const; |
| 257 | |
| 258 | const withCorsHeaders = ( |
| 259 | req: Request, |
| 260 | response: Response, |
| 261 | allowedHosts: ReadonlySet<string>, |
| 262 | ): Response => { |
| 263 | const origin = req.headers.get("origin"); |
| 264 | // Same-origin requests carry no Origin header — nothing to do. Cross-origin |
| 265 | // requests only get credentialed CORS if their Origin is an allowed loopback |
| 266 | // host; an arbitrary web page (e.g. https://evil.example) gets no ACAO, so |
| 267 | // the browser blocks it reading the response even if it knew the token. |
| 268 | if (!origin || !isAllowedOrigin(origin, allowedHosts)) return response; |
| 269 | const headers = new Headers(response.headers); |
| 270 | headers.set("access-control-allow-origin", origin); |
| 271 | for (const [key, value] of Object.entries(corsHeaders)) headers.set(key, value); |
| 272 | headers.set( |
| 273 | "access-control-allow-headers", |
| 274 | req.headers.get("access-control-request-headers") ?? |
| 275 | corsHeaders["access-control-allow-headers"], |
| 276 | ); |
| 277 | headers.append("vary", "Origin"); |
| 278 | return new Response(response.body, { |
| 279 | status: response.status, |
| 280 | statusText: response.statusText, |
| 281 | headers, |
| 282 | }); |
| 283 | }; |
| 284 | |
| 285 | const corsPreflightResponse = (req: Request, allowedHosts: ReadonlySet<string>): Response => |
| 286 | withCorsHeaders(req, new Response(null, { status: 204 }), allowedHosts); |
no test coverage detected