From 1213aad90d0932ee31938350df23d267905c9218 Mon Sep 17 00:00:00 2001 From: Octo8080X <64694349+Octo8080X@users.noreply.github.com> Date: Thu, 12 Jun 2025 00:34:00 +0900 Subject: [PATCH] feat: add CORS middleware (#3013) ## Why was this PR initiated? I opened an issue and held discussions about officially providing middleware in Fresh by porting middleware from Hono. https://github.com/denoland/fresh/issues/3011 ## What does this PR do? I introduced the CORS middleware bundled with Fresh by porting the CORS middleware from Hono. I appreciate your review. --------- Co-authored-by: Marvin Hagemeister --- src/middlewares/cors.ts | 195 +++++++++++++++++++++++++++ src/middlewares/cors_test.ts | 249 +++++++++++++++++++++++++++++++++++ src/mod.ts | 1 + 3 files changed, 445 insertions(+) create mode 100644 src/middlewares/cors.ts create mode 100644 src/middlewares/cors_test.ts diff --git a/src/middlewares/cors.ts b/src/middlewares/cors.ts new file mode 100644 index 00000000..61ca03db --- /dev/null +++ b/src/middlewares/cors.ts @@ -0,0 +1,195 @@ +import type { FreshContext } from "../context.ts"; +import type { MiddlewareFn } from "./mod.ts"; + +export type CORSOptions = { + origin: + | string + | string[] + | ((requestOrigin: string, ctx: FreshContext) => string | undefined | null); + allowMethods?: string[]; + allowHeaders?: string[]; + maxAge?: number; + credentials?: boolean; + exposeHeaders?: string[]; +}; + +/** + * CORS Middleware for Fresh. + * Adapted from Hono's CORS middleware. + * Would like to express my gratitude to all the developers of Hono. + * + * @param {CORSOptions} [options] - The options for the CORS middleware. + * @param {string | string[] | ((requestOrigin: string, ctx: FreshContext) => string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header. + * @param {string[]} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header. + * @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header. + * @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header. + * @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header. + * @param {string[]} [options.exposeHeaders=[]] - The value of "Access-Control-Expose-Headers" CORS header. + * @returns {(req: Request, ctx: FreshContext) => Promise} The Fresh middleware handler function. + * + * @example + * ```ts + * // main.ts or routes/_middleware.ts + * import { cors } from 'fresh'; + * + * export const handler = [ + * cors({ origin: '*' }), // Allow all origins + * // other middlewares or main route handler + * ]; + * + * // Example with options: + * // export const handler = [ + * // cors({ + * // origin: 'http://example.com', + * // allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'], + * // allowMethods: ['POST', 'GET', 'OPTIONS'], + * // exposeHeaders: ['Content-Length', 'X-Kuma-Revision'], + * // maxAge: 600, + * // credentials: true, + * // }), + * // // ... + * // ]; + * ``` + */ +export function cors(options?: CORSOptions): MiddlewareFn { + const opts: CORSOptions = { + origin: "*", + allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"], + allowHeaders: [], + exposeHeaders: [], + ...options, + }; + + const findAllowOrigin = ((optsOrigin: CORSOptions["origin"]) => { + if (typeof optsOrigin === "string") { + if (optsOrigin === "*") { + return (_requestOrigin: string, _ctx: FreshContext) => optsOrigin; + } else { + return (requestOrigin: string, _ctx: FreshContext) => + optsOrigin === requestOrigin ? requestOrigin : null; + } + } else if (typeof optsOrigin === "function") { + return (requestOrigin: string, ctx: FreshContext) => + optsOrigin(requestOrigin, ctx); + } else { + return (requestOrigin: string, _ctx: FreshContext) => + optsOrigin.includes(requestOrigin) ? requestOrigin : null; + } + })(opts.origin); + + const addHeaderProperties = ( + headers: Headers, + allowOrigin: string | null | undefined, + opts: CORSOptions, + ) => { + if (allowOrigin) { + headers.set("Access-Control-Allow-Origin", allowOrigin); + } + + if (opts.credentials) { + headers.set("Access-Control-Allow-Credentials", "true"); + } + + if (opts.exposeHeaders?.length) { + headers.set( + "Access-Control-Expose-Headers", + opts.exposeHeaders.join(","), + ); + } + }; + + const OptionsResponse = ( + ctx: FreshContext, + allowOrigin: string | null | undefined, + opts: CORSOptions, + varyValues: Set, + ) => { + const headers = new Headers(); + + addHeaderProperties( + headers, + allowOrigin, + opts, + ); + + if (opts.maxAge != null) { + headers.set("Access-Control-Max-Age", opts.maxAge.toString()); + } + + if (opts.allowMethods?.length) { + headers.set( + "Access-Control-Allow-Methods", + opts.allowMethods.join(","), + ); + } + + let effectiveAllowHeaders = opts.allowHeaders; + if (!effectiveAllowHeaders?.length) { + const reqHeaders = ctx.req.headers.get( + "Access-Control-Request-Headers", + ); + if (reqHeaders) { + effectiveAllowHeaders = reqHeaders.split(/\s*,\s*/); + } + } + + if (effectiveAllowHeaders?.length) { + headers.set( + "Access-Control-Allow-Headers", + effectiveAllowHeaders.join(","), + ); + varyValues.add("Access-Control-Request-Headers"); + } + + if (varyValues.size > 0) { + headers.set("Vary", Array.from(varyValues).join(", ")); + } else { + headers.delete("Vary"); // Ensure Vary is not set if no conditions met + } + + headers.delete("Content-Length"); + headers.delete("Content-Type"); + + return new Response(null, { + status: 204, + statusText: "No Content", + headers, + }); + }; + + return async (ctx: FreshContext): Promise => { + const requestOrigin = ctx.req.headers.get("origin") || ""; + const allowOrigin = findAllowOrigin(requestOrigin, ctx); + + const varyValues = new Set(); + // Add 'Origin' to Vary if a specific origin is allowed, not '*' + if (opts.origin !== "*" && allowOrigin && allowOrigin !== "*") { + varyValues.add("Origin"); + } + + if (ctx.req.method === "OPTIONS") { + return OptionsResponse(ctx, allowOrigin, opts, varyValues); + } + + // For non-OPTIONS requests + const res = await ctx.next(); + + addHeaderProperties( + res.headers, + allowOrigin, + opts, + ); + + // Merge our calculated varyValues with any existing Vary from downstream response + if (varyValues.size > 0) { + const existingVary = res.headers.get("Vary"); + if (existingVary) { + existingVary.split(/\s*,\s*/).forEach((v) => varyValues.add(v)); + } + + res.headers.set("Vary", Array.from(varyValues).join(", ")); + } + + return res; + }; +} diff --git a/src/middlewares/cors_test.ts b/src/middlewares/cors_test.ts new file mode 100644 index 00000000..1d0f356a --- /dev/null +++ b/src/middlewares/cors_test.ts @@ -0,0 +1,249 @@ +import { App } from "../app.ts"; +import type { FreshContext } from "../context.ts"; +import { cors } from "./cors.ts"; +import { describe, it } from "@std/testing/bdd"; +import { expect } from "@std/expect"; + +describe("CORS by Middleware", () => { + const app = new App(); + + app.all("/api/*", cors()); + + app.all( + "/api2/*", + cors({ + origin: "http://example.com", + allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"], + allowMethods: ["POST", "GET", "OPTIONS"], + exposeHeaders: ["Content-Length", "X-Kuma-Revision"], + maxAge: 600, + credentials: true, + }), + ); + + app.all( + "/api3/*", + cors({ + origin: [ + "http://example.com", + "http://example.org", + "http://example.dev", + ], + }), + ); + + app.all( + "/api4/*", + cors({ + origin: ( + origin, + ) => (origin.endsWith(".example.com") ? origin : "http://example.com"), + }), + ); + + app.all("/api5/*", cors()); + + app.all( + "/api6/*", + cors({ + origin: "http://example.com", + }), + ); + // + app.get("/api/abc", (_ctx: FreshContext) => { + return Response.json({ success: true }); + }); + + app.get("/api2/abc", (_ctx: FreshContext) => { + return Response.json({ success: true }); + }); + + app.get("/api3/abc", (_ctx: FreshContext) => { + return Response.json({ success: true }); + }); + + app.get("/api4/abc", (_ctx: FreshContext) => { + return Response.json({ success: true }); + }); + + app.get("/api5/abc", () => { + return new Response(JSON.stringify({ success: true })); + }); + + app.get("/api6/abc", (_ctx: FreshContext) => { + return Response.json({ success: true }); + }); + + const handler = app.handler(); + + it("GET default", async () => { + const res = await handler( + new Request("https://localhost/api/abc"), + ); + + expect(res.status).toBe(200); + expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*"); + expect(res.headers.get("Vary")).toBeNull(); + }); + + it("Preflight default", async () => { + const req = new Request("https://localhost/api/abc", { method: "OPTIONS" }); + req.headers.append( + "Access-Control-Request-Headers", + "X-PINGOTHER, Content-Type", + ); + + const res = await handler(req); + + expect(res.status).toBe(204); + expect(res.statusText).toBe("No Content"); + expect(res.headers.get("Access-Control-Allow-Methods")?.split(",")[0]).toBe( + "GET", + ); + expect(res.headers.get("Access-Control-Allow-Headers")?.split(",")).toEqual( + [ + "X-PINGOTHER", + "Content-Type", + ], + ); + }); + + it("Preflight with options", async () => { + const req = new Request("https://localhost/api2/abc", { + method: "OPTIONS", + headers: { origin: "http://example.com" }, + }); + + const res = await handler(req); + + expect(res.headers.get("Access-Control-Allow-Origin")).toBe( + "http://example.com", + ); + expect(res.headers.get("Vary")?.split(/\s*,\s*/)).toEqual( + expect.arrayContaining(["Origin"]), + ); + expect(res.headers.get("Access-Control-Allow-Headers")?.split(/\s*,\s*/)) + .toEqual([ + "X-Custom-Header", + "Upgrade-Insecure-Requests", + ]); + expect(res.headers.get("Access-Control-Allow-Methods")?.split(/\s*,\s*/)) + .toEqual([ + "POST", + "GET", + "OPTIONS", + ]); + expect(res.headers.get("Access-Control-Expose-Headers")?.split(/\s*,\s*/)) + .toEqual([ + "Content-Length", + "X-Kuma-Revision", + ]); + expect(res.headers.get("Access-Control-Max-Age")).toBe("600"); + expect(res.headers.get("Access-Control-Allow-Credentials")).toBe("true"); + }); + + it("Disallow an unmatched origin", async () => { + const req = new Request("https://localhost/api2/abc", { + method: "OPTIONS", + headers: { origin: "http://example.net" }, + }); + + const res = await handler(req); + expect(res.headers.has("Access-Control-Allow-Origin")).toBeFalsy(); + }); + + it("Allow multiple origins", async () => { + let req = new Request("http://localhost/api3/abc", { + headers: { + Origin: "http://example.org", + }, + }); + let res = await handler(req); + expect(res.headers.get("Access-Control-Allow-Origin")).toBe( + "http://example.org", + ); + + req = new Request("http://localhost/api3/abc"); + res = await handler(req); + expect( + res.headers.has("Access-Control-Allow-Origin"), + "An unmatched origin should be disallowed", + ).toBeFalsy(); + + req = new Request("http://localhost/api3/abc", { + headers: { + Referer: "http://example.net/", + }, + }); + res = await handler(req); + expect( + res.headers.has("Access-Control-Allow-Origin"), + "An unmatched origin should be disallowed", + ).toBeFalsy(); + }); + + it("Allow different Vary header value", async () => { + const req = new Request("http://localhost/api3/abc", { + headers: { + Vary: "accept-encoding", + Origin: "http://example.com", + }, + }); + const res = await handler(req); + + expect(res.status).toBe(200); + expect(res.headers.get("Access-Control-Allow-Origin")).toBe( + "http://example.com", + ); + expect(res.headers.get("Vary")).toBe("Origin"); + }); + + it("Allow origins by function", async () => { + let req = new Request("http://localhost/api4/abc", { + headers: { + Origin: "http://subdomain.example.com", + }, + }); + let res = await handler(req); + expect(res.headers.get("Access-Control-Allow-Origin")).toBe( + "http://subdomain.example.com", + ); + + req = new Request("http://localhost/api4/abc"); + res = await handler(req); + expect(res.headers.get("Access-Control-Allow-Origin")).toBe( + "http://example.com", + ); + + req = new Request("http://localhost/api4/abc", { + headers: { + Referer: "http://evil-example.com/", + }, + }); + res = await handler(req); + expect(res.headers.get("Access-Control-Allow-Origin")).toBe( + "http://example.com", + ); + }); + + it("With raw Response object", async () => { + const req = new Request("http://localhost/api5/abc"); + const res = await handler(req); + + expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*"); + expect(res.headers.get("Vary")).toBeNull(); + }); + + it("Should not return duplicate header values", async () => { + const req = new Request("http://localhost/api6/abc", { + headers: { + origin: "http://example.com", + }, + }); + const res = await handler(req); + + expect(res.headers.get("Access-Control-Allow-Origin")).toBe( + "http://example.com", + ); + }); +}); diff --git a/src/mod.ts b/src/mod.ts index 96b39193..91a1d51b 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -12,6 +12,7 @@ export { export type { LayoutConfig, RouteConfig } from "./types.ts"; export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts"; export { staticFiles } from "./middlewares/static_files.ts"; +export { cors, type CORSOptions } from "./middlewares/cors.ts"; export type { FreshConfig, ResolvedFreshConfig } from "./config.ts"; export type { FreshContext, Island, PageProps } from "./context.ts"; export { createDefine, type Define } from "./define.ts";