refactor(api): 🎨 Switch to base64url for proxy url encoding instead of plaintext

This commit is contained in:
Jesse Wierzbinski 2024-05-04 21:02:25 -10:00
parent 3be9d1d6ce
commit 5f785c391d
No known key found for this signature in database
2 changed files with 14 additions and 3 deletions

View file

@ -1,5 +1,5 @@
import { apiRoute, applyConfig } from "@api"; import { apiRoute, applyConfig } from "@api";
import { response } from "@response"; import { errorResponse, response } from "@response";
import { z } from "zod"; import { z } from "zod";
export const meta = applyConfig({ export const meta = applyConfig({
@ -15,13 +15,23 @@ export const meta = applyConfig({
}); });
export const schema = z.object({ export const schema = z.object({
url: z.string(), // Base64 encoded URL
url: z
.string()
.transform((val) => Buffer.from(val, "base64url").toString()),
}); });
export default apiRoute<typeof meta, typeof schema>( export default apiRoute<typeof meta, typeof schema>(
async (req, matchedRoute, extraData) => { async (req, matchedRoute, extraData) => {
const { url } = extraData.parsedRequest; 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 fetch(url).then((res) => {
return response(res.body, res.status, res.headers.toJSON()); return response(res.body, res.status, res.headers.toJSON());
}); });

View file

@ -73,9 +73,10 @@ export const redirect = (url: string | URL, status = 302) => {
}; };
export const proxyUrl = (url: string | null) => { export const proxyUrl = (url: string | null) => {
const urlAsBase64Url = Buffer.from(url || "").toString("base64url");
return url return url
? new URL( ? new URL(
`/media/proxy?url=${encodeURIComponent(url)}`, `/media/proxy?url=${urlAsBase64Url}`,
config.http.base_url, config.http.base_url,
).toString() ).toString()
: url; : url;