import { beforeEach, describe, expect, mock, test } from "bun:test";
mock.module("cloudflare:workers", () => ({
env: { PUBLIC_URL: "https://forge.example.com", SECRETS_KEY: "k".repeat(32) },
waitUntil: () => undefined,
}));
let secrets = new Map<string, string>();
mock.module("../db", () => ({
first: async (sql: string, ...params: unknown[]) => {
if (sql.includes("FROM notification_unsubscribe_tokens")) {
const token = secrets.get(String(params[0]));
return token ? { token } : null;
}
return null;
},
run: async (sql: string, ...params: unknown[]) => {
if (sql.includes("INSERT OR IGNORE INTO notification_unsubscribe_tokens")) {
if (!secrets.has(String(params[0]))) secrets.set(String(params[0]), String(params[1]));
} else if (sql.includes("DELETE FROM notification_unsubscribe_tokens")) secrets.delete(String(params[0]));
return { meta: { changes: 1 } };
},
all: async () => [],
chunks: <T>(items: T[]) => [items],
placeholders: (count: number) => Array(count).fill("?").join(","),
}));
const { emailFooter, userForUnsubscribeToken, revokeUnsubscribeTokens, canUnsubscribe } = await import("./prefs");
function tokenOf(url: string | null): string {
return new URL(url ?? "").searchParams.get("token") ?? "";
}
beforeEach(() => {
secrets = new Map();
});
describe("unsubscribe tokens", () => {
test("a fresh token resolves to its user for its own category only", async () => {
const footer = await emailFooter("u1", "ci");