From 5f785c391d44abee8564a54c45dcdf436601fd39 Mon Sep 17 00:00:00 2001 From: Jesse Wierzbinski Date: Sat, 4 May 2024 21:02:25 -1000 Subject: [PATCH] refactor(api): :art: Switch to base64url for proxy url encoding instead of plaintext --- server/api/media/proxy/index.ts | 14 ++++++++++++-- utils/response.ts | 3 ++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/server/api/media/proxy/index.ts b/server/api/media/proxy/index.ts index 38960432..dfa19af4 100644 --- a/server/api/media/proxy/index.ts +++ b/server/api/media/proxy/index.ts @@ -1,5 +1,5 @@ import { apiRoute, applyConfig } from "@api"; -import { response } from "@response"; +import { errorResponse, response } from "@response"; import { z } from "zod"; export const meta = applyConfig({ @@ -15,13 +15,23 @@ export const meta = applyConfig({ }); export const schema = z.object({ - url: z.string(), + // Base64 encoded URL + url: z + .string() + .transform((val) => Buffer.from(val, "base64url").toString()), }); export default apiRoute( async (req, matchedRoute, extraData) => { const { url } = extraData.parsedRequest; + // Check if URL is valid + if (!URL.canParse(url)) + return errorResponse( + "Invalid URL (it should be encoded as base64url", + 400, + ); + return fetch(url).then((res) => { return response(res.body, res.status, res.headers.toJSON()); }); diff --git a/utils/response.ts b/utils/response.ts index d74502a6..3bd2ac75 100644 --- a/utils/response.ts +++ b/utils/response.ts @@ -73,9 +73,10 @@ export const redirect = (url: string | URL, status = 302) => { }; export const proxyUrl = (url: string | null) => { + const urlAsBase64Url = Buffer.from(url || "").toString("base64url"); return url ? new URL( - `/media/proxy?url=${encodeURIComponent(url)}`, + `/media/proxy?url=${urlAsBase64Url}`, config.http.base_url, ).toString() : url;