akiyama.mizuki.guru/apps/backend/src/routes/proxy.ts

45 lines
1.3 KiB
TypeScript

import { Elysia, t } from "elysia";
const ALLOWED_HOSTS = [
"pbs.twimg.com",
"video.twimg.com",
"ton.twimg.com",
"abs.twimg.com",
];
export default new Elysia({ prefix: "/proxy" })
.get("/image", async ({ query, status, set }) => {
const targetUrl = query.url;
let parsed: URL;
try {
parsed = new URL(targetUrl);
} catch {
return status(400, "Invalid URL");
}
if (!ALLOWED_HOSTS.includes(parsed.hostname)) {
return status(403, `Host not allowed: ${parsed.hostname}`);
}
const response = await fetch(targetUrl, {
headers: {
"User-Agent": "Mozilla/5.0 (compatible; akiyama.mizuki.guru/1.0)",
"Referer": "https://twitter.com/",
},
});
if (!response.ok) {
return status(response.status as any, `Upstream error: ${response.status}`);
}
const contentType = response.headers.get("content-type") ?? "application/octet-stream";
set.headers["Content-Type"] = contentType;
set.headers["Cache-Control"] = "public, max-age=86400, immutable";
return response;
}, {
query: t.Object({
url: t.String(),
}),
});