server/api/media/proxy/[id].ts
Jesse Wierzbinski 1b983f9334
Some checks failed
CodeQL Scan / Analyze (javascript-typescript) (push) Failing after 44s
Build Docker Images / lint (push) Successful in 29s
Build Docker Images / check (push) Failing after 5m42s
Build Docker Images / tests (push) Failing after 6s
Build Docker Images / build (server, Dockerfile, ${{ github.repository_owner }}/server) (push) Has been skipped
Build Docker Images / build (worker, Worker.Dockerfile, ${{ github.repository_owner }}/worker) (push) Has been skipped
Deploy Docs to GitHub Pages / build (push) Failing after 13s
Mirror to Codeberg / Mirror (push) Failing after 0s
Deploy Docs to GitHub Pages / Deploy (push) Has been skipped
Nix Build / check (push) Failing after 32m30s
fix(api): 🐛 Fix routes using incorrect path parameter notation
2025-03-29 03:59:06 +01:00

97 lines
3.1 KiB
TypeScript

import { apiRoute, handleZodError } from "@/api";
import { describeRoute } from "hono-openapi";
import { resolver, validator } from "hono-openapi/zod";
import { proxy } from "hono/proxy";
import type { ContentfulStatusCode, StatusCode } from "hono/utils/http-status";
import { z } from "zod";
import { ApiError } from "~/classes/errors/api-error";
import { config } from "~/config.ts";
export default apiRoute((app) =>
app.get(
"/media/proxy/:id",
describeRoute({
summary: "Proxy media through the server",
responses: {
200: {
description: "Media",
content: {
"*": {
schema: resolver(z.any()),
},
},
},
400: {
description: "Invalid URL to proxy",
content: {
"application/json": {
schema: resolver(ApiError.zodSchema),
},
},
},
},
}),
validator(
"param",
z.object({
id: z
.string()
.transform((val) =>
Buffer.from(val, "base64url").toString(),
),
}),
handleZodError,
),
async (context) => {
const { id } = context.req.valid("param");
// Check if URL is valid
if (!URL.canParse(id)) {
throw new ApiError(
400,
"Invalid URL",
"Should be encoded as base64url",
);
}
const media = await proxy(id, {
// @ts-expect-error Proxy is a Bun-specific feature
proxy: config.http.proxy_address,
});
// Check if file extension ends in svg or svg
// Cloudflare R2 serves those as application/xml
if (
media.headers.get("Content-Type") === "application/xml" &&
id.endsWith(".svg")
) {
media.headers.set("Content-Type", "image/svg+xml");
}
const realFilename =
media.headers
.get("Content-Disposition")
?.match(/filename="(.+)"/)?.[1] || id.split("/").pop();
if (!media.body) {
return context.body(null, media.status as StatusCode);
}
return context.body(
media.body,
media.status as ContentfulStatusCode,
{
"Content-Type":
media.headers.get("Content-Type") ||
"application/octet-stream",
"Content-Length":
media.headers.get("Content-Length") || "0",
"Content-Security-Policy": "",
// Real filename
"Content-Disposition": `inline; filename="${realFilename}"`,
},
);
},
),
);