Cotton code
144 lines · 9.8 KB · TypeScriptRaw
/** * Paid plans for space (assets/design/shared/SPACE.md "Plans", 23 Nov 2026): the seam a payment provider's webhook * calls, driven by a fake provider whose secret only the tests bind. Every account and event is invented. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Business } from "../src/business.ts";import { applied, GRACE_MS, PLANS, stateOf, type HeldPlan, type PlanEvent } from "../src/plans.ts";import { FREE_BYTES, FRIEND_BYTES, GB, MOST_BYTES } from "../src/space.ts";import { ADMIN, http } from "./personal.ts";const OPEN = "https://cottondb.com";const DAY = 86_400_000;const PNG = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC"), (c) => c.charCodeAt(0));type Plan = { plan: string; bytes: number; status: string; until: number; grace_until: number } | null;type Space = { mode: string; bytes: number; allowance: number; bought: number; plan: Plan };async function open<T = Record<string, unknown>>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; body: T }> {  const res = await SELF.fetch(`${OPEN}${path}`, { method, headers: { "content-type": "application/json", ...headers }, body: body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body) });  const text = await res.text();  return { status: res.status, body: (text ? JSON.parse(text) : null) as T };}let ips = 140;async function signUp(phone: string): Promise<{ slug: string; auth: Record<string, string> }> {  ips += 1;  const ip = { "cf-connecting-ip": `198.51.100.${ips}` };  const code = await open<{ challenge_id: string; database_id: string }>("POST", "/v1/code", { phone, device_id: "phone-1" }, ip);  const signed = await open<{ credential: string }>("POST", "/v1/sign-in", { database_id: code.body.database_id, challenge_id: code.body.challenge_id, code: "123456", device_id: "phone-1" }, ip);  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  return { slug: `p-${code.body.database_id}`, auth: { authorization: `Bearer ${signed.body.credential}` } };}const object = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));function meta(slug: string, values: Record<string, string | null>): Promise<void> {  return runInDurableObject(object(slug), (instance: Business) => {    const store = (instance as unknown as { store: { setMeta(k: string, v: string | null): void } }).store;    for (const [k, v] of Object.entries(values)) store.setMeta(k, v);  });}const on = (slug: string) => http(slug, "POST", "/v1/admin/space/mode", { mode: "on" }, ADMIN);const spaceOf = async (a: { auth: Record<string, string> }) => (await open<Space>("GET", "/v1/space", undefined, a.auth)).body;const putPng = (slug: string, auth: Record<string, string>, key: string) =>  SELF.fetch(`https://example.test/b/${slug}/v1/media/${slug.slice(2)}/${key}`, { method: "PUT", headers: { ...auth, "content-type": "image/png", "content-length": String(PNG.length) }, body: PNG });async function sign(body: string, secret = "test-plans-fake-secret"): Promise<string> {  const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);  return [...new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body)))].map((b) => b.toString(16).padStart(2, "0")).join("");}let events = 0;/** The fake provider's webhook, signed as it signs. */async function told(event: Record<string, unknown>, secret?: string): Promise<{ status: number; body: Record<string, unknown> }> {  events += 1;  const body = JSON.stringify({ id: `evt_${events}`, ...event });  return open("POST", "/v1/plans/fake", body, { "x-fake-signature": await sign(body, secret) });}const iso = (ms: number) => new Date(ms).toISOString();describe("a plan's rules", () => {  const set = (over: Partial<PlanEvent> = {}): PlanEvent => ({ id: "e1", provider: "fake", subscription: "sub_1", account: "p-x", kind: "set", plan: "100gb", paid_through: 2_000, at: 1_000, ...over });  it("holds while paid for, then a grace, then nothing; the same event lands once and an older one changes nothing", () => {    const held = applied(null, set()) as HeldPlan;    expect(stateOf(held, 1_500)).toMatchObject({ plan: "100gb", bytes: PLANS["100gb"], status: "active" });    expect(stateOf(held, 2_000 + GRACE_MS - 1)).toMatchObject({ status: "grace", bytes: PLANS["100gb"] });    expect(stateOf(held, 2_000 + GRACE_MS)).toMatchObject({ status: "ended", bytes: 0 });    expect(applied(held, set())).toBe(held);    const older = applied(held, set({ id: "e0", plan: "2tb", at: 500 }))!;    expect(older.plan).toBe("100gb");    const ended = applied(held, { ...set({ id: "e2", at: 1_200 }), kind: "end" })!;    expect(stateOf(ended, 1_300)).toMatchObject({ status: "grace", until: 1_200, grace_until: 1_200 + GRACE_MS });    // The end of a subscription he left for another plan ends nothing.    const moved = applied(held, set({ id: "e3", subscription: "sub_2", plan: "1tb", at: 1_100, paid_through: 3_000 }))!;    expect(applied(moved, { ...set({ id: "e4", at: 1_150 }), kind: "end" })!.ended_at).toBeNull();  });});describe("the plans webhook", () => {  it("answers nowhere for a provider not bound, and refuses a bad signature", async () => {    expect((await open("POST", "/v1/plans/stripe", "{}")).status).toBe(404);    const a = await signUp("+15550170001");    const bad = await told({ type: "subscription.active", subscription: "sub_x", account: a.slug, plan: "10gb", paid_through: iso(Date.now() + 30 * DAY), at: iso(Date.now()) }, "not-the-secret");    expect(bad.status).toBe(401);    expect((await spaceOf(a)).plan).toBeNull();  });  it("sets a plan: the larger of the plan and the free space with friends, never past 2 TB; nothing changes with the switch off", async () => {    const a = await signUp("+15550170002");    const now = Date.now();    const set = await told({ type: "subscription.active", subscription: "sub_a", account: a.slug, plan: "100gb", paid_through: iso(now + 30 * DAY), at: iso(now) });    expect(set.status, JSON.stringify(set.body)).toBe(200);    // Off: the plan is kept, today's cap still holds.    const off = await spaceOf(a);    expect(off.plan).toMatchObject({ plan: "100gb", status: "active" });    expect(off.mode).toBe("off");    await on(a.slug);    expect((await spaceOf(a)).allowance).toBe(100 * GB);    // Friends give more than a small plan: the larger holds (a plan is a total, as the site prices it).    await meta(a.slug, { space_friends: "12" });    await told({ type: "subscription.renewed", subscription: "sub_b", account: a.slug, plan: "10gb", paid_through: iso(now + 60 * DAY), at: iso(now + 1) });    expect((await spaceOf(a)).allowance).toBe(FREE_BYTES + 12 * FRIEND_BYTES);    await told({ type: "subscription.renewed", subscription: "sub_c", account: a.slug, plan: "2tb", paid_through: iso(now + 60 * DAY), at: iso(now + 2) });    expect((await spaceOf(a)).allowance).toBe(MOST_BYTES);  });  it("ends a plan: its space holds through the grace; after it new files are refused and nothing is erased", async () => {    const a = await signUp("+15550170003");    await on(a.slug);    const now = Date.now();    await told({ type: "subscription.active", subscription: "sub_e", account: a.slug, plan: "10gb", paid_through: iso(now + 30 * DAY), at: iso(now - 40 * DAY) });    expect((await putPng(a.slug, a.auth, "photos/kept.png")).status).toBe(201);    await meta(a.slug, { media_bytes: String(5 * GB) });    // Ended ten days ago: in its grace, still 10 GB.    await told({ type: "subscription.ended", subscription: "sub_e", account: a.slug, at: iso(now - 10 * DAY) });    expect((await spaceOf(a)).plan).toMatchObject({ status: "grace", bytes: 10 * GB });    expect((await putPng(a.slug, a.auth, "photos/in-grace.png")).status).toBe(201);    // Past the grace (an end older than 30 days, as a renewed then ended plan's would be).    await meta(a.slug, { space_plan: null });    await told({ type: "subscription.active", subscription: "sub_f", account: a.slug, plan: "10gb", paid_through: iso(now - 50 * DAY), at: iso(now - 80 * DAY) });    await told({ type: "subscription.ended", subscription: "sub_f", account: a.slug, at: iso(now - 50 * DAY) });    const ended = await spaceOf(a);    expect(ended.plan).toMatchObject({ status: "ended", bytes: 0 });    expect(ended.allowance).toBe(FREE_BYTES);    const refused = await putPng(a.slug, a.auth, "photos/after.png");    expect(refused.status).toBe(413);    expect(await refused.json()).toMatchObject({ code: "space_full" });    expect(ended.bytes).toBe(5 * GB + PNG.length);    const kept = await SELF.fetch(`https://example.test/b/${a.slug}/v1/media/${a.slug.slice(2)}/photos/kept.png`, { headers: a.auth });    expect(kept.status, "what was kept still reads").toBe(200);  });  it("lands the same event once, and never makes an account", async () => {    const a = await signUp("+15550170004");    const body = JSON.stringify({ id: "evt_same", type: "subscription.active", subscription: "sub_s", account: a.slug, plan: "1tb", paid_through: iso(Date.now() + DAY), at: iso(Date.now()) });    const first = await open("POST", "/v1/plans/fake", body, { "x-fake-signature": await sign(body) });    const again = await open("POST", "/v1/plans/fake", body, { "x-fake-signature": await sign(body) });    expect([first.status, again.status]).toEqual([200, 200]);    expect((await spaceOf(a)).plan).toMatchObject({ plan: "1tb" });    const nobody = await told({ type: "subscription.active", subscription: "sub_n", account: "p-00000000-0000-4000-8000-000000000000", plan: "10gb", paid_through: iso(Date.now() + DAY), at: iso(Date.now()) });    expect(nobody.body).toMatchObject({ ok: true, events: [{ applied: false }] });  });});