import { createHmac } from "node:crypto";
import { toHex } from "#lib/markup/paths.ts";
import { signableTarget } from "#lib/server/camotarget.ts";
import { getConfig } from "#lib/server/config.ts";
// null when camo cannot carry the target: no secret configured, or a host the
// worker must not be aimed at
export const camoUrl = (target: string): string | null => {
let parsed: URL;
try {
parsed = new URL(target);
} catch {
return null;
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
if (!signableTarget(parsed)) return null;
const { camoUrl: origin, camoSecret } = getConfig();
if (!camoSecret) return null;
const signature = createHmac("sha256", camoSecret).update(target).digest("hex");
return `${origin}/${signature}/${toHex(target)}`;
};