import { createHmac } from "node:crypto";
import { error } from "@sveltejs/kit";
import { getConfig } from "$lib/server/config";
import type { RequestHandler } from "./$types";

// the signed url only changes when the secret does, so it can cache for a day
const MAX_AGE = 86400;

const HEX = /^(?:[0-9a-f]{2})+$/;

export const GET: RequestHandler = ({ params }) => {
	const hex = params.hex.toLowerCase();
	if (!HEX.test(hex)) error(400, "Not a camo url");

	const target = Buffer.from(hex, "hex").toString("utf8");
	let parsed: URL;
	try {
		parsed = new URL(target);
	} catch {
		error(400, "Not a camo url");
	}
	if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
		error(400, "Not a camo url");
	}

	// redirecting unsigned would make this an open redirect, so no secret means
	// no images at all
	const { camoUrl, camoSecret } = getConfig();
	if (!camoSecret) error(404, "Camo is not configured");

	const signature = createHmac("sha256", camoSecret).update(target).digest("hex");
	return new Response(null, {
		status: 302,
		headers: {
			location: `${camoUrl}/${signature}/${hex}`,
			"cache-control": `public, max-age=${MAX_AGE}`
		}
	});
};
