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

Function withCorsHeaders

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

Source from the content-addressed store, hash-verified

256} as const;
257
258const 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
285const corsPreflightResponse = (req: Request, allowedHosts: ReadonlySet<string>): Response =>
286 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