Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/fresh/src/middlewares/static_files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import { BUILD_ID } from "@fresh/build-id";
import { tracer } from "../otel.ts";
import { getBuildCache } from "../context.ts";

/** Decode and re-encode each path segment so that characters like commas
* are percent-encoded consistently with how `prepareStaticFile` stores
* entries in the build cache. */
function normalizePathname(pathname: string): string {
return "/" +
pathname.split("/").filter(Boolean).map(encodeURIComponent).join("/");
}

/**
* Fresh middleware to serve static files from the `static/` directory.
* ```ts
Expand All @@ -25,6 +33,13 @@ export function staticFiles<T>(): Middleware<T> {
: "/";
}

try {
pathname = normalizePathname(decodeURIComponent(pathname));
} catch (_e: unknown) {
if (!(_e instanceof URIError)) throw _e;
return await ctx.next();
}

// Fast path bail out
const startTime = performance.now() + performance.timeOrigin;
const file = await buildCache.readFile(pathname);
Expand Down
26 changes: 26 additions & 0 deletions packages/fresh/src/middlewares/static_files_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,3 +296,29 @@ Deno.test("static files - fallthrough", async () => {
expect(text).toEqual("it works");
expect(called).toEqual(["before", "after"]);
});

Deno.test("static files - comma in pathname", async () => {
const key = systemPathToUrlEncoded("foo,bar.css");

const buildCache = new MockBuildCache({
[key]: {
content: "body {}",
hash: null,
},
});

const server = serveMiddleware(
staticFiles(),
{ buildCache },
);

// Browser/request path usually keeps the comma unencoded
let res = await server.get("/foo,bar.css");
await res.body?.cancel();
expect(res.status).toEqual(200);

// Encoded form should also resolve
res = await server.get("/foo%2Cbar.css");
await res.body?.cancel();
expect(res.status).toEqual(200);
});