| 1 | import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 2 | import { createSession, type CommunityAgentEnv } from "../community-agent"; |
| 3 | import { handleAdminMerchInterest, handleMerchInterest, interestOriginAllowed, type MerchInterestEnv, type MerchInterest } from "./interest"; |
| 4 | import { MERCH_INTEREST_ITEMS } from "./interest-options"; |
| 5 | |
| 6 | const PREFIX = "private:merch-interest:v1:"; |
| 7 | let records: Map<string, string>, env: MerchInterestEnv; |
| 8 | const put = vi.fn(), get = vi.fn(), list = vi.fn(), remove = vi.fn(), limit = vi.fn(); |
| 9 | const input = () => ({ email: "fixture@example.test", country: "China", currency: "cny", locale: "zh", consent: true, website: "", picks: [{ id: "signature-tee", priceChoice: "mid" }, { id: "mousepad", priceChoice: "low" }] }); |
| 10 | function request(value: unknown = input(), headers: Record<string, string> = {}) { |
| 11 | return new Request("https://codewhale.net/api/merch/interest", { method: "POST", headers: { "Content-Type": "application/json", Origin: "https://codewhale.net", "CF-Connecting-IP": "192.0.2.10", ...headers }, body: JSON.stringify(value) }); |
| 12 | } |
| 13 | function interestRecords() { return [...records.entries()].filter(([key]) => key.startsWith(PREFIX)); } |
| 14 | beforeEach(() => { |
| 15 | vi.clearAllMocks(); |
| 16 | records = new Map(); |
| 17 | get.mockImplementation(async (key: string) => records.get(key) ?? null); |
| 18 | put.mockImplementation(async (key: string, value: string) => { records.set(key, value); }); |
| 19 | remove.mockImplementation(async (key: string) => { records.delete(key); }); |
| 20 | list.mockImplementation(async ({ prefix, limit: pageSize, cursor = "0" }: { prefix: string; limit: number; cursor?: string }) => { |
| 21 | const keys = [...records.keys()].filter(key => key.startsWith(prefix)).sort(); |
| 22 | const page = keys.slice(Number(cursor), Number(cursor) + pageSize); |
| 23 | const complete = Number(cursor) + pageSize >= keys.length; |
| 24 | return { keys: page.map(name => ({ name })), list_complete: complete, cursor: complete ? "" : String(Number(cursor) + pageSize) }; |
| 25 | }); |
| 26 | limit.mockResolvedValue({ success: true }); |
| 27 | env = { CURATED_KV: { get, put, list, delete: remove }, MERCH_INTEREST_LIMITER: { limit } }; |
| 28 | vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("No external calls are allowed in interest tests"); })); |
| 29 | }); |
| 30 | afterEach(() => { vi.unstubAllGlobals(); }); |
| 31 | |
| 32 | describe("durable merch interest registration", () => { |
| 33 | it("writes consent, unverified status and authoritative currency choices before generic success", async () => { |
| 34 | const response = await handleMerchInterest(request({ ...input(), email: " Fixture@Example.Test ", country: " China " }), env); |
| 35 | expect(response.status).toBe(200); |
| 36 | expect(await response.json()).toEqual({ ok: true }); |
| 37 | expect(response.headers.get("Cache-Control")).toBe("no-store"); |
| 38 | expect(put).toHaveBeenCalledTimes(1); |
| 39 | const [key, serialized, ttl] = put.mock.calls[0]; |
| 40 | expect(key).toMatch(/^private:merch-interest:v1:[a-f0-9]{64}$/); |
| 41 | expect(key).not.toContain("fixture"); |
| 42 | expect(ttl).toEqual({ expirationTtl: 15552000 }); |
| 43 | const saved = JSON.parse(serialized) as MerchInterest; |
| 44 | expect(saved).toMatchObject({ schemaVersion: 1, email: "fixture@example.test", country: "China", currency: "cny", locale: "zh", consent: true, emailVerified: false, picks: [{ id: "signature-tee", priceChoice: "mid", surveyAmount: 69 }, { id: "mousepad", priceChoice: "low", surveyAmount: 29 }] }); |
| 45 | expect(Date.parse(saved.expiresAt) - Date.parse(saved.submittedAt)).toBe(15552000000); |
| 46 | expect(limit.mock.calls.map(([value]) => value.key)).toEqual([expect.stringMatching(/^merch-interest:ip:[a-f0-9]{64}$/), expect.stringMatching(/^merch-interest:email:[a-f0-9]{64}$/)]); |
| 47 | expect(fetch).not.toHaveBeenCalled(); |
| 48 | }); |
| 49 | |
| 50 | it("replaces repeated email choices without exposing whether it existed", async () => { |
| 51 | const first = await handleMerchInterest(request(), env); |
| 52 | const second = await handleMerchInterest(request({ ...input(), currency: "usd", picks: [{ id: "plush", priceChoice: "unsure" }] }), env); |
| 53 | expect(await first.json()).toEqual(await second.json()); |
| 54 | expect(interestRecords()).toHaveLength(1); |
| 55 | expect(JSON.parse(interestRecords()[0][1])).toMatchObject({ currency: "usd", picks: [{ id: "plush", priceChoice: "unsure", surveyAmount: null }] }); |
| 56 | }); |
| 57 | |
| 58 | it("accepts all registered items and stores USD amounts from shared survey options", async () => { |
| 59 | const picks = MERCH_INTEREST_ITEMS.map(item => ({ id: item.id, priceChoice: "high" })); |
| 60 | const response = await handleMerchInterest(request({ ...input(), currency: "usd", locale: "pt-BR", picks }), env); |
| 61 | expect(response.status).toBe(200); |
| 62 | const saved = JSON.parse(interestRecords()[0][1]) as MerchInterest; |
| 63 | expect(saved.picks.map(pick => pick.surveyAmount)).toEqual(MERCH_INTEREST_ITEMS.map(item => item.prices.usd[2])); |
| 64 | }); |
| 65 | |
| 66 | it.each(["storage", "limiter"])("fails closed when %s is absent, including status", async (missing) => { |
| 67 | if (missing === "storage") delete env.CURATED_KV; |
| 68 | else delete env.MERCH_INTEREST_LIMITER; |
| 69 | const status = await handleMerchInterest(new Request("https://codewhale.net/api/merch/interest"), env); |
| 70 | expect(await status.json()).toEqual({ available: false }); |
| 71 | const denied = request(); |
| 72 | expect((await handleMerchInterest(denied, env)).status).toBe(503); |
| 73 | expect(denied.bodyUsed).toBe(false); |
| 74 | expect(put).not.toHaveBeenCalled(); |
| 75 | }); |
| 76 | |
| 77 | it.each(["storage", "limiter"])("never returns success when %s throws, and does not echo errors", async (failed) => { |
| 78 | (failed === "storage" ? put : limit).mockRejectedValue(new Error("fixture@example.test secret provider error")); |
| 79 | const response = await handleMerchInterest(request(), env); |
| 80 | expect(response.status).toBe(503); |
| 81 | expect(await response.text()).not.toMatch(/fixture@example|secret provider/); |
| 82 | expect(interestRecords()).toHaveLength(0); |
| 83 | }); |
| 84 | |
| 85 | it("blocks a denied native rate limit before reading the body", async () => { |
| 86 | limit.mockResolvedValue({ success: false }); |
| 87 | const denied = request(); |
| 88 | const response = await handleMerchInterest(denied, env); |
| 89 | expect(response.status).toBe(429); |
| 90 | expect(response.headers.get("Retry-After")).toBe("60"); |
| 91 | expect(denied.bodyUsed).toBe(false); |
| 92 | expect(put).not.toHaveBeenCalled(); |
| 93 | }); |
| 94 | |
| 95 | it.each(["", "https://evil.example", "https://codewhale.net.evil.example", "https://codewhale.net/", "http://127.0.0.1:3100"])("blocks origin %s", async (origin) => { |
| 96 | const response = await handleMerchInterest(request(input(), { Origin: origin }), env); |
| 97 | expect(response.status).toBe(403); |
| 98 | expect(limit).not.toHaveBeenCalled(); |
| 99 | expect(put).not.toHaveBeenCalled(); |
| 100 | }); |
| 101 | |
| 102 | it("permits the exact configured HTTPS origin and development loopback only", () => { |
| 103 | const custom = request(input(), { Origin: "https://merch.example.test" }); |
| 104 | expect(interestOriginAllowed(custom, { MERCH_INTEREST_SITE_ORIGIN: "https://merch.example.test" })).toBe(true); |
| 105 | expect(interestOriginAllowed(request(), { MERCH_INTEREST_SITE_ORIGIN: "https://merch.example.test" })).toBe(false); |
| 106 | expect(interestOriginAllowed(request(), { MERCH_INTEREST_SITE_ORIGIN: "https://codewhale.net/path" })).toBe(false); |
| 107 | const local = new Request("http://127.0.0.1:3100/api/merch/interest", { headers: { Origin: "http://127.0.0.1:3100" } }); |
| 108 | expect(interestOriginAllowed(local, {}, true)).toBe(true); |
| 109 | expect(interestOriginAllowed(local, {}, false)).toBe(false); |
| 110 | expect(interestOriginAllowed(new Request(local.url, { headers: { Origin: "http://localhost:3100" } }), {}, true)).toBe(false); |
| 111 | }); |
| 112 | |
| 113 | it.each(["http://127.0.0.1:3100", "http://localhost:3100", "http://[::1]:3100", "https://localhost:3100"])("permits explicit same-origin native preview at %s with production semantics", async (siteOrigin) => { |
| 114 | const localEnv = { ...env, MERCH_INTEREST_SITE_ORIGIN: siteOrigin }; |
| 115 | const local = new Request(siteOrigin + "/api/merch/interest", { method: "POST", headers: { Origin: siteOrigin, "Content-Type": "application/json" }, body: JSON.stringify(input()) }); |
| 116 | expect(interestOriginAllowed(local, localEnv, false)).toBe(true); |
| 117 | const response = await handleMerchInterest(local, localEnv); |
| 118 | expect(response.status).toBe(200); |
| 119 | expect(await response.json()).toEqual({ ok: true }); |
| 120 | expect(interestRecords()).toHaveLength(1); |
| 121 | const production = request(input(), { Origin: siteOrigin }); |
| 122 | expect(interestOriginAllowed(production, localEnv, false)).toBe(false); |
| 123 | expect((await handleMerchInterest(production, localEnv)).status).toBe(403); |
| 124 | expect(put).toHaveBeenCalledTimes(1); |
| 125 | }); |
| 126 | |
| 127 | it("blocks mismatched loopback ports and unencrypted public configured origins", () => { |
| 128 | const local = new Request("http://127.0.0.1:3101/api/merch/interest", { headers: { Origin: "http://127.0.0.1:3100" } }); |
| 129 | expect(interestOriginAllowed(local, { MERCH_INTEREST_SITE_ORIGIN: "http://127.0.0.1:3100" }, false)).toBe(false); |
| 130 | const publicHttp = new Request("http://codewhale.net/api/merch/interest", { headers: { Origin: "http://codewhale.net" } }); |
| 131 | expect(interestOriginAllowed(publicHttp, { MERCH_INTEREST_SITE_ORIGIN: "http://codewhale.net" }, false)).toBe(false); |
| 132 | }); |
| 133 | |
| 134 | it.each([ |
| 135 | { email: "invalid" }, { email: "a".repeat(250) + "@example.test" }, |
| 136 | { consent: false }, { consent: "true" }, { country: "" }, { country: "x".repeat(81) }, |
| 137 | { country: "China\nUS" }, { currency: "eur" }, { locale: "unknown" }, { website: "bot.example" }, |
| 138 | { picks: [] }, { picks: [{ id: "unknown" }] }, |
| 139 | { picks: [{ id: "mousepad" }, { id: "mousepad" }] }, |
| 140 | { picks: [{ id: "mousepad", priceChoice: "cheap" }] }, |
| 141 | { picks: [{ id: "mousepad", priceChoice: "low", surveyAmount: 0.01 }] }, |
| 142 | ])("rejects invalid payload %# without a write", async (patch) => { |
| 143 | expect((await handleMerchInterest(request({ ...input(), ...patch }), env)).status).toBe(422); |
| 144 | expect(put).not.toHaveBeenCalled(); |
| 145 | }); |
| 146 | |
| 147 | it("bounds actual bytes as well as Content-Length and checks the media type exactly", async () => { |
| 148 | const actual = new Request("https://codewhale.net/api/merch/interest", { method: "POST", headers: { Origin: "https://codewhale.net", "Content-Type": "application/json" }, body: JSON.stringify({ padding: "x".repeat(8192) }) }); |
| 149 | expect((await handleMerchInterest(actual, env)).status).toBe(413); |
| 150 | expect((await handleMerchInterest(request(input(), { "Content-Length": "8193" }), env)).status).toBe(413); |
| 151 | expect((await handleMerchInterest(request(input(), { "Content-Type": "application/jsonp" }), env)).status).toBe(415); |
| 152 | expect(put).not.toHaveBeenCalled(); |
| 153 | }); |
| 154 | }); |
| 155 | |
| 156 | describe("private merch interest list and deletion", () => { |
| 157 | async function signedIn(): Promise<{ auth: CommunityAgentEnv; headers: Record<string, string> }> { |
| 158 | const auth = { CURATED_KV: env.CURATED_KV, MAINTAINER_TOKEN: "local-maintainer-fixture" }; |
| 159 | const sid = await createSession(auth.CURATED_KV); |
| 160 | return { auth, headers: { Cookie: "mt_sid=" + sid } }; |
| 161 | } |
| 162 | it("requires a real stored maintainer session for reading or deleting contacts", async () => { |
| 163 | const response = await handleAdminMerchInterest(new Request("https://codewhale.net/api/admin/merch/interest"), env, { MAINTAINER_TOKEN: "fixture", CURATED_KV: env.CURATED_KV }); |
| 164 | expect(response.status).toBe(401); |
| 165 | expect(list).not.toHaveBeenCalled(); |
| 166 | expect(remove).not.toHaveBeenCalled(); |
| 167 | }); |
| 168 | it("paginates only the private prefix and deletes an opaque id with same-origin CSRF", async () => { |
| 169 | await handleMerchInterest(request(), env); |
| 170 | await handleMerchInterest(request({ ...input(), email: "second@example.test" }), env); |
| 171 | const { auth, headers } = await signedIn(); |
| 172 | const response = await handleAdminMerchInterest(new Request("https://codewhale.net/api/admin/merch/interest?limit=1", { headers }), env, auth); |
| 173 | expect(response.status).toBe(200); |
| 174 | expect(response.headers.get("Cache-Control")).toBe("no-store"); |
| 175 | const first = await response.json(); |
| 176 | expect(first.entries).toHaveLength(1); |
| 177 | expect(first.cursor).toBe("1"); |
| 178 | expect(first.entries[0].id).toMatch(/^[a-f0-9]{64}$/); |
| 179 | const second = await handleAdminMerchInterest(new Request("https://codewhale.net/api/admin/merch/interest?limit=1&cursor=1", { headers }), env, auth); |
| 180 | expect((await second.json()).cursor).toBeNull(); |
| 181 | const deleting = (origin: string, id: string) => new Request("https://codewhale.net/api/admin/merch/interest", { method: "DELETE", headers: { ...headers, Origin: origin, "Content-Type": "application/json" }, body: JSON.stringify({ id }) }); |
| 182 | expect((await handleAdminMerchInterest(deleting("https://evil.example", first.entries[0].id), env, auth)).status).toBe(403); |
| 183 | expect((await handleAdminMerchInterest(deleting("https://codewhale.net", "dispatch:latest"), env, auth)).status).toBe(422); |
| 184 | const removed = await handleAdminMerchInterest(deleting("https://codewhale.net", first.entries[0].id), env, auth); |
| 185 | expect(await removed.json()).toEqual({ ok: true }); |
| 186 | expect(interestRecords()).toHaveLength(1); |
| 187 | expect(list).toHaveBeenCalledWith({ prefix: PREFIX, limit: 1, cursor: "1" }); |
| 188 | }); |
| 189 | it("bounds admin pagination and omits corrupt or expired records", async () => { |
| 190 | await handleMerchInterest(request(), env); |
| 191 | const [key, serialized] = interestRecords()[0]; |
| 192 | records.set(key, JSON.stringify({ ...JSON.parse(serialized), expiresAt: "2000-01-01T00:00:00.000Z" })); |
| 193 | records.set(PREFIX + "a".repeat(64), "invalid fixture data"); |
| 194 | const { auth, headers } = await signedIn(); |
| 195 | expect((await handleAdminMerchInterest(new Request("https://codewhale.net/api/admin/merch/interest?limit=51", { headers }), env, auth)).status).toBe(422); |
| 196 | expect((await handleAdminMerchInterest(new Request("https://codewhale.net/api/admin/merch/interest?cursor=" + "x".repeat(2049), { headers }), env, auth)).status).toBe(422); |
| 197 | const response = await handleAdminMerchInterest(new Request("https://codewhale.net/api/admin/merch/interest", { headers }), env, auth); |
| 198 | expect((await response.json()).entries).toEqual([]); |
| 199 | }); |
| 200 | }); |
| 201 |