MCPcopy Create free account
hub / github.com/UsefulSoftwareCo/executor / withCorsHeaders

Function withCorsHeaders

apps/local/src/serve.ts:259–284  ·  view source on GitHub ↗
(
  req: Request,
  response: Response,
  allowedHosts: ReadonlySet<string>,
)

Source from the content-addressed store, hash-verified

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

Callers 2

corsPreflightResponseFunction · 0.85
withCorsFunction · 0.85

Calls 4

isAllowedOriginFunction · 0.90
setMethod · 0.80
getMethod · 0.65
appendMethod · 0.65

Tested by

no test coverage detected