import { describe, expect, mock, test } from "bun:test";
mock.module("cloudflare:workers", () => ({
env: { SECRETS_KEY: "test-secret", PUBLIC_URL: "https://forge.example.com" },
}));
const { renderMarkdown } = await import("./markdown");
const { verifyCamoPath } = await import("./camo-sign");
const context = { owner: "acme", repo: "app", ref: "main", basePath: "docs" };
function camoTargets(html: string): string[] {
return [...html.matchAll(/src="(\/camo\/[^"]+)"/g)].map((match) => verifyCamoPath(match[1]) ?? "INVALID");
}
describe("renderMarkdown hardening", () => {
test("external markdown images are rewritten to signed camo URLs", () => {
const html = renderMarkdown("", context);
expect(html).not.toContain("https://evil.example/pixel.gif");
expect(camoTargets(html)).toEqual(["https://evil.example/pixel.gif"]);
});
test("raw <img> and protocol-relative sources are proxied too", () => {
const html = renderMarkdown('<img src="//tracker.example/p.png"><img src="http://a.example/b.jpg">', context);
expect(camoTargets(html)).toEqual(["https://tracker.example/p.png", "http://a.example/b.jpg"]);
});
test("slashless and backslash external images are proxied, not loaded directly", () => {
const html = renderMarkdown(" ", context);
expect(html).not.toMatch(/src="https?:/);
expect(camoTargets(html)).toEqual(["http://evil.example/a.gif", "https://evil.example/b.gif"]);
const bare = renderMarkdown("", null);
expect(bare).not.toContain('src="/\\evil');
});
test("entity-encoded raw image sources are decoded before the camo decision", () => {
const html = renderMarkdown(
'<img src="//evil.example/x.gif"><img src="https://evil.example/y.gif">',
null,
);