/** * A shaken report lands in Cotton's own database (src/feedback.ts): one * `app_report` row in the `cotton-product` object, written from POST * /v1/feedback on the open host, signed in or anonymous, the owner told by * an alert push. Synthetic numbers and bytes only; the fake APNs and FCM are * Calling's (test/calling.ts). */ import { env, runInDurableObject, SELF } from "cloudflare:test"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { CAPS, FEEDBACK_SLUG, LIMITS } from "../src/feedback.ts"; import { bearer, fakes, type Fakes, OPEN, open, signUp } from "./calling.ts"; type Body = Record; const tools = import.meta.glob("../../../crates/cotton-core/kits/developer/tools/app_reports/manifest.json", { eager: true, import: "default" }) as Record; const tables = import.meta.glob("../../../crates/cotton-core/kits/developer/tables/app_report.json", { eager: true, import: "default" }) as Record; const ADMIN = bearer("test-admin-token"); const OWNER = "+919800001001"; const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4]); const b64 = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes)); let ips = 0; const fromIp = (ip?: string): Record => ({ "cf-connecting-ip": ip ?? `203.0.113.${(ips += 1) % 250}` }); async function admin(method: string, path: string, body?: unknown): Promise<{ status: number; body: Body }> { return open(method, `/b/${FEEDBACK_SLUG}/v1/admin${path}`, body, ADMIN); } /** Cotton's own object, made as the coordinator's once-steps make it. */ async function makeCotton(owner: string | null = OWNER): Promise { const made = await admin("PUT", "/business", { name: "Cotton", kind: "business", currency: "INR", timezone: "Asia/Kolkata", ...(owner ? { owner_phone: owner } : {}) }); expect(made.status, JSON.stringify(made.body)).toBe(200); const defs = await admin("PUT", "/definitions", { tools: Object.values(tools), tables: Object.values(tables), flavour: { flavour: FEEDBACK_SLUG, name: "Cotton", public_views: {}, fan: null } }); expect(defs.status, JSON.stringify(defs.body)).toBe(200); } async function reports(): Promise { const out = await admin("GET", "/export"); return (out.body.rows as { table: string; id: string; data: Body }[]).filter((r) => r.table === "app_report").map((r) => ({ id: r.id, ...r.data })); } function report(extra: Body = {}): Body { return { id: crypto.randomUUID(), sentence: "The fan does not open on Notes", app: "notes", build: "1.4 (212)", platform: "ios", device: "iPhone16,1", os: "iOS 26.1", route: "/notes", ...extra }; } async function send(body: Body, headers: Record = {}): Promise<{ status: number; body: Body }> { return open("POST", "/v1/feedback", body, { ...fromIp(), ...headers }); } let world: Fakes; beforeEach(async () => { world = fakes(); // Each test starts from no Cotton object at all: the pool keeps one object's storage across a file's tests. await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(FEEDBACK_SLUG)), (_instance, state) => { for (const table of ["rows", "definitions", "meta", "feedback_hit"]) state.storage.sql.exec(`DELETE FROM ${table}`); }); }); afterEach(() => { vi.restoreAllMocks(); }); describe("POST /v1/feedback", () => { it("writes an anonymous report with its screenshot and log as media, and claims no number", async () => { await makeCotton(); const body = report({ screenshot: { type: "image/png", base64: b64(PNG) }, log: ["boot", "fan: opened"], sender_number: "+919800009999", sender: "signed_in" }); const res = await send(body); expect(res.status, JSON.stringify(res.body)).toBe(201); expect(res.body).toMatchObject({ id: body.id, status: "new", sender: "anonymous" }); const [row] = await reports(); expect(row).toMatchObject({ id: body.id, sentence: "The fan does not open on Notes", status: "new", app: "notes", build: "1.4 (212)", platform: "ios", device: "iPhone16,1", os: "iOS 26.1", route: "/notes", sender: "anonymous" }); expect(row!.sender_number).toBeUndefined(); expect(row!.sender_name).toBeUndefined(); expect(row!.chat_thread).toBeUndefined(); expect(typeof row!.made_at).toBe("string"); const shot = await env.PHOTOS.get(String(row!.screenshot)); expect(String(row!.screenshot)).toMatch(new RegExp(`^${FEEDBACK_SLUG}/feedback/[0-9a-f]{64}\\.png$`)); expect(new Uint8Array(await shot!.arrayBuffer())).toEqual(PNG); const log = await env.PHOTOS.get(String(row!.log)); expect(await log!.text()).toBe("boot\nfan: opened"); // Never public by key (ROUTES-AUDIT 15); the admin token reads it, uncached. const key = String(row!.screenshot); expect((await SELF.fetch(`https://example.test/b/${FEEDBACK_SLUG}/v1/photos/${key}`)).status).toBe(404); const read = await SELF.fetch(`https://example.test/b/${FEEDBACK_SLUG}/v1/admin/feedback/file?key=${encodeURIComponent(key)}`, { headers: ADMIN }); expect(read.status).toBe(200); expect(read.headers.get("cache-control")).toBe("private, no-store"); expect(new Uint8Array(await read.arrayBuffer())).toEqual(PNG); }); it("keeps a signed-in sender's number and name, as their own object vouches", async () => { await makeCotton(); const credential = await signUp("+919800001002", "dev-fb-1"); const res = await send(report({ sender_number: "+919800009999" }), bearer(credential)); expect(res.status, JSON.stringify(res.body)).toBe(201); expect(res.body.sender).toBe("signed_in"); const [row] = await reports(); expect(row).toMatchObject({ sender: "signed_in", sender_number: "+919800001002" }); }); it("refuses a bearer that is no good rather than making it anonymous", async () => { await makeCotton(); const bad = await send(report(), bearer("ctd_00000000-0000-4000-8000-000000000000_nope")); expect(bad.status).toBe(401); const mcp = await send(report(), bearer("ctn_00000000-0000-4000-8000-000000000000_nope")); expect(mcp.status).toBe(401); expect(await reports()).toEqual([]); }); it("answers a retry of the same id as the first, writing nothing twice", async () => { await makeCotton(); const body = report(); expect((await send(body)).status).toBe(201); const again = await send(body); expect(again.status).toBe(200); expect(again.body).toMatchObject({ id: body.id, duplicate: true }); expect(await reports()).toHaveLength(1); }); it("refuses what does not read: no id, no sentence, a bad app, platform or picture", async () => { await makeCotton(); expect((await send(report({ id: "nope" }))).body.code).toBe("bad_id"); expect((await send(report({ sentence: " " }))).body.code).toBe("bad_sentence"); expect((await send(report({ sentence: "x".repeat(CAPS.sentence + 1) }))).body.code).toBe("bad_sentence"); expect((await send(report({ app: "Not An App" }))).body.code).toBe("bad_app"); expect((await send(report({ platform: "windows" }))).body.code).toBe("bad_platform"); expect((await send(report({ screenshot: { type: "image/png", base64: b64(new Uint8Array([1, 2, 3])) } }))).body.code).toBe("bad_screenshot"); expect((await send(report({ screenshot: { type: "image/gif", base64: b64(PNG) } }))).body.code).toBe("bad_screenshot"); expect((await send(report({ log: [1, 2] }))).body.code).toBe("bad_log"); expect(await reports()).toEqual([]); }); it("caps the picture, the log and the request", async () => { await makeCotton(); const big = new Uint8Array(CAPS.screenshot + 1); big.set(PNG); let text = ""; for (let i = 0; i < big.length; i += 8192) text += String.fromCharCode(...big.subarray(i, i + 8192)); const shot = await send(report({ screenshot: { type: "image/png", base64: btoa(text) } })); expect(shot.status).toBe(413); const log = await send(report({ log: "y".repeat(CAPS.log + 1) })); expect(log.status).toBe(413); expect(log.body.code).toBe("log_too_large"); const whole = await SELF.fetch(`${OPEN}/v1/feedback`, { method: "POST", headers: { "content-type": "application/json", "content-length": String(CAPS.request + 1), ...fromIp() }, body: "{}" }); expect(whole.status).toBe(413); }); it("limits reports per IP and per number in an hour", async () => { await makeCotton(); const ip = { "cf-connecting-ip": "198.51.100.7" }; for (let i = 0; i < LIMITS.perIpHour; i++) expect((await send(report(), ip)).status).toBe(201); const over = await send(report(), ip); expect(over.status).toBe(429); expect(over.body.code).toBe("too_many_reports"); expect((await send(report(), { "cf-connecting-ip": "198.51.100.8" })).status).toBe(201); const credential = await signUp("+919800001003", "dev-fb-2"); for (let i = 0; i < LIMITS.perNumberHour; i++) expect((await send(report(), { ...bearer(credential), "cf-connecting-ip": `192.0.2.${i}` })).status).toBe(201); expect((await send(report(), { ...bearer(credential), "cf-connecting-ip": "192.0.2.200" })).status).toBe(429); }); it("says not ready, and keeps nothing, before Cotton's object is made", async () => { const res = await send(report()); expect(res.status).toBe(503); expect(res.body.code).toBe("not_ready"); }); it("pushes the owner's phones on each new report, and writes the row when nobody can be pushed", async () => { await makeCotton(); const owner = await signUp(OWNER, "dev-fb-owner"); const publicKey = b64(new Uint8Array(32).fill(7)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); const token = "ab".repeat(32); const put = await open("POST", "/v1/chat/device", { publicKey, platform: "ios", token, topic: "com.cottondb.cotton.dev", sandbox: true }, bearer(owner)); expect(put.status, JSON.stringify(put.body)).toBe(200); const res = await send(report({ sentence: "Books shows a blank shelf", app: "books" })); expect(res.status).toBe(201); expect(res.body.pushed).toBe(true); const push = world.pushes.find((p) => p.token === token)!; expect(push.verified).toBe(true); expect(push.headers["apns-topic"]).toBe("com.cottondb.cotton.dev"); expect(push.headers["apns-push-type"]).toBe("alert"); expect(push.body).toMatchObject({ aps: { alert: { title: "Report from books", body: "Books shows a blank shelf" } }, feedback: res.body.id }); }); it("writes the row and says pushed false when the owner has no phone to push", async () => { await makeCotton("+919800001004"); const res = await send(report()); expect(res.status).toBe(201); expect(res.body.pushed).toBe(false); expect(await reports()).toHaveLength(1); expect(world.pushes).toEqual([]); }); });