~james/core

core/web/src/lib/server/camo.ts -rw-r--r-- 797 bytes
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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)}`;
};