75 lines · 2.8 KB
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,
}));

const { memoryScopes } = await import("../scoped-db/testing");
let scopes = memoryScopes();
mock.module("../scoped-db", () => ({
  accountDb: (id: string) => scopes.accountDb(id),
  repoDb: (id: string) => scopes.repoDb(id),
  stmt: scopes.module.stmt,
}));
mock.module("../db", () => ({
  first: async () => null,
  run: async () => ({ meta: { changes: 0 } }),
  all: async () => [],
  stmt: () => ({}),
  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(() => {
  scopes = memoryScopes();
});

describe("unsubscribe tokens", () => {
  test("a fresh token resolves to its user for its own category only", async () => {
    const footer = await emailFooter("u1", "ci");
    const token = tokenOf(footer.unsubscribeUrl);
    expect(token).not.toBe("");
    expect(await userForUnsubscribeToken(token, "ci")).toBe("u1");
    expect(await userForUnsubscribeToken(token, "deploy")).toBeNull();